text:
Arduino Ping sensor with NewPing library
I was trying out the NewPing library (the main example sketch) and when I compile it and check the serial monitor, it seems like it works for about 10 seconds, then instead of giving distance values it just writes out random characters. The only thing I can think of is that my sensor is bad. Any suggestions before I get another Ping sensor? I'm unsure if the same thing will happen.

The main example sketch has this:
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.

Your serial monitor is set to 9600 baud (bottom RH corner). Change that to match the setting in the sketch.


text:
Serial.println for pointers to the byte datatype behaves unexpectedly
byte subkeys[16][48/8];

for (size_t address = 0; address < 16*6; address++)
    Serial.println( (byte) *(subkeys + address) );

Why won't the compiler handle this? It tells me

cast from 'byte* {aka unsigned char*}' to 'byte {aka unsigned char}' loses precision [-fpermissive]

If I omit the (byte) part, it tells me

call of overloaded 'println(byte [6])' is ambiguous

I have no idea what's happening.

A byte is to small to store a pointer value. Instead to casting to
byte, you should cast to uintptr_t, which is guaranteed to be large
enough. On an AVR-based device like the Uno, this is the same as
uint16_t or unsigned int, but uintptr_t is more general.
Edit: From your comment it would seem you want to print the contents
of the array instead of the addresses of the rows. The obvious way is to
loop with two indices:
for (size_t i = 0; i < 16; i++) for (size_t j = 0; j < 6; j++)
    Serial.println(subkeys[i][j]);

If you really want to use subkeys as a 1D array, then cast it to a
byte *, which is the type a 1D array would naturally decay to:
for (size_t address = 0; address < 16*6; address++)
    Serial.println(((byte *) subkeys)[address]);

But *(subkeys + address) is not a pointer. It is a value in subkeys array. Am I wrong?

No, subkeys is an array of arrays of bytes, then *subkeys (as well as subkeys[address], which is a nicer syntax for *(subkeys + address)) is an array of 6 bytes. In most cases, arrays decay to pointers when you use them. You should probably start by telling us what you want to achieve.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Problem receiving CAN messages using arduino, MCP2515 CAN module and multiprotocol radio shield
I am using an arduino UNO and a Cooking Hacks CAN BUS module through a Cooking Hacks Multiprotocol radio shield. I plan to read the CAN messages through the car's OBD-II port. I have connected the components according to the tutorial and though there is no LED to indicate that the shield and CAN bus module are ON, I verified that they are indeed ON by using a multimeter. Also, when the reset button is pressed on either the shield or the CAN module, the arduino resets so I guess they are powered up. Coming to my problem, I uploaded the code and connected the setup to the OBD-II port and turned the ignition ON. I expected to see the CAN messages on the arduino serial monitor but I didn't see anything. I also took up this issue with the cooking hacks support team who told me that the libraries were updated and that I should use the updated ones. So I downloaded the revised libraries to use with my code but I am unable to upload the code itself to the arduino because of an error during compilation.
C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\arduinoCAN.cpp:26:49: fatal error: ../arduino-api/arduinoMultiprotocol.h: No such file or directory
The major difference as far as I can tell between the old and the new libraries is the addition of two lines in the arduinocan.cpp file :
include "../arduino-api/arduinoMultiprotocol.h"
include "../arduino-api/arduinoUtils.h"
Both of these are header files in another library that was included as part of the whole library that you can download from their website.
I realise I might have confused whoever's reading but please have a look at the arduino code. Hopefully, that should clear things up. Any help would be highly appreciated. Thanks.
Code:
    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    // Create an instance of the object
    CAN myCAN = CAN();

    // Setting up our devices and I/Os
    void setup() {
    // Using the Socket 0 onto which Can bus module is plugged in
    Utils.setONSocket0();
    Utils.setMUXSocket0();
    // Initializes the UART
    Serial.begin(115200);
    delay(100);

    myCAN.begin(500); // Start talking to the BUS. Speed= 500 Kbps
    }

    void loop() {
    // 1. Receive data

    if (myCAN.messageAvailable()) {
    // Read the last message received.
    myCAN.getMessage(&myCAN.messageRx);
    // Print in the serial monitor the received message
    myCAN.printMessage(&myCAN.messageRx);
     }
    }

EDIT: PROBLEM SOLVED!
Putting the header file's full path in the sketch did not solve it. The compiler still displayed the same error. I then made a backup copy of all the files containing the #include "arduinoMultiprotocol.h" statement and edited them to contain the full path. Initially, the error didn't change and I moved onto the next suggestions, all of which did not change the error. However, I went back to the edited files and replaced the backslash() with the slash(/). This time, the compiler did not throw the same error, instead saying it cannot find arduinoUtils.h.
So I proceeded to do the same thing with arduinoUtils.h, editing all the files containing it to mention the full path. And this time it worked and the sketch works as well. Thanks for your help!

We have a SE site specifically devoted to Arduino-specific issues. Migrating.

The compiler is saying it can't find the header files. The part of the path ../arduino-api/ is suspicious.
It may be because the header files are expected to be somewhere else, or their is a small error which has had a knock on effect.
1 - Find arduinoMultiprotocol.h
Put its full path into the include statement, e.g.
    #include "C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\wibble\arduinoMultiprotocol.h"

If that is still broken, but a new error is printed, copy the error. If the error doesn't change, then make a backup copy of every file you can find containing #include <arduinoMultiprotocol.h> and edit it to contain the full path. It looks like starting with arduinocan.cpp is a good place to start.
2 - If that doesn't fix the error, create an empty sketch, including all those headers, e.g.
    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    void setup() { }

    void loop() { }

Compile and copy the error message.
Move the #include <arduinoMultiprotocol.h> a bit later in the sequence of #includes. If the error changes copy that for later, and record which sequence changed it.
3 - Change #include <arduinoMultiprotocol.h> in that empty sketch
to the full path (as in step 1). If that doesn't fix it, copy that error message.
If you still need help, please update your question with the results of those tests.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
text to 2D array on Arduino
I am trying to read a text file and send the info to 2D array, but after loading the array, it reads all zeroes. What can I do to stop the Arduino from doing this and get the array with my required data?
/* This program was created by ScottC on 8/5/2012 to receive serial signals from a computer to turn on/off 1-9 LEDs */

int** ptr;

void setup() {
  // initialize the digital pins as an output.
  pinMode(13, OUTPUT);
  // Turn the Serial Protocol ON
  Serial.begin(9600);
}

void loop() {
  byte byteRead;

  if (Serial.available()) {

    /* read the most recent byte */
    byteRead = Serial.read();
    //You have to subtract '0' from the read Byte to convert from text to a number.
    byteRead = byteRead - '0';
    ptr = new int* [byteRead];

    int i,j;
    for ( i = 0; i < byteRead; i++) {
      ptr[i] = new int[3];
      for ( j = 0; j < 3; j++) {
        if (Serial.available()) {

            /* read the most recent byte */
            byteRead = Serial.read();
            //You have to subtract '0' from the read Byte to convert from text to a number.
            byteRead = byteRead - '0';
            ptr[i][j] = byteRead;
            Serial.print(ptr[i][j]);
        }
      }
    }
  }
}

I see nothing there at all to do with text files, and the whole program looks somewhat daft. Please take a step back from the program and think about what you want to achieve before dumping someone else's code on us.

For reading serial data on the Arduino you should really read this to clear up some of your bad misconceptions: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

There are several issues with your code but instead of correcting I recommend that you start by checking that your assumptions about the format is correct. Send your data to this "reduced" variant of your sketch. Does it work? Did you receive what you expected?
void setup() {
  // initialize the digital pins as an output.
  pinMode(13, OUTPUT);
  // Turn the Serial Protocol ON
  Serial.begin(9600);
}

void loop() {
  byte byteRead;

  if (Serial.available()) {

    /* read the most recent byte */
    byteRead = Serial.read();
    //You have to subtract '0' from the read Byte to convert from text to a number.
    byteRead = byteRead - '0';
    Serial.print(F("byteRead = "));
    Serial.println(byteRead);

    int i,j;
    for ( i = 0; i < byteRead; i++) {
      for ( j = 0; j < 3; j++) {
        if (Serial.available()) {

            /* read the most recent byte */
            byteRead = Serial.read();
            //You have to subtract '0' from the read Byte to convert from text to a number.
            byteRead = byteRead - '0';
            Serial.print(i);
            Serial.print(':');
            Serial.print(j);
            Serial.print(F(":byteRead = "));
            Serial.println(byteRead);
        }
      }
    }
  }
}

Did you see the issue with:
    for ( i = 0; i < byteRead; i++) {
    ...
    }

Cheers!

The worst part of that code is the bit that reads `for ( j = 0; j < 3; j++) {
if (Serial.available()) {
        /* read the most recent byte */
        byteRead = Serial.read();`


text:
Is it possible to control a 12v led matrix with an arduino?
This is a bit home automation but if I want to control my 12v LEDs and I have 8 free pins would it be possible to drive 16 lights as a matrix. I was looking into running 8 LEDs with an 8 channel relay but the I got to thinking if I wire up 16 LEDs in a matrix I could still control them all with those 8 channels. Problem is I was looking at mechanical relays that would burn out very quickly with that kind of switching. Are there any other solutions?

Why mechanical relays? since they are 12V leds you will need 12 MOS (4 nMOS on the columns, 4 pMOS on the rows and 4 more nMOS to pull the pMOS gate to ground (since your arduino can output at most 5V). they are much cheaper than relays, much smaller, much faster and will last much longer...

I originally found the relays that we rated for ac and DC and it seemed nice to have the option.I started looking into solid state relays but couldn't find a balance between price, quality, and available datasheets. I'm way more of a software guy so that explains why transistors slipped my mind

If you want AC support then you'll definitely need to wire them one by one, or you'll maybe get some weird behavior. As for relays, you will not be able to use them in a matrix. The reason, apart from the wearing, is that a common relay needs 10-20ms to switch, and you will need at least 200 flashes per second (but more is much better) to get an acceptable light. I mean, if you turn on an led for 10ms and then off for 30ms (100Hz switching frequency) your light will blink at 25Hz, and your eye will see the light "flashing", which is really tiring for the eyes. So.. Just go with transistors ;)

@frarugi87 Yes, thanks again, I decided 120vac would be many more problems than it's worth and I have a main priority of not burning the house down :)

@JacobKern How's your project going? Did the answer lead to a solution?

You can use ULN2803 driver IC on sink side (cathode), P channel MOSFET on anode/source side of common anode LED matrix. Since you need only 4 sinks you can pair every 2 i/o of ULN2803 so you can drive/sink 1A max load per row. This IC is cheap and widely available.
MOSFET current and speed should match those of ULN2803. You can use BJT instead of MOSFET, but voltage drop on BJT will be higher.
Similar design is here: 8x8 LED matrix

The real gem is your similar design. It shows two daisy-chained shift registers. So with the 4 pins, you can drive the two shift registers, who drive the P-channel and ULN2803. Effectively 8x8 with only 4 inputs and it's even very scaleable.

I think the best solution would be to use WS2812 LEDS. I already implemented this many times also for my home illumination.
WS2812 is a RGB LED with an integrated chip (1m strip with 60 LED will cost about 10$).
One advantage is that you need only 1 output from your Arduino and the library works very well.
Another one is that you don't need power! 5mA is enough to drive 1000 LEDS! So you don't need MOSFETS and you don't need any Relais.

I would choose an SPI based digital ledstrip. They're easier to control with various devices and leave soms time inbetween setting pixels to be able to calculatie the next one. Which is much more memory efficiënt.


text:
Why is my SRAM so quickly filled? There are not more than 60 bytes
I have just gone through all my code. At max I use 60 bytes. I have done everything in order to minimize its usage - I even store booleans as bits, not bytes! What could be happening here?
The only thing that comes to my mind are extremely large arrays, like this:
const uint8_t SBoxes[8][4][16] PROGMEM;

However, these are stored in the program memory as you can see. How can I check they are really there and my memory usage? My code is too large to post it here.
EDIT:
IDE tells me (even though I believe it's very inaccurate):

Sketch uses 7,898 bytes (24%) of program storage space. Maximum is 32,256 bytes.
  Global variables use 1,023 bytes (49%) of dynamic memory, leaving 1,025 bytes for local variables. Maximum is 2,048 bytes.

All my literal strings use F() and there are not many of them.
EDIT2:
Code on pastebin. Just for a quick glance, it is really large.
EDIT3:
My Serial prints
ready
some numbers (that's ok I ask it to print out an array)
ENready
again numburs
Enready
...

I ask it to print ready at the very beginning of my program. I ask it to println End of encr near the end of my setup funciton, but as you see it never finishes the printing.
It always behaves like that when I run out of SRAM.

What does the IDE say how much space was used?

Please post the data declarations. Check that all literal strings use F().

I updated my question. Please, see the EDIT.

What does avr-nm -Crtd --size-sort your_elf_file tell you? Look at symbols of type D, B and V.

On what kind of file should I call it? All I have are .ino files. And it doesn't take my project file as an argument. It tells me it 'is not an ordinary file'.

Build the program with the “verbose compilation” option activated. You will see the IDE creates a file with a .elf extension in a temporary directory. That's the file you should give to avr-nm.

You are also using the LiquidCrystal library and Serial (which uses a 64 byte buffer). Removing all else, you end up with about 260 bytes already. Though, I have no idea where the other 750 bytes go to.

Oh I see, you have just taught me something new. Here it is on Pastebin

About the Serial and LiquidCrystal: Yeah, I forgot about it. Thank you for pointing about, but I am afraid not even this solves the riddle.

If you want to learn a lot of details about the 1975 Data Encryption Standard (DES), implementing it from scratch will teach you a lot. However, if your goal is to actually encrypt something, perhaps it would be better to (a) use a more modern cipher such as Twofish or AES; or (b) use a pre-existing library; or both. See Spaniakos, AESLib, AES-library, etc.

When you are asking yourself what is eating so much RAM, the first step
is to look at the symbol table in the ELF file. If you use a makefile, you
probably know where to find the ELF file. If you are using the Arduino
IDE, go to File / Preferences, check “Show verbose output during
compilation”, compile and look at the output: you will see the temporary
directory where the compiler puts your ELF file.
Now run the command avr-nm -Crtd --size-sort your_elf_file and look
for symbols of type 'D' (data), 'V' (vtable) and 'B' (BSS), in either
upper or lower case. On a Unix-style OS you would pipe through
grep -i ' [dbv] '. Running this on your program gives:
00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000021 B lcd
00000016 V vtable for HardwareSerial
00000008 V vtable for LiquidCrystal
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 D __malloc_margin
00000002 D __malloc_heap_start
00000002 D __malloc_heap_end
00000002 B __flp
00000002 B __brkval
00000001 b timer0_fract
00000001 D encr
00000001 B debug
00000001 B EEPROM

Obviously, this cannot account for the 1,023 bytes of static RAM your
program is using. What this command misses is the literal arrays and
strings. These can be seen with the command
avr-objdump -j .data -s your_elf_file. The literal strings are quite
obvious in the output, the literal arrays less so. Running this on your
program gives a long listing starting with
Contents of section .data:
800100 00000005 2000010e 040d0102 0f0b0803  .... ...........
800110 0a060c05 09000700 0f07040e 020d010a  ................

Now, on the source code we see:
const uint8_t SBoxes[8][4][16] PROGMEM = {
{{14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
 { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
 { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
 {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13} },
 ...

If you translate this to hexadecimal, you get 0e 04 0d 01 02 0f...,
which appears also by the end of the first line of previous listing. So
there is your culprit: all the big PROGMEM arrays. The compiler does not
honor the PROGMEM attribute on local variables.
My first thought was to make the arrays global, and this does solve the
problem. However, as pointed out by Mikael Patel in a comment, the
documentation on PROGMEM states that “variables must be either globally
defined, OR defined with the static keyword, in order to work with
PROGMEM.” Then, making the arrays static const PROGMEM is a cleaner
solution.

It can't. It doesn't make sense to.

I tested simply defining them as "static" where they stand and data size drops to 311 bytes.

I tried to take them out of the functions to make them global. To make sure the library works I called the input rigth above the arrays. As you can see the IDE says something different (Sketch uses 7,788 bytes (24%) of program storage space. Maximum is 32,256 bytes.
Global variables use 399 bytes (19%) of dynamic memory, leaving 1,649 bytes for local variables. Maximum is 2,048 bytes.). But it is still out of SRAM - the program loops its Serial the same way as before.

There is actually a line in the Arduino PROGMEM documentation about this "Please note that variables must be either globally defined, OR defined with the static keyword, in order to work with PROGMEM." https://www.arduino.cc/en/Reference/PROGMEM

But it is still out of SRAM - the program loops its Serial the same way as before. - let's not jump to conclusions now. What do you mean "loops its Serial" exactly?

Is it printing fff a lot? Well, you told it to do that.

I use the Serial input for debugging. Once it starts printing gibberish or looping (that means it prints something and starts again from the beginning of the program) I know I have run out of SRAM. No, I mean in Serial, fff is for the lcdDisplay - it never comes to the command anyway, it starts looping before.

Please edit your question and paste into it what it is actually printing. We are now trying to guess what you are getting at.

I have just editted it to make it more clear, good idea.

To elaborate on Edgar Bonet's answer and my comment under it, you cannot usefully put PROGMEM variables as local variables because local (non-static) variables have to be allocated on the stack.
void lookUpInSBox(size_t which, byte *address, byte* binaryOutcome, size_t addressFrom){

   ...

    const uint8_t SBoxes[8][4][16] PROGMEM = {

                             /*S1*/

   { {14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
     { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
     { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
     {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13}    },

You could make them global. But if you prefer  not to do that, put static in front of them. Doing that on your code reduced it to 247 bytes.
Global variables use 247 bytes (12%) of dynamic memory, leaving 1,801 bytes for local variables. Maximum is 2,048 bytes.

You expect a bit more than the 60 you counted. The serial buffers take a bit (128 bytes).
See Putting constant data into program memory (PROGMEM) for more information. On a tiny sketch I found the following 346 bytes already in use:

34 bytes for the HardwareSerial instance (Serial)
64 bytes for the Serial transmit buffer
64 bytes for the Serial receive buffer
4 bytes for the Serial transmit buffer head and tail pointers
4 bytes for the Serial receive buffer head and tail pointers
9 bytes for keeping track of millis / micros
4 bytes for memory allocation (__malloc_heap_start, __malloc_margin)
128 bytes for the heap safety margin
6 bytes for a few nested function calls (main -> setup -> getFreeMemory)
16 bytes for the compiler vtable for HardwareSerial
4 bytes for variables __brkval and __flp (used in memdebug)
2 bytes pushed onto the stack in main (to save registers)
2 bytes pushed onto the stack in setup (to save registers)
4 bytes pushed onto the stack in getFreeMemory (to save registers)
1 byte because the stack pointer starts at 0x8FF rather than 0x900

The sketch on my page used dynamic memory allocation so it used a bit more than yours does (for keeping track of it).

Once it starts printing gibberish or looping (that means it prints something and starts again from the beginning of the program) I know I have run out of SRAM

I'm a bit puzzled by all the new/delete you are doing. Why do that? For example:
byte *E;
E = new byte[48/8];
for(size_t i = 0; i < 48; i++){
    insertBit( E, i, bitValue( R, E_BIT[i]-1 ) );
}

// XOR Kn and  E(Rn-1)
byte KxorE[48/8];
for (size_t i = 0; i < 48; i++){
    insertBit( KxorE, i, bitValue( K, i ) ^ bitValue( E, i ) );
}
delete[] E;

Massive amounts of dynamic memory allocation may fragment memory. Can't you rewrite to not do that? You can pass arrays by reference, it just seems weird (and slow) to do all that allocation.

You mean like const uint8_t SBoxes[8][4][16] PROGMEM? I have tried it and although the IDE lowered the numbers of memory usage, the program still loops its Serial input - it is still out of SRAM :( Even if I add your additional bytes to my numbers we get nowhere near 2000.

I don't understand that. Therefore it is not out of SRAM, unless you dynamically allocate memory a lot. See my comment under Edgar Bonet's answer.

See my amended answer about dynamic allocation.

I need both of the E and KxorE arrays. What I can do is not to delete them, but not much more. Originally I was worried about the SRAM so I deleted everything I could. Of course I am going to optimalize its speed, but only when it runs. But thank you for that tip, I didn't know memory allocation would be that slow.

It's not that slow but it is slower than not doing it. If you use local variables rather than dynamic ones, then you save the allocation / deallocation. You would need to modify the functions to take an argument by reference, or pass a pointer (depending on whether or not the function modifies the argument).

If you redesign to not use dynamic memory, at least you know that once you have enough memory at the start, you won't use any more of it.

Yeah, I know. Maybe you have noticed that in order to save even more bytes I use the EEPROM. Well, I can't save more space. That means that even reprogramming it would be useless.

What do you mean you "can't save more space"? If you switch from dynamic allocation to using static arrays, it should work. You have heaps of RAM free (only using 12% at present).

Ok, I guess I don't understand the heap anymore. I thought that pretty much the stack and the heap both occupy the same space - one on each end and the program collides once they have no more space between them. But basically it doesn't matter if I have int[5] or new int[5]. I am going to rewrite it to static arrays.

I've been just told that if I save the arrays in PROGMEM I need to use pgm_read_byte / pgm_read_word to read them. Might this solve the problem?

@SlowerPhoton: “it doesn't matter if I have int[5] or new int[5].”. With the former, there is no risk of memory fragmentation, and there is no risk of you forgetting to delete the array. And to answer your last comment, not using the pgm_read_*() functions is clearly a bug. Whether it's the only bug in your program, I cannot say.

I've been just told that if I save the arrays in PROGMEM I need to use pgm_read_byte / pgm_read_word to read them. - absolutely. They are different address spaces. I didn't look at your code in that level of detail to notice that you weren't.


text:
How to read data from PC
I'm new to Arduino.
I'm passing some data from my Android phone to my Macbook via bluetooth (throught the app Sensoduino).
What I'd like to do now is to export that data to my Arduino Mini Pro.
Is there any way to achieve it?
(NOTE: I'm not able to connect my Android Phone directly to the Arduino via Sensoduino)

Could you please add more detail about what bluetooth hardware for example you are using. Also, could you elaborate a bit what "export that data to my Pro Mini" means?

A simple bluetooth module like a HC-05 wired to your Arduino will give you a  serial stream that can be read and/or written.
With the RX/TX connected to say pins 10 & 11, a SoftwareSerial() object will provide access:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
    mySerial.begin(9600);
}

void loop()
{
    int value;

    if (mySerial.available(sizeof(int)))
    {
        value = mySerial.parseInt();
    }
}

If you connect the module to pins 0 & 1 - you can just use the Arduino standard Serial functions, but it will cause problems uploading to the board.  In which case you would disconnect the bluetooth module for uploading.


text:
Help Understanding FFT Analysis and analogRead()?
Here's the deal, I'm attempting to learn how to use an FFT (Fast Fourier Transformation) Library for sound analysis (link is here). My issue is that this comes with included C++ code to show users how to use the FFT library. There are three examples, but I'll show this one because it's closest to the application I have planned for it:
/*
fft_adc_serial.pde
guest openmusiclabs.com 7.7.14
example sketch for testing the fft library.
it takes in data on ADC0 (Analog0) and processes them
with the fft. the data is sent out over the serial
port at 115.2kb.
*/

#define LOG_OUT 1 // use the log output function
#define FFT_N 256 // set to 256 point fft

#include <FFT.h> // include the library

void setup() {
  Serial.begin(115200); // use the serial port
  TIMSK0 = 0; // turn off timer0 for lower jitter
  ADCSRA = 0xe5; // set the adc to free running mode
  ADMUX = 0x40; // use adc0
  DIDR0 = 0x01; // turn off the digital input for adc0
}

void loop() {
  while(1) { // reduces jitter
    cli();  // UDRE interrupt slows this way down on arduino1.0
    for (int i = 0 ; i < 512 ; i += 2) { // save 256 samples
      while(!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fft_input[i] = k; // put real data into even bins
      fft_input[i+1] = 0; // set odd bins to 0
     }
    fft_window(); // window the data for better frequency response
    fft_reorder(); // reorder the data before doing the fft
    fft_run(); // process the data in the fft
    fft_mag_log(); // take the output of the fft
    sei();
    Serial.println("start");
    for (byte i = 0 ; i < FFT_N/2 ; i++) {
      Serial.println(fft_log_out[i]); // send out the data
    }
  }
}

Now, with that said, I have a very general grasp of the idea that those lines referencing some variable called ADMUX and ADCSRA have to do with the analogRead() method and that the ADCH and ADCL refer to another two components that are combined to provide the returned integer that analogRead() spits out. What I don't understand whatsoever are those seemingly random strings of characters that these are being set equal to. For example, what does 0x40 or 0x01 or 0xe5 even refer to in the setup() method (if nothing else maybe somebody could point me in the right direction for this, because that part I really am entirely clueless about). And furthermore, why manipulate these directly in the first place, because if you reference the source code for analogRead() they look awfully similar. Thanks for any help in advance!

All is explained in Chap. 24 http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf,

The register-level manipulations are trying to optimize the sampling rate to be faster than you get out of analogRead() sampling rate.

The random values in ADMUX differ, depending on the chip, but it can choose the pin, internal sensors, reference voltage, etc... What they really mean depends on the datasheet.

It would have been preferable if the author of that code had used proper bit masks. For example:
  ADCSRA = 0xe5; // set the adc to free running mode

Looking at the datasheet:

Now, 0xe5 is 11100101 in binary.
So that line could have been written:
  ADCSRA = bit (ADEN) | bit (ADSC) | bit (ADATE) | bit (ADPS2) | bit (ADPS0);

The last two (ADPS2 and ADPS0) give the prescaler (of 32):

The other bits are explained in the datasheet:

Bit 7 – ADEN: ADC Enable
Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off. Turning the ADC off while a
conversion is in progress, will terminate this conversion.
Bit 6 – ADSC: ADC Start Conversion
In Single Conversion mode, write this bit to one to start each conversion. In Free Running mode, write this bit to
one to start the first conversion. The first conversion after ADSC has been written after the ADC has been
enabled, or if ADSC is written at the same time as the ADC is enabled, will take 25 ADC clock cycles instead of
the normal 13. This first conversion performs initialization of the ADC.
ADSC will read as one as long as a conversion is in progress. When the conversion is complete, it returns to
zero. Writing zero to this bit has no effect.
Bit 5 – ADATE: ADC Auto Trigger Enable
When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a
positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits,
ADTS in ADCSRB.

You can work through the other registers in a similar way.

Nick Gammon already gave a very fine answer about the meaning of the
mysterious numbers you were wondering about. Here I am trying to answer
only your last question:

why manipulate these directly in the first place, because if you
  reference the source code for analogRead() they look awfully similar.

One of the reasons is, as Dave X said in a comment, to get a higher
sample rate. Assuming this is an Arduino Uno or similar (ATmega328P @
16 MHz), the Arduino core normally configures the ADC prescaler to 128.
This gives a conversion time of 104 µs (equal to 13 × prescaler ÷
F_CPU), and a maximum sample rate of about 9.6 kHz. This is fine for
telephone quality audio, but insufficient for hi-fi applications. This
example code sets the prescaler to 32 for a conversion time of 26 µs and
a maximum sample rate around 38 kHz. According to Atmel, the ADC should
work fine with this kind of sample rate, except that you should not
expect to get the full resolution.
The main reason, however, is not to get a fast sample rate, but rather
to get a consistent sample rate. The problem with analogRead() is
that it is a blocking function. If you look at its source code you
will see a busy wait like this:
// ADSC is cleared when the conversion finishes
while (bit_is_set(ADCSRA, ADSC));

This means that the CPU is not doing anything useful while waiting for
the ADC to finish the conversion. If you do analogRead() in a loop,
the CPU will wait for the ADC, then the ADC will be idle while the CPU
completes the loop and so on. The conversion period is then the time
required by the ADC plus the time taken by the CPU to loop. And the
CPU time is hard to predict because it can be influenced by interrupts
and by conditional branches inside the loop.
This code, in contrast, configures the ADC to work in free running
mode. In this mode, the ADC starts a new conversion as soon as the
previous one is done. This way you get a steady sample rate while the
ADC and the CPU work in parallel. In the loop you see these lines:
while(!(ADCSRA & 0x10)); // wait for adc to be ready
ADCSRA = 0xf5; // restart adc

The comments are a bit misleading. The first line (which I would rather
write loop_until_bit_is_set(ADCSRA, ADIF);) waits for a flags that is
set when the current conversion is done and the data register updated.
The next line does not restart the ADC (it restarted itself, as it is in
free running mode): it only clears the flag so that it can be
meaningfully tested on the next iteration.
Now, I have a few comments on this code that are not directly related to
your question, but may be useful if you are going to build your program
on this basis.
First, it should be noticed that the whole ADC-reading loop is done with
interrupts disabled. This is not normally needed, as the free running
mode gives you a steady sampling even if the CPU timing is somewhat
jittery. The only valid reason I see for disabling interrupts is if
one of your ISRs takes so long to execute that you may miss one sample.
This could very well be the case with such a high sampling frequency.
But still, there is no point in keeping the interrupts disabled during
the FFT processing. And there is no point in turning off Timer 0 if you
are disabling interrupts anyway.
My second point is about the three lines starting with byte m = ADCL;.
Those are meant to read the ADC data register in the proper order: low
byte first. However, the C compiler is well aware of the proper way to
do read a 16-bit I/O register (see “Accessing 16-bit Registers” in the
datasheet chapter about Timer 1). Thus, these three lines can be
simplified to just int k = ADC;.
My last point is that having the CPU left adjust the result (k <<= 6)
takes some time, as it is implemented as a loop. There is no point in
doing this when the ADC can do it for free: you just have to set the
ADLAR bit when configuring ADMUX in setup(). Then the 5 lines starting
with byte m = ADCL; would be reduced to
int k = ADC - 0x8000;  // ADC reading as a 16 bit signed int

An excellent answer from Edgar Bonet. My reply described how to interpret the bit patterns. This reply goes into a lot more detail about the meaning of them.

authors: إبراهيم السمطي


text:
Mysterious behavior when using objects
I am writing a project that involves using complementary filters to combine gyroscope and accelerator readings in 3 directions. The relevant code is below.
class CompFilter {
 public:
   long prevTime;
   float alpha;
   int angle;

   CompFilter(float Alph);
   int combine (float gyroRate, float accelAngle);
};

CompFilter::CompFilter(float Alph) {
 alpha = Alph;
 prevTime = 0;
 angle = 0;
}

int CompFilter::combine(float gyroRate, float accelAngle){
  Serial.println("Here THREE");

 long timeStep = millis() - prevTime;
 if (timeStep == 0) { timeStep = 1;}

 angle = alpha * (angle + gyroRate * timeStep);

 angle += (1.0 - alpha) * accelAngle;

 prevTime = millis();

 return angle;
}

//Global Objects
CompFilter *senPitch; CompFilter *senRoll;  //Declare Complementary Filters

//Adjustable Parameters
float alpha = .5;   //Constant affecting Gyro's vs. Accel's influence on sensor reading

void setup(void)
{
  //Open Data Channel
  Serial.begin(115200);
  Serial.println(F("IMU Complementary Filter Tester")); Serial.println("");

 //Initialise TMU sensors
 sensorInit(accel, mag, gyro);
 senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha);
  Serial.println("HERE ONE");
}

void loop(void)
{
 //Variables for reading sensors
 sensors_event_t accel_event, mag_event, gyro_event;
 sensors_vec_t   orientation;

 // Retrieve Sensor Readings
 accel.getEvent(&accel_event);
 gyro.getEvent(&gyro_event);
 mag.getEvent(&mag_event);

 Serial.println("HERE TWO");

 int anglePitch = senPitch->combine(gyro_event.gyro.y, orientation.pitch);
 int angleRoll = senRoll->combine(gyro_event.gyro.x, orientation.roll);

}
I had to keep track of a couple of pieces of information for each direction, so rather than trying to use parallel arrays, I created a CompFilter class. I think I am using the correct syntax in the class and constructing the object, but I am getting very unusual outputs from Serial.print().
RE ONE
RE TWO
Here THREE
Here THREE
entary Filter Tester

Depending on how I fiddle with the code, I can get setup() repeating over and over or loop() running once before silently failing.
I suspect that I have misdirected a pointer somewhere, but I am not sure. I would appreciate any help.

senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha); -- looks like a duplicate.

Simply remove that line and use static instances instead i.e. CompFilter senPitch(alpha); CompFilter senRoll(alpha); You might need to move the declaration of alpha or use a default constructor and a setter instead.

Dave X is absolutely right.
I never assigned the senRoll pointer to an object. Then when I tried to dereference it, it went to some random address. I guess there are very few memory protections, so rather than causing a seg fault it just caused erratic behavior.
Thanks for the help.


text:
How to upload a sketch via Arduino Nano
I have two Nano boards, but the first one seems the CH340 chipset was burn. :( ,

Nano v3, CH340 chipset but unable to identify after connect to my Mac using USB
Nano v3, FTDI chipset and in good condition
USB to Serial module, using FTDI chipset

I am trying to upload a sketch via a USB-to-Serial module OR another Nano board (or UNO board v3) to my CH340 Nano Board.
Question:

How to wire them up?
Is it need upload a "Arduino as ISP" first?
step-by-step tutorial or website talking about this ??

I presume you have boot loader on your Nano, so you can use your USB to serial, just wire (D0)TX->RX(USB), (D1)RX->TX(USB), GND-GND and supply power to the target Nano. You will need to reboot Nano just before the uploading the code. Uploading is same as usual.
Using other Arduino as ISP needs more wires as well as 2nd Arduino, so i would use above method.

Firstly, yes, there are boot loader on Nano which chipset was burn one. Means solution A) using USB-to-Serial, B) "Arduino as ISP" board, both able to upload sketch to my broken Nano?

If only CH340 was burnt than yes, both shall work. CH340 (or FTDI) IC is only to provide USB to Nano D0 & D1 TTL serial conversion, so bootloader can detect and accept new firmware. BTW, there are different CH340 ICs and at least some drivers are incompatible among them. ISP programming method uses MCU SPI programming option so doesn't need USB-TTL conversion.

Check this video https://www.youtube.com/watch?v=0zuRukW7o0A

Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
Open Terminal from Recovery mode
Run the command csrutil enable --without kext
Reboot
Install driver


text:
Arduino CAN SPI Configuration problem
I am using an Arduino UNO along with a Cooking Hacks CAN Bus Module and Multiprotocol Radio Shield. The CAN module is connected to the radio shield which is plugged into the Arduino. I got this radio shield keeping future applications in mind where I can combine multiple protocols, for eg. CAN and Bluetooth.
I connected them through an OBD2-DB9 cable to the car's OBD port but noticed that I was not really getting any messages. Well I am getting messages but just:
   -- Constructor Can(uint16_t speed) --
   SPI configured
   The MCP2515 has been successfully reset, configuration mode activated
   Speed=500kps
   -- End Constructor Can(uint16_t speed) --

   Data in buffer 0
   id: 7FF  rtr: FFFFFFFF => Data in buffer 0
   id: 7FF  rtr: FFFFFFFF => Data in buffer 0
   id: 7FF  rtr: FFFFFFFF => Data in buffer 0

After analysing the connections, I realised that the hardware is probably fine since the continuity between the pins of the cables is fine and the CAN module(MCP2515 + MCP2551) is receiving power and I also checked the voltages at the pins and think they're mostly fine apart from a few pins which I'm not sure about. Which brings me to the software issue. I can see that the SPI is not getting configured properly and the MCP2515 controller doesn't enter configuration mode which means the bit times defined are not being used and hence the controller is not initialising like it should. I even tried manually changing to configuration mode by changing the values of the REQOP bits of the CANCTRL register as opposed to doing a software reset which was how I was doing it initially. Even then, no luck. To verify the SPI connection, I chose a random read/write control register like BFPCTRL and wrote a value to it and then read it back to verify that it matched the values I wrote. However, the value read back is not the same as the value I wrote. Also, the controller only has trouble going into configuration mode. It seems to change to normal and listen only mode without problem since the CANSTAT register displays the correct values for the REQOP bits. I don't understand why the controller has problem entering configuration mode but no problem changing to the other modes. Can anybody help me?
SPI Code:
    bool CAN::begin(uint16_t speed)
    {
    #if (DEBUGMODE ==1 )
    Serial.println("-- Constructor Can(uint16_t speed) --");
    #endif

    //Initialization SPI
    SPI.begin();
    SPI.detachInterrupt();
    SPI.setBitOrder(MSBFIRST);
    // both mode 0 & 3 should work
    SPI.setDataMode(SPI_MODE0);

    //Set the SPI frequency
    SPI.setClockDivider(SPI_CLOCK_DIV4);

    #if (DEBUGMODE==1)
    Serial.println("SPI configured");
    #endif

    //Configure MCP2515 pins
    pinMode(CAN_CS,OUTPUT);
    pinMode(CAN_INT,INPUT);
    digitalWrite(CAN_CS,HIGH);

    writeRegister(BFPCTRL, (1<<B0BFM) | (1<<B1BFM));
    int dat = readRegister(BFPCTRL<<2);
    Serial.println(dat);

    //Software resets MCP2515
    reset();
    delay(100);
    //After the reset, controller enters configuration mode
    dispMode();

When I read back the values of B0BFM and B1BFM bits, they should be 1 but the display says that their values are 0.
   void CAN::writeRegister( char direction, char data )
   {
   //CS low to select the MCP2515
   digitalWrite(CAN_CS,LOW);

  SPI.transfer(SPI_WRITE);
  SPI.transfer(direction);
  SPI.transfer(data);

  //CS line again to release
  digitalWrite(CAN_CS,HIGH);
   }

  char CAN::readRegister(char direction)
  {
  char data;
  //CS low to select the MCP2515
  digitalWrite(CAN_CS,LOW);

  SPI.transfer(SPI_READ);
  SPI.transfer(direction);
  //Read data SPI
  data = SPI.transfer(0xff);

  //CS line again to release
  digitalWrite(CAN_CS,HIGH);
  return data;
  }

Please fix the format and remove extra characters "myCAN.begin(500);  ]"

In SPI protocol you'll need to read the SPI buffer twice because the data you wrote will be read by the IC and the IC will respond to it in the next communication and that's when you know.
Also, by looking at the message, I see that your IC is working fine, but is your CAN bus initialised properly? I'm a FSAE team member and I've faced this issue with the CAN Bus termination resistances and the ODB-II configuration on the Sparkfun CAN Bus shield.
Also, have you tried any other libraries for the CAN Shield? For me the seeedstudio library of their CAN shield worked very well.


text:
Error: invalid types 'int[int]' for array subscript
I am trying to get an Arduino to work with some Adafruit Motor shields.
Everything seemed to work fine, but when I tried to create a function, I get the error in the subject. As far as I can tell, everything was declared properly (the array is initialized and is indexed elsewhere with without issue). Only the function seems to cause an issue.
Would anyone have a guess at what's wrong?
    //////// Imports
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    ////////My globals. Times are in milliseconds
    unsigned long currentTime = 0;
    unsigned long elapsedTime = 0;
    unsigned long startTime = 0;
    byte currentMotor = 1;
    byte currentShield = 1;
    byte motorRunning = 0;

    //// Settings

    // How many seconds between motors
    unsigned long endTime = 4000;

    // How many shields and motors per shield
    const int nShields = 1;
    const int nMotorsPerShield = 3;

    /////////MicroManager globals
    unsigned int version_ = 2;
    const unsigned long timeOut_ = 1000;
    byte currentPattern_ = 0;
    unsigned long time;

    /////////Adafruit globals
    Adafruit_MotorShield afms[nShields];
    Adafruit_DCMotor *motor[nShields][nMotorsPerShield];

    ////////////Setup
    void setup() {
      Serial.begin(57600);

      unsigned char address = 96;

      for (int i = 0; i < nShields; i++) {
        afms[i] = Adafruit_MotorShield(address);
        address = ++address;
        afms[i].begin();
      }

      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          motor[i][j] = afms[i].getMotor(j + 1);
          motor[i][j]->setSpeed(255);
        }
      }

      pinMode(13, OUTPUT);
    }

    ////////////////////Main
    void loop() {
      currentTime = millis();
      elapsedTime = currentTime - startTime;

      if (elapsedTime > endTime) {
        startTime = currentTime;
        currentMotor = currentMotor + 1;
        if (currentMotor > nMotorsPerShield) {
          currentMotor = 1;
        }
      }

      if (Serial.available() > 0) {
        int inByte = Serial.read();

        switch (inByte) {
          case 1:
            if (waitForSerial(timeOut_)) {
              currentPattern_ = Serial.read();
              if (currentPattern_ == 0) {
                for (int i = 0; i < nShields; i++) {
                  for (int j = 0; j < nMotorsPerShield; j++) {
                    motor[1][j]->run(RELEASE);
                  }
                }
              }
              else {
                switchMotor();
              }
              Serial.write( byte(1));
              digitalWrite(13, HIGH);
            }
            break;

          case 30:
            Serial.println("MM-Ard");
            break;

          case 31:
            Serial.println(version_);
            break;
        }
      }

      digitalWrite(13, LOW);
    }

    ////////////////Function definitions

    bool waitForSerial(unsigned long timeOut)
    {
      unsigned long starTime = millis();
      while (Serial.available() == 0 && (millis() - starTime < timeOut) ) {}
      if (Serial.available() > 0)
        return true;
      return false;
    }

    void switchMotor()
    {
      int shield = currentShield - 1;
      int motor = currentMotor - 1;
      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          if (i == shield && j == motor)
            motor[i][j]->run(FORWARD);
          else
            motor[i][j]->run(RELEASE);
        }
      }
    }

Please post the full error message from the compiler. And the code where it occurs.

Take a close look at this line:
motor[1][j]->run(RELEASE);

Looks like it should be:
motor[i][j]->run(RELEASE);

Otherwise it is an illegal index (as there is only one shield).
The next error is in the function switchMotor(). Again, have a close look at the definition of "motor". There is a local variable with that name but you want to also access the global array with the same name.
void switchMotor()
{
  int shield = currentShield - 1;
  int motor = currentMotor - 1;
      ^
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == motor)
        motor[i][j]->run(FORWARD);
        ^
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

My guess is that this is where the compiler give you the error message!
Cheers!

To be able to help you must add the compiler error output with line, file, and the code. It is too much guessing otherwise.

Changing the int motor = and the j == motor to xmotor instead of motor allows it to compile perfectly fine for me. Just get rid of that variable naming conflict and it should be fine.

Thanks Mikael, the motor naming conflict was the problem!

I get a warning flag in UECIDE for the line:
address = ++address;

‣ operation on 'address' may be undefined [-Wsequence-point]

Increment address, and then assign the new value from address into address.  That seems a bit odd to me.  I think you just meant to increment:
address++;

Or
address = address + 1;

Also it flags up the 1 instead of i that Mikael found:

‣ array subscript is above array bounds [-Warray-bounds]

And of course there is the (somewhat hard to spot - Kudos to Mikael for finding it - it took me a bit to see it myself) naming conflict:

‣ invalid types 'int[int]' for array subscript

It was only when I used the advanced editing facilities of UECIDE to highlight all occurrences of motor that I found there was extra ones that shouldn't have been there causing the problem.

So just changing the integer variable name from motor to something else fixes it:
void switchMotor()
{
  int shield = currentShield - 1;
  int thismotor = currentMotor - 1;       // RENAMED MOTOR
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == thismotor)  // RENAMED MOTOR
        motor[i][j]->run(FORWARD);
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

Cheers, that was the issue!


text:
Need help debugging my Binary Clock
I have tried everything but I can't get my binary clock to display correctly. The diagram and code are here: Binary Clock | Electronics Lab.
The hardware is based off this (it also explains the process that my program is trying to do): DIY: Binary Clock with Arduino. The problems lie in a, probably, simple error as my variable tempTime, which is used to convert the individual digits to their binary equivalent, does not change when I tell it to. All this occurs in the display function. (Sorry, I'm new Here and only a high school student)
While debugging it I realized that the only problem is the variable tempTime - the hardware and other functions work as they were intended.
Can anyone help? (Sorry if this is not very well documented).
    int digitPins[4][4] = {{13,6,-1,-1},{12,7,3,1},{11,8,4,-1},{10,9,5,2}};
int time[4] = {0,0,0,0};
int steps[4]={1,2,4,8};
int tempTime = 0;
void setup(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    pinMode(digitPins[x][y],OUTPUT);
    }
  }
    Serial.begin(9600);
    convertHour(12);
    convertMinute(57);
    Serial.println("The time is:");

  for(int z = 0; z < 4; z++){
    if(z == 2){
    Serial.print(":");
    }
  Serial.print(time[z]);
  }
  display();
}
void loop(){

}
void display(){
  int displayer[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
/*
0 - Hour
1 - Hour
2 - Minute
3 - Minute
4 - Hour(Total)
5 - Minute(Total)
*/

  int counter1 = 0;
  for(int i = 0; i < 4; i++){ //Loop for the individual digits
    tempTime = time[i];
    if(tempTime >= 10){
    tempTime = tempTime % 10;
    }
    Serial.print("\nBegining new iteration i = ");
    Serial.print("\nStarting with digit: ");
    Serial.print(tempTime);
    Serial.print(i);
    Serial.println("");
    for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
      if(time[i]/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
        Serial.print("\n");
        Serial.print(time[i]);
        Serial.print("/");
        Serial.print(steps[j]);
        Serial.print(" = ");
        Serial.print(time[i]/steps[j]);
        tempTime =tempTime - (time[i]*steps[j]);
        displayer[counter1] = digitPins[i][j];
        Serial.print("\nAdded: ");
        Serial.print(digitPins[i][j]);
        counter1++;
      }
    }

  }
  clear();
  for(int a = 0; a < 13; a++){
  digitalWrite(displayer[a],HIGH);
  }
}
void clear(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    digitalWrite(digitPins[x][y],LOW);
    }
  }
}
  void convertHour(int value){
    int digits[] = {0,0};
    if(value >= 10){
        debug("Bigger than 10");
        if(value >= 20){
            digits[0] = 2;
        }else{
            digits[0] = 1;
        }
    }
    digits[1] = value - (digits[0] * 10);
    //String hour = digits[0]+""+digits[1];
    //Serial.print(digits[0]);
    //Serial.print(digits[1]);
    time[0] = digits[0];
    time[1] = digits[1];
  }
void convertMinute(int value){
  int digits[2] = {0,0};
  int val = value;
  if(value >= 10){
    digits[0] = val/10;
  }
  digits[1] = value - (digits[0] * 10);
  Serial.print("\n");
  Serial.print(digits[0]);
  Serial.print(digits[1]);
  time[2] = digits[0];
  time[3] = digits[1];
}
  void debug(String value){
    boolean de = true;
    if(de){
    Serial.println(value);
    }
  }

Serial and LED on the same pin?

Calculate the power requirements for all these LEDs (and 120 ohm). Will the Uno be able to deliver that?

We need more information.  What should it do? What does it do? What have you tried?

Very Sorry wrote that post in a hurry. The hardware is based off this (it also explains the proccess that my program is trying to do): http://www.danielandrade.net/2008/07/15/binary-clock-with-arduino/ The problems lie in  a probably simple error as my variable tempTime which is used to convert the individual digits to their binary equivalent does not change when I tell it to. All this occurs in the display function. (Sorry New Here and only a highschool student)

Can you edit your question and paste the code into it please? This is looking like a link-only question. Format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. If that link goes down the question, and any following answer, will be meaningless.

In your “Loop to determin the arrangement”, you are erroneously using
time[i] in several places where you mean tempTime. Also, to update
tempTime you only have to subtract steps[j]. With these fixes, your
loop becomes:
for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
  if(tempTime/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
    Serial.print("\n");
    Serial.print(tempTime);
    Serial.print("/");
    Serial.print(steps[j]);
    Serial.print(" = ");
    Serial.print(tempTime/steps[j]);
    tempTime = tempTime - steps[j];
    displayer[counter1] = digitPins[i][j];
    Serial.print("\r\nAdded: ");
    Serial.print(digitPins[i][j]);
    counter1++;
  }
}

Now, if you learn a little bit about how binary numbers work, and about
the binary operators in C and C++, you can rewrite your loop in a
simpler form:
for (int j = 3; j >= 0; j--) {
  int weight = 1 << j;      // 2 raised to the power j
  if (tempTime & weight) {  // if bit j of tempTime is set
    displayer[counter1++] = digitPins[i][j];
    Serial.print("Added bit ");
    Serial.print(j);
    Serial.print(", weight ");
    Serial.print(weight);
    Serial.print(", output ");
    Serial.println(digitPins[i][j]);
  }
}

As a side note, it is considered good practice to print a new line at
the end of each string you print (using println()), rather than at
the beginning.
Edit: As your display() function is way too complex for what it
does, I did not resist the temptation to simplify it:
void display() {
  for (int i = 0; i < 4; i++)
    for (int j = 0; j < 4 && digitPins[i][j] >= 0; j++)
      digitalWrite(digitPins[i][j], time[i] & (1<<j));
}

Thank you so much, I'm relatively new to c++ with a background in js and php, still trying to get the hang of it.

Well, the bitwise operators of C and C++ are the same you already know from JavaScript and PHP.


text:
Since double and float represent the same data type (usually), which is preferable?
It looks like on ATMega based boards, float and double are equivalent 32-bit (4-byte) data types.
However, on the Arduino Due, doubles are 64-bit (8-byte) where floats are 32-bit (4-byte), same as the ATMega boards.
I also saw one source on avr-gcc that listed double as non-standard.
So, when writing code for ATMega based boards are floats preferable to using doubles, since that would make the code equivalent for Due boards? Or are doubles preferable for any reason?

I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect. But this is more personal preference than a hard rule (hence I do not consider it a “real” answer).

I think that's fairly solid reasoning; one might not expect the 'double' to really be a float if they're coming from another platform.

See avr-gcc

Deviations from the Standard
double
double is only 32 bits wide and implemented in the same way as float

when writing code for ATMega based boards ...

They are the same, therefore.

(Edited to add)

When writing code, is it then preferable to using one over the other?

I don't really understand your question. You asked about writing code for the ATMega based boards. Do you really mean, if you are writing code for the Due? The quick answer would be, on the Due, double takes twice the RAM, however it is over twice as precise - around 7.2 decimal digits for float compared to 15.9 for double. (I'm not sure about the speed, probably double would be slower, unless it is implemented in floating-point hardware - however I cannot see any reference to that on the AT91SAM3X8E datasheet).
See: https://en.wikipedia.org/wiki/Floating_point
If you want more precision (however slower and taking more RAM) then you could use double - which won't make any difference on the ATmega based boards, but will on the Due.

As Edgar Bonet said:

I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect.

That makes quite a bit of sense.

I warn you though that "preferable" is subjective. It is close to asking "what is best"? To which the reply is: "best for what?"

On ATMega boards, yes, they are the same. If you then take the code to an Arduino Due, they are no longer the same if using double, but the same if using float. When writing code, is it then preferable to using one over the other? Why or why not?

See amended reply.

Well, strictly speaking I'm only targeting ATMega architectures right now, I thought I was writing code that was consistent across all arduinos. I did not ask which was best, though I think I'm answering my own question in that float is more well known, a better cross-architecture description of the datatype, and consistent across more arduinos.

Would it make more sense if I added "When writing Arduino code for an unknown board, is it then preferable to use one over the other?"

I suppose. *shrug* - when dealing with boards which may have limited RAM and Flash, it isn't always possible to code generically.

At the outset of Arduino programming, I thought they were at least attempting to make the code as hardware-agnostic as they could. In this spirit, I think I'll use floats from here on.

This answer is no more up to date with avr-gcc, which suports 64-bit double (and long dounble) since v10.  See for example the avr-gcc wiki page you linked.

@emacsdrivesmenuts Well, yes, but using a configuration option, not the default. In avr-gcc v10 and higher, the layout of double and long double are determined by configure options --with-double= and --with-long-double=, respectively. Bear in mind that using more precise floating point will take longer, so your application would need to choose precision over speed.

And take more memory, which you may not want to take on a processor with limited RAM.

@Nick Gammon: Of course it's about precision, which was not the point of my comment.  Besides that, avr-gcc v10+ supports -mdouble=64.  The only reason to default it to 32 bits was to align with older (not standard-compliant) versions of avr-gcc.

Neither are preferable.
Unless your microcontroller has a hardware floating point unit using float or double results in huge overheads for your program.
So instead use integer mathematics whenever possible.
Instead of working in Volts, work in millivolts, for example.
However, if your MCU does have an FPU, and some modern more powerful ones do, then you should use the size of float or double that is native to the FPU. If it is a 32 bit FPU then use float. If it is a 64 bit FPU then you can use double.

do you have any actual benchmarks of the "huge overheads"? less efficient sure, but I've never really had it be a problem to use floating point on arduino.

int a; void setup() { a = 1; } void loop() { a = a * 2; } uses 482 bytes. Change the int to a float it slmost doubles to 878 bytes. Even worse if you change the 2 to 2.0, while it's int - you end up with 1086 bytes. Massive increases. And that's not even mentioning how long it takes to run. I'll do a crude benchmark.

Multiplying 1 by 2 until it exceeds 32768 (1, 2, 4, 8, 16, etc) with int takes 12 microseconds. Using float it takes 148 microseconds. That's more than ten times longer for just that one simple operation.

Interestingly, multiplying an integer by 2.0 takes even longer - 208 microseconds. 17 times longer.

Fixed point takes more ops than just integer multiply, and we should be comparing 32-bit values on both sides. in a test of float (a*b) and long (a*b/1000), as would be the case if you did operations in mV, floating point is faster. That's not calculating the extra high byte that's necessary for real fixed point, then again fixed point would benefit from an easier divisor. Addition will certainly remain faster in fixed point. I don't think float vs fixed is as clear cut as the arduino SE community makes it out to be.

@BrettAM: When doing fixed point, you would never scale by 1000, always by a power of two. And no, you should not compare at 32 bits: you should compare 32-bit floats vs. fixed point of the smallest size that is precise enough for the job, which will often be 16 bits, and sometimes even 8. I've done a 16-bit fixed-point implementation of cos() and sin() that is 15.7 times faster than the standard <math.h> functions.

@EdgarBonet I mentioned that the divisor is bad, its taken from the answer that suggested it. A 6.10 fixed point multiplication results in a 12.20 (32 bit) result; so unless their numbers fit in 8 the multiplication would need to take place in 32 bits. The overhead of writing a custom fixed point cos() (or even downloading one) is much greater than having a few slow trig functions for most applications here on arduino SE.

@BrettAM: The answer did not suggest a division, it suggested using millivolts, which is not the same. Typically you would either analogRead(pin) * 39U >> 3 or analogRead(pin) * 1250UL >> 8, depending on the required precision. And you do not need to multiply in 32 bits: you can do a 16×16→16 multiply in assembly, or use the _Fract or _Accum data types. But then I agree that many projects have enough CPU cycles to spare to make fixed point irrelevant.


text:
Arduino Hardware Issue
I have two Arduino Uno R3 boards and both of them now seem to have an issue. There's a micro sized 8 Pin chip near the dc power port. This seems to get incredibly hot (i managed to get a blister from touching it) and the "L" Led seems to stay dimly lit even when the reset button is pressed.
The Arduino Uno was working fine during operation and only started giving me this problem recently, i cant seem to find any visible short or loose terminal on the board.
I can see that the reset function is being used as my LCD does reset.
Would anyone have a reason for this mysterious issue?

This chip seems to be the dual op-amp labeled LMV358IDGKR in the Uno R3 schematic.

How are you powering the Arduino when this condition occurs?

I had something similar before because I tried to attach a fan to it. Are there any short circuits or something that would take a huge amount of power?

post a picture of your UNO board

There are two issues here:

The "L" LED lighting. On the R3 Uno this is driven by an op-amp and if pin 13 is "floating" the op-amp may, or may not, turn the LED on. So this is normal.
The 8-pin chip near the power plug getting very hot. This is definitely not normal. You must be consuming a lot of current to do that. You could try measuring it. A Uno running an "empty" sketch should be consuming around 50 mA. Note that this chip is the op-amp mentioned in my first point. Possibly you have damaged it. Did you connect an LED (or motor) or similar to pin D13? If so, what current-limiting precautions did you take?

Try running an empty sketch (or the Blink sketch) with no hardware connected to the board, to see if it still happens.
Try measuring the power consumption, if possible, with a meter measuring the input through the 5V pin, if you have a 5V power supply you could use for this.
Are these genuine boards, or cheap clones from eBay?

Did my answer help or not? Stack Exchange is recycling this as an unanswered question. If it helps, please indicate this. If not, please state in what way it was not helpful.


text:
Understanding types of timer interrupts
I'm learning this note about timer's api on Arduino Due. Interrupt can be attached with the next function:
void tc_enable_interrupt(
       Tc * p_tc,
       uint32_t ul_channel,
       uint32_t ul_sources)

Where the input parameter ul_sources can be one or more of the following:

TC_IER_COVFS Enables the Counter Overflow Interrupt
TC_IER_LOVRS Enables the Load Overrun Interrupt
TC_IER_CPAS  Enables the RA Compare Interrupt
TC_IER_CPBS  Enables the RB Compare Interrupt
TC_IER_CPCS  Enables the RC Compare Interrupt
TC_IER_LDRAS Enables the RA Load Interrupt
TC_IER_LDRBS Enables the RB Load Interrupt
TC_IER_ETRGS Enables the External Trigger Interrupt

I'm more like mobile developer and I don't understand what does all this interrupt types mean.

The datasheet is a good place to start, http://www.atmel.com/images/atmel-11057-32-bit-cortex-m3-microcontroller-sam3x-sam3a_datasheet.pdf, See chap. 36. Timer Counter (TC), pp. 856 and forward. It is really simple. Just a counter and a few registers to match counter value.

@MikaelPatel, this chapter is to difficult for me.

At least take a look at Figure 36-6. Waveform Mode, pp. 866. It shows the interrupt flags and where they come from. A Timer is basically a counter with a clock source and a few match/load registers. Interrupts are typically when the counter comes to a specific value such as overflow, contents of A/B match register, etc. It is not rocket science.

@MikaelPatel, ok thanks. I will take a look. Actually I want to achieve one of this things: A) Timer Interrupt that fires only once; B) Adjustable timer interrupt, so I can modify phase without restarting the timer.

A) disable the timer interrupt in the ISR, B) adjust the match register in the ISR, are typical methods. Typical ISRs can be found in for instance Cosa Real-Time Timer (RTT) implementation, https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/RTT.cpp#L143, Compare A is used for millis-seconds count update, Compare B is used for one-shot micro-seconds level job scheduling.

Thank you. I've thought about disabling interrupt in the ISR but it seem to expensive by performance to me.


text:
Arduino Infinity Loop
I'm new to this Arduino programming. So I want to ask about my current project. My lecturer told me to make a temperature sensor using an LM35, where a green LED will light up when below some certain temperature that I set. The same goes for yellow and red LEDs for medium, and high temperatures. The tricky part here is that I need to make sure my buzzer (piezo) is on forever if it reaches the high temperature, until I press a button to reset it.
This is my coding so far:
const int greenLed = 3;
const int redLed = 4;
const int yellowLed = 5;
float tempC;
int reading;
int tempPin = 0;
int speakerOut = 11;
const int buttonPin = 2;
int buttonState = 0;
long duration = 10000;
int tempo = 0;

void setup() {
// initialize digital pin 13 as an output.
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(2, INPUT);
pinMode(11, OUTPUT);
analogReference(INTERNAL);
Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {
buttonState = digitalRead(buttonPin);
reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.println(tempC);
delay(500);

if (tempC < 30.00) {
//Serial.println("Temp LOW");
digitalWrite(3, HIGH);
delay(10);
}else {
digitalWrite(3,LOW);
delay(10);

}

if (31.00 < tempC < 33){
//Serial.println("Temp MED");
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(50);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(50);

}else {
digitalWrite(4,LOW);
digitalWrite(5,LOW);

}

if(tempC >= 34){
**WHAT SHOULD I FILL UP HERE TO MAKE SURE MY PIEZO BUZZER ON FOREVER**
}
if(buttonState = 1);{
digitalWrite(11, LOW);
}

}
Any help would be great. Or if you have a better idea on how to do this, I'm gonna love it.

Please post the wiring of this and format the code. Also use the constants you have defined. Why define "greenLed = 3" and still use "digitalWrite(3, ...)"?

uhmm i dont get what you mean.its my 1st month learning this.well if i do "greenLed =3 , it is not good to use digitalWrite(3,...)"? .Whats the better way?

A better way is "digitalWrite(greenLed, ...)". The whole idea behind giving a pin a "name" is to allow change but also make the code easier to read. But your lecturer should have told you that :)

You can use the toneAC library, which allows even better handling of piezo speakers then the standard "tone"-functions.

Features: Nearly twice the volume (because it uses two out of phase pins in push/pull fashion)
      Higher quality (less clicking)
      Capability of producing higher frequencies (even if running at a lower clock speed)
      Nearly 1.5k smaller compiled code
      Bug fixes (standard tone library can generate some odd and unpredictable results)
      Can set not only the frequency but also the sound volume
      Less stress on the speaker so it will last longer and sound better

With the library you can do something like:
int freq = 1000
int vol = 10
int length = 0
boolean background = true

toneAC(freq, vol, length, background);

The tone now will play forever in the background, until you stop it with:
toneAC(0);

Ohh cool.Gonna try this one later. Thanks for ur help!

The answer is simple add
digitalWrite(speakerOut,HIGH);

Common mistake made by beginners is to use assign operator instead of compare operator
if(buttonState=1)

should actually be
if(buttonState==1)

Never pull that pin LOW
if(buttonState = 1);{
digitalWrite(11, LOW);
}

is wrong use the below code
if(buttonState == 1){
    digitalWrite(11, LOW);
}

Don't forget to connect the button to buttonPin or you will get random HIGH or LOW from that pin since its floating
Hope this helps.

That's not how a Piezo-Speaker works...

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Another traffic light project
I have a school project, where I'm going to make a traffic light system on a pls. I want to try it out on an Arduino first, just to get the hang of it.
To make it a little bit more advanced than I have found on the internet, I want to make the lights go in "emergency mode" if the green lights in both directions are on at the same time. It will then go into a yellow blink.
My idea is something like this:
// Yellow blinking if fault in the system or operator activates it
int killState = digitalRead(Kill);
int resState = digitalRead(Res);
if (killState == HIGH /*|| greenlights in both directions */) {
 while (resState == LOW;) { // Yellow blink as long as system is not reset
  BLINK();
 }
}

I guess I need a variable or two that tells what state the lights are in, but I'm stuck. Any good solutions out there?
Another thing is the reset button. I haven't put much effort in it, but I want it to go into the starting point.
The link to the complete script can be found here.

For starters, take a close look at this line:
while (resState == LOW;)

That is not the correct syntax. But the real issue is how is this while loop terminated? The value is never set again?
Cheers!

I guessed so. As I said, I haven't put much effort in it yet. I need to take one step at a time. Thanks for the quick reply, though!
The idea is that the state will not change until the reset button is activated. And the ' ; ' was a type-o.
I am new to 'while' and 'for' loops, but i think I'm starting to get the hang on 'if' and 'else' criterias.

You could do something simple to test if both red and green are on,  eg.
if (digitalRead (RED_PIN) == HIGH && digitalRead (GREEN_PIN) == HIGH)
  {
  digitalWrite (RED_PIN, LOW);  // turn off red
  digitalWrite (GREEN_PIN, LOW);  // turn off green
  while (true)
    {
    digitalWrite (YELLOW_PIN, HIGH);
    delay (500);
    digitalWrite (YELLOW_PIN, LOW);
    delay (500);
    }  // end of while
  }  // end of it

If you have other questions please post your code and not a snippet - however I suggest you try to get further on your own. This is obviously an exercise, and the more you try to work it out yourself the more you will learn.

Thanks! That was a good idea. I will add this to the script. I will add the full code next time. I added it as a link, though.

What is it that is true in the while (true) part?

true is true. That particular loop loops indefinitely. In other words, if there is some failure in the traffic lights, it will flash yellow ... forever. (Kind of a scary thought, eh?)

I could have written while (5 == 5) - it just means to do something forever.


text:
Trying to read a 93lc46b chip using Arduino
I am trying to read a 93lc46b EEPROM chip using Arduino. I am reusing the code from http://owlsan.blogspot.de/2012/10/accessing-93c4693c46n-serial-eeprom.html, except I have modified it for 93lc46b chip, plus I am using Arduino Uno and not Arduino Mega. The problem I am facing is, I get different set of bytes every time I try to read 93lc46b EEPROM chip. I doubt this might be some garbage data. Can you please explain me what and where exactly I am doing something wrong. The modified code snippet is as follows:
#include <avr/io.h>
#include <util/delay.h>

#define CLEAN 0b00000000

#define DDR93LC46B  _SFR_IO8(0x04)
#define PORT93LC46B _SFR_IO8(0x05)
#define PIN93LC46B  _SFR_IO8(0x03)

#define SK 13
#define DO 12
#define DI 11
#define CS 10

#define READ 0x02

#define SET_CS PORT93LC46B |= (1 << CS)
#define CLR_CS PORT93LC46B &= ~(1 << CS)

#define SET_SK {PORT93LC46B |= (1 << SK); _delay_us(0.01);}
#define CLR_SK PORT93LC46B &= ~(1 << SK)

#define SET_DI PORT93LC46B |= (1 << DI)
#define CLR_DI PORT93LC46B &= ~(1 << DI)

class SPI_93LC46B {
  private:
    uint8_t Transfer(uint8_t data) {
      SPDR = data;
      while(!(SPSR & (1 << SPIF))); // Wait for SPI interrupt flag
      return SPDR;                  // Return byte gathered from SPI data register
    }
    void Opcode(uint8_t opcode, uint8_t address) {
      SET_CS;
      SPCR &= ~(1 << SPE);               // SPI disable
     _delay_us(1);
      CLR_SK;
      SET_DI;                            // Send start bit
      SET_SK;
      CLR_SK;
      SPCR |= (1 << SPE);         // SPI enable
      Transfer((opcode << 6) | address); // Transmit byte
    }
  public:
    SPI_93LC46B() {
      SPCR =    CLEAN        // Set SPI control register
         & ~(1 << SPIE)  // SPI interrupt disable
         |  (1 << SPE)   // SPI enable
         & ~(1 << DORD)  // MSB first
         |  (1 << MSTR)  // SPI master device
         & ~(1 << CPOL)  // SPI
         & ~(1 << CPHA)  //  mode 0
         |  (1 << SPR1)  // XX/64 MHz
         & ~(1 << SPR0); //  speed
      SPSR =    CLEAN         // Init SPI status register
         & ~(1 << SPI2X); // SPI double speed
      DDR93LC46B =    CLEAN      // Set up inputs/outputs
             |  (1 << SK)  // Serial clock output
             |  (1 << DI)  // Data input (MOSI) output
             |  (1 << CS)  // Chip select output
             & ~(1 << DO); // Data output (MISO) input
      PORT93LC46B |= (1 << DO); // Data output (MISO) high
      CLR_DI;
      CLR_CS;
      CLR_SK;
     _delay_us(1);
    }
    ~SPI_93LC46B() {
      //
    }
    uint16_t Read(uint8_t address) {
      uint16_t data = 0;
      Opcode(READ, address);
      CLR_DI;
      SET_SK;
      CLR_SK;
      SPCR |=  (1 << CPHA);
      data = Transfer(0);
      data = (data << 8) | (Transfer(0));
     _delay_us(1);
      CLR_CS;
      CLR_DI;
      SPCR &= ~(1 << CPHA);
      return data;
   }
};

void setup(void) {
  Serial.begin(115200);
  _delay_ms(100);
  Serial.println("EEPROM writing/reading");
}

void loop(void) {
  Serial.println("new round");
  SPI_93LC46B _93LC46B;
  int i;
  uint16_t data;
  for(i = 0; i < 64; i++) {
    data = _93LC46B.Read(i);
    _delay_ms(50);
    Serial.print(data, HEX);
    Serial.print(" ");
    if((i + 1) % 8 == 0)
      Serial.println();
  }
  _delay_ms(10000);
}

This code is over complicated and has a lot of errors. Let us start with the obvious. Look closely at this section. Do you see the error(s)?
#define SK 13
#define DO 12
#define DI 11
#define CS 10

#define READ 0x02

#define SET_CS PORT93LC46B |= (1 << CS)
#define CLR_CS PORT93LC46B &= ~(1 << CS)

#define SET_SK {PORT93LC46B |= (1 << SK); _delay_us(0.01);}
#define CLR_SK PORT93LC46B &= ~(1 << SK)

#define SET_DI PORT93LC46B |= (1 << DI)
#define CLR_DI PORT93LC46B &= ~(1 << DI)

The symbols SK, D0, DI, CS seem to be pin numbers but look how they are used in the SET_XX and CLR_XX macros. That is very wrong. They should be the bit numbers in the PORT register instead.
There is more. How about this?
_delay_us(0.01);

What is the intention? _delay_ns(10)??? In any case yet another error.
Cheers!


text:
Arduino Nano no output on any controllable pins except for RX and TX pins
I have 2 Arduino Nanos which don't output anything on any controllable pins except for RX and TX pins. I used an LED which I have tested works on the 3.3v/GND and 5.0v/GND. When I try to control the RX and TX pins (1 and 2) the LED lights up on the board and the external LED I am using to test. I am using the example "Blink" program to test it, and I've tried it on both nanos. I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything. Why isn't it working?
    /*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
 */

// Pin 13 has an LED connected on most Arduino boards.
// Pin 11 has the LED on Teensy 2.0
// Pin 6  has the LED on Teensy++ 2.0
// Pin 13 has the LED on Teensy 3.0
// give it a name:
int led = 26;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Anything. Please paste minimal test code demonstrating the problem.

It's the same as default

You are using a resistor with the LED? And it is .... ohm? And you connect to GND. Pin 26??? On an nano??

No, the LED doesn't need a resistor, yes I connected it to the relevant pin and ground.

What does a multimeter say when you check those pins for voltage levels?

@Matthew There is no pin 26 on Arduino. If you connect it to a analog/digital pin (they're all labeled) then you must use the same letter number combination. Most LEDs need resistors to limit the current to Arduino safe limits, are you sure you haven't burned any pins?

the LED doesn't need a resistor - why?

@NickGammon because I tested it with the 5v and 3.3v therefore higher voltages doesn't blow it up.

@Avamander See https://www.google.co.uk/search?q=arduino+nano+pinout&safe=strict&rlz=1C1MDNA_enGB657GB657&espv=2&biw=1440&bih=731&tbm=isch&imgil=DjW-X6jomBqBmM%253A%253Bk3TFJA7h4Hu5yM%253Bhttp%25253A%25252F%25252Fforum.arduino.cc%25252Findex.php%25253Ftopic%2525253D243653.0&source=iu&pf=m&fir=DjW-X6jomBqBmM%253A%252Ck3TFJA7h4Hu5yM%252C_&usg=__y-E6nlxoFgeWaZW9OJ5ZwOW-0Js%3D&ved=0ahUKEwj2j7rMi_PKAhUEWxoKHUSHBOkQyjcIMQ&ei=B0S-VrbwKoS2acSOksgO#imgrc=DjW-X6jomBqBmM%3A

Idea was to test it with the first digital pin, last digital pin and last analogue pin

Please read The care and feeding of LEDs. therefore higher voltages doesn't blow it up - however you are asking why your board isn't working properly.

@HollandWilson multimetre reports no voltage. I tried pins 5 and 15.

@NickGammon still doesn't work on pins that I haven't used, tested with the mutimetre

@Matthew I think you are confusing pin numbering. It is digital pin #n and analog pin # not the nano physical pin #. What you call 5 and 15 are digital pin 2 and 12,

@Matthew Numbers between 2 to 13 and A0 to A7 are accepted as valid pin numbers. The digitalWrite function expects the digital/analog pin number not physical pin number. In addition to that you've probably blown the physical pins 5 and 15 by drawing too much current.

I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything.
No, the LED doesn't need a resistor ...
because I tested it with the 5v and 3.3v therefore higher voltages doesn't blow it up

Sounds to me like you have damaged your output pins. Read The care and feeding of LEDs by Mike Cook.
The LED may briefly light up, but without a resistor you are damaging both the LED and the output pin. It is no surprise then, that afterwards the pins "none output anything".
Without a limiting resistor the output driver on the Arduino is overloaded and may burn out. Whether you have damaged the LED, the pin, or both, is hard to say.

(Edited to add)

still doesn't work on pins that I haven't used ...

Can you slow down a bit?

I've tested pins 26 (serial) ...

There is no pin 26 from the IDE point of view. On the board pin 26 is A7 (analog input 7) which cannot be used for digital input/output.
Please specify exactly what pin you tried (just choose one) and stick to the Arduino number (printed on the board, eg. D05) and then show the code you used to access that pin.

According to this ... the analogue pins can be used just the same as digital pins

That page shows a Uno. You have a Nano.
See Arduino Nano - Arduino.cc. On that page:

Analog pins 6 and 7 cannot be used as digital pins.

Added extra stuff to address comment about "still doesn't work".

According to this, http://waihung.net/arduino-tip-turn-your-analog-pins-into-digital-io/, the analogue pins can be used just the same as digital pins...

See amended answer. He shows a picture of a Uno. Don't believe everything you read on the Internet. In your case you have extended what one person said about one Arduino to think it applies to every Arduino.

I've managed to half fix the problem; I can use analogue pins as digital from A0 to A5, by referencing the pins as A+num rather then their physical location. However, the IDE doesn't recognise any D+num, so I still can't use the normal digital pins...

Digital pin 2 is just 2. For example: digitalWrite (2, HIGH); and for analog pins: digitalWrite (A3, HIGH); These are "board" pins, not the pins on the processor chip.

It seems I was getting all the pin numbers wrong... All pins work fine without the resistors.

No, the LED doesn't need a resistor ...
That is correct, but the processor I/O - output pin - does.
Check the schematic to see how RX /TX LEDs are connected.

So do the RX/TX pins have integrated resistors?


text:
Double ## in macros
I was looking at some macro use in an Arduino code. I believe what this macro does is it expands into a state that basically sets a pin to either input or output, but I'm a little confused about everything going on in this macro.
I do understand the point behind the do{...} while(0), but I'm sure what the ## are accomplishing. Also, what if anything do the underscores before DDR and PIN do? I would very appreciative of a simple clarification. Thank you!
#define MASK(PIN)  (1 << PIN)

/// set pin as input
#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)
/// set pin as output
#define _SET_OUTPUT(IO) do {DIO ##  IO ## _DDR |=  MASK(DIO ## IO ## _PIN); } while (0)

## is the concatenation operator in macros. It joins two macros or pieces of text together when expanded.
#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)

_SET_INPUT(3);

woukd expand to:
do {DIO3_DDR &= ~MASK(DIO3_PIN); } while (0);

You can read more about how it works here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

It seems that SE's syntax highlighting can't handle those macros. Should it maybe be reported?


text:
How to perform action if two rfid tag UIDs have been detected?
I'm using an rfid-rc522 and I want to print to the serial a string of text if two rfid tags have been read in a given time period.
Essentially this:
 1. First tag is read (print to serial: Tag 1 has been read)
 2. Wait 2 seconds
 3. Second tag is read (print to serial: Tag 2 has been read)
 4. Print to serial: Tag 1 and Tag 2 has been read)
 5. Bonus: Keep this state - and then when a button is pressed (print to serial: Tag 1 and Tag 2 are finished)
I know how to read the UID and print to the serial if one is read.
Thank you so much for your help, it's greatly appreciated.
Here is my code so far:
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>
#include <MFRC522.h>

// For the breakout, you can use any 2 or 3 pins
// These pins will also work for the 1.8" TFT shield
#define sclk 4  // SainSmart: SCL
#define mosi 5  // SainSmart: SDA
#define cs   6  // SainSmart: CS
#define dc   7  // SainSmart: RS/DC
#define rst  8  // SainSmart: RES

Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk, rst);

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  Serial.print("Starting cornhole leaderboard...");
  mfrc522.PCD_Init(); // Init MFRC522 card
  Serial.println("Scan PICC to see UID and type...");
  // Use this initializer if you're using a 1.8" TFT
  tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab

  // Use this initializer (uncomment) if you're using a 1.44" TFT
  //tft.initR(INITR_144GREENTAB);   // initialize a ST7735S chip, black tab

  Serial.println("Initialized");

  uint16_t time = millis();
  tft.fillScreen(ST7735_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);

  // large block of text
  tft.fillScreen(ST7735_BLACK);
}

void loop() {

  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    if (mfrc522.uid.uidByte[0] == 0xA4 &&
       mfrc522.uid.uidByte[1] == 0xB8 &&
       mfrc522.uid.uidByte[2] == 0xB8 &&
       mfrc522.uid.uidByte[3] == 0x96) {
          Serial.println("Nate has checked in to the game.");
          tft.fillScreen(ST7735_BLUE);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_YELLOW);
          tft.print("Nate ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);
    }

    if (mfrc522.uid.uidByte[0] == 0x03 &&
       mfrc522.uid.uidByte[1] == 0xFD &&
       mfrc522.uid.uidByte[2] == 0xBC &&
       mfrc522.uid.uidByte[3] == 0x02) {
          Serial.println("Ted has checked in to the game.");
          tft.fillScreen(ST7735_RED);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_CYAN);
          tft.print("Ted ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);

    }

}

What you can do is store the current time whenever a card is swiped, and then when another card is swiped check how long it's been since the last card was swiped
first create a couple of variables
unsigned long swipedTime;
int tag1 = 0;
int tag2 = 0;
int swipeTimeOut = 10000; // how much time in MS you have to swipe both cards

Next we'll jump down to where where you read the cards.
      if (mfrc522.uid.uidByte[0] == 0xA4 &&
           mfrc522.uid.uidByte[1] == 0xB8 &&
           mfrc522.uid.uidByte[2] == 0xB8 &&
           mfrc522.uid.uidByte[3] == 0x96) {

               ........

               if (tag2 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }

                tag1 = 1;
                swipedTime = millis();
        }

        if (mfrc522.uid.uidByte[0] == 0x03 &&
           mfrc522.uid.uidByte[1] == 0xFD &&
           mfrc522.uid.uidByte[2] == 0xBC &&
           mfrc522.uid.uidByte[3] == 0x02) {

               ........

               if (tag1 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }
                tag2 = 1;
                swipedTime = millis();

         }

You'll also want to come up with a system for resetting tag1 and tag2 to 0 or "checking them out".

You could try:
byte tag1[] = {0xA4, 0xB8, 0xB8, 0x96};
byte tag1_read = 0;    // flag is set when tag 1 is read
byte tag2[] = {0x3, 0xFD, 0xBC, 0x02};
byte tag2_read = 0;    // flag is set when tag 2 is read

int BUTTON = 3;

void setup(){
    pinMode(BUTTON, INPUT_PULLUP);  //set button as input pulled high
    .... // the rest of your setup()
}

void loop() {

  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    if (tag1_read == 0 && memcmp(mfrc522.uid.uidByte, tag1, 4) == 0){
          Serial.println("Tag 1 has been read.");
          tag1_read = 1;   //tag 1 has been read
          //delay(2000);   //not sure why u need the delay
    }

    if (tag1_read && tag2_read == 0 && memcmp(mfrc522.uid.uidByte, tag2, 4) == 0) {
          Serial.println("Tag 2 has been read.");
          tag2_read = 1;    // tag 2 has been read
          Serial.println("Both tags have been read.");
    }

    if (digitalRead(BUTTON) == LOW && tag1_read && tag2_read){
        Serial.println("Both tags are finished.");
        tag1_read = 0; tag2_read = 0;
    }
}

This code assumes the cards must be presented and read in order.


text:
Connecting arduino to an existing circuit
I have a little clock with a button on it that i need to push four times every second hour. I am trying to get the arduino micro to do it for me.
I am trying to figure out how to connect the arduino to trigger it. The clock is operated by a CR2 (3.0V) cell battery. Is there a way to do this without a transistor? If not what do i need? How can i find out how much amp my circuit requires?
The red arrow is pointing on the cable i think triggers the clock, and i think the black arrow is pointing on the cable that is the clock gnd.
(edit: I have found similar questions explaining the process with transistor, but not without..)

What happens if you do not push the button four times every second hour?

This might be answerable by someone who has the same model of clock to test, but its otherwise unlikely unless you add a bunch of information. Eg:  What brand and model is it?  Is it battery operated? What's the battery voltage if so?  Do you have a digital voltmeter to take measurements?  Do you have an oscilloscope to look at waveforms?  By "black cable is the clock gnd", do you mean the red wire with a black arrow pointing to it, or do you mean that bit that appears to be a black wire next to a gray wire, near test point P14 at lower left?

The voltage of the battery is 3.0V. "black cable" should be "black arrow". I have a digital voltmeter and when a push the button with the yellow arrow it is connection between the the cables that i have pointed out with arrows.

Guess an opto-isolator could work. https://en.wikipedia.org/wiki/Opto-isolator

@MikaelPatel Have you never watched Lost?

Why is a transistor not allowed? If it's a case of doing it with only the Arduino then you may struggle to achieve it. If you don't care how it's done so long as it doesn't use a transistor then you may have more luck. However, a transistor is by far and away the easiest solution; a MOSFET doubly so.

You might try attaching an Arduino IO through a resistor to pin 4 (where your red arrow points), and Arduino ground to pin 1 (where your black arrow points).  Because the clock is battery-operated, you can connect its ground to the Arduino's ground without problem.
Before attaching the Arduino, use your DVM to measure the voltage between pins 4 and 1, with the switch open and with the switch closed.  In following, I'll suppose you have measured 3V when the switch is open and 0V when it's closed.  This would indicate that the clock's circuit pulls or drives pin 4 high when the switch is open.  In initial experiments, I'd start with a 1KΩ or so resistor (eg, any resistor between 500Ω and 2000Ω) in series with an ammeter and the Arduino IO.  If you measure at most a few microamps of current in both the “switch open” and “switch closed” cases (see below) then the circuit should function ok with the resistor in place (since there will be only a tiny voltage drop across it).  [If, on the other hand, you measure several milliamps of current in either case, then my ideas about the clock circuit might not apply; in which case you might need an optoisolator or relay.]
To represent switch operation, put the Arduino IO into INPUT mode to represent an open switch, and into OUTPUT LOW to represent a closed switch.  For example, in setup() say
pinMode(ClockPin, INPUT);  // Also does digitalWrite(ClockPin, LOW);

and in your loop() say stuff like
if (TheTimeHasCome) {
   for (int k=0; k<4; ++k) {
      pinMode(ClockPin, OUTPUT);  // Presses the button
      delay(50);                  // Holds the button
      pinMode(ClockPin, INPUT);   // Releases the button
      delay(50);                  // Wait between buttons
   }

The comment // Also does digitalWrite(ClockPin, LOW); is a reminder that pinMode(ClockPin, INPUT); has two actions: it sets ClockPin to be an input instead of an output, and takes the corresponding PORTx bit low (ie, resets a bit in PORTB, PORTC, PORTD, or whatever).  If we had said pinMode(ClockPin, INPUT_PULLUP);, then the corresponding PORTx bit would have been set high, and the pin would be weakly pulled to Vcc, eg +5V.  It would be a mistake to send 5V to the clock, as it's likely that would exceed its voltage tolerance.
Since pinMode(ClockPin, INPUT); leaves the appropriate PORTx bit low, there is no need to use digitalWrite() separately in the sketch.  When ClockPin is an input, its high impedance allows the clock to pull pin 4 high; when ClockPin is an output, its 0 level connects pin 4 to pin 1.

Yes, This can be achieved without a transistor.
As the circuits would be on isolated power supplies: Arduino circuit on one and the clock on another, you can use a Solid State Relay.

Use the relay with your Arduino (5v or 3.3v) and wire the relay contacts parallel to the clock switch. This will isolate any power issues as clock will be powered with its own power and Arduino will be powered with its own.
You can program Arduino with proper delays to actuate the relay accordingly.
Hope this helps.

Very few relays will have a coil current low enough to allow it to be powered directly from an Arduino - you'll need a transistor for the relay.

@CharlieHanson thanks for the pointer; a SSR is also a relay. I'll update my answer.

Connect the Arduino and your clock grounds together.
Get a small resistor - no less than 1 kOhm - and connect your VOM (in current mode) in series with the resistor and your Arduino output pin.
Set the output pin to LOW and observe
Did the clock reset?
What was the current on your VOM?
If the clock reset and the current was more than 20 mA get a bigger ( 10 kOhms )  resistor and try it again.
If the clock reset and your current was less than 20 mA you are done.
And if you really want to isolate the clock from Arduino use low current LED and connect the cathode to the output pin and anode to the clock.
Keep the resistor in the circuit.
Than you will also have an indicator of "circuit is active".

authors: Асмир Абдимажитов