body:
This is completely acceptable for your intended purpose.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form using an Arduino is overkill.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form adding an Arduino is overkill.

When it comes to playing overkill can be good :-)

________________________

**To use it to provide input to an Arduino and NOT to a mains level light:**

**NB** relay contacts may only be connected to mains for light switching **OR** to the Arduino. **NEVER** to both at the same time.

Connect it's DC supply input to your Arduino (or other) power supply.
As long as the **supply** can provide 40 mA when needed it will work OK.
40 mA is a **power supply** rating This is unrelated to the Arduino pin loading.

Connect the output to an Arduino digital pin configured as an input.

![enter image description here][1]

The output is a relay, activated when an object is sensed.
When inactive the centre pin is probably connected to the right pin - Check with Ohm meter.

When activated the left pin in connected to the centre pin (see their diagram)

Connect ground to right pin.
Connect Arduino digital input to centre pin.
Connect a "high" level to left hand pin.
OR as Majenko suggests, just set the pin to have pullups enabled.

If connecting to V+ as shown then V+ can be Vcc  (=5V for a 5V Arduino, 3v3 for a 3V3 Arduino)
DO NOT set V+ to higher than Arduino's Vcc.
You can connect a say 1k to 10k resistor from V+ to the voltage source bur still do not set V+ above Vcc.
OK - just have pullups enabled:-)

eg (untested)

> int ADCMode = 0;
 int PIRPin = 6;                 // PIR connected to digital pin 6
 void setup()
 {
   pinMode(PIRPin, INPUT_PULLUP); // set PIRpin as input with pullup
 }
 void loop()
 {
  ...
   ADCMode  = digitalRead(PIRpin);   // $Read PIR status
 ...
 }

When the circuit activates digitalRead() will return a high.
When the circuit is not activated digitalRead() will return a low.

__________________

See [here](http://www.arduino.cc/en/Tutorial/DigitalPins) re Arduino pin modes

  [1]: https://i.stack.imgur.com/HrPkj.jpg


sender: user

message:
ESP8266 and Arduino Interfacing

I have connected Arduino with ESP8266 with

Arduino pin 2 connected to ESP's Tx Arduino pin 3 connected to ESP's Rx via Voltage Divider Arduino GND connected to ESP's GND Arduino 3v3 connected to ESP's CH_PD

I have powered ESP8266 using 1117 Voltage regulator

When I initially bought ESP8266 it was working properly(I could even set up a server) but now when I connect it to Arduino an endless stream of garbage values is seen on the Serial Monitor...

The arduino is programmed with the following code

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {
      Serial.begin(9600);
      esp8266.begin(9600); // your esp's baud rate might be different
    }

    void loop()
    {
      if(esp8266.available()) // check if the esp is sending a message
      {
        while(esp8266.available())
        {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
        }
      }

      if(Serial.available())
      {
        // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
        // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
        // but we want to send everything at the same time.
        delay(1000);

        String command="";

        while(Serial.available()) // read the command character by character
        {
            // read one character
          command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
      }
    }

sender: assistant

body:
There is a new command for the ESP8266 in AT version:0.50.0.0 - SDK version:1.4.0 that lets you explicitly set the full UART configuration:

`AT+UART_CUR` – set the current UART configuration
This command sets the current UART configuration; it does not write to the flash. Hence there is no change in the default baud rate.

For example:

`AT+UART_CUR=9600,8,1,0,0`


message:
GPS logging on the intel edison breakout board

I'm working on my project car, and I have decided I would like to have a GPS and log some sensors too. I'm just at a bottle neck here, the sensors I have brought pull about 7v each where I can't pull that much from the breakout board that I have, and I can't seam to get the GPS to work.

I've tried using ths code but software serial isn't supported on the edison:

    // GPS Setup
    #define rxGPS 0
    #define txGPS 1
    SoftwareSerial serialGPS = SoftwareSerial(rxGPS, txGPS);
    String stringGPS = "";

    void setup() {
      pinMode(rxGPS, INPUT);
      pinMode(txGPS, OUTPUT);

      Serial.begin(9600);
      Serial.println("Started");

      // GPS Setup
      serialGPS.begin(4800);
      digitalWrite(txGPS,HIGH);

      // Cut first gibberish
      while(serialGPS.available())
        if (serialGPS.read() == '\r')
          break;
    }

    void loop()
    {
      String s = checkGPS();
      if(s && s.substring(0, 6) == "$GPGGA")
      {
        Serial.println(s);
      }
    }

    // Check GPS and returns string if full line recorded, else false
    String checkGPS()
    {
      if (serialGPS.available())
      {
        char c = serialGPS.read();
        if (c != '\n' && c != '\r')
        {
          stringGPS  = c;
        }
        else
        {
          if (stringGPS != "")
          {
            String tmp = stringGPS;
            stringGPS = "";
            return tmp;
          }
        }
      }
      return false;
    }

Any ideas or help would be much appreciated

body:
Try this:

    String GPSLine;

    bool checkGPS()
    {
      while(serialGPS.available())
      {
        char c = serialGPS.read();
        if(c == '\n') return true;
        if(c == '\r') continue;

        GPSLine += c;
      }
      return false;
    }

    void loop()
    {
      if(checkGPS())
      {
        Serial.println(GPSLine);
        GPSLine = "";
      }
    }


body:
You might try my [NeoGPS](https://github.com/SlashDevin/NeoGPS) library.  It has a diagostic program and some good information in the [Troubleshooting section](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Troubleshooting.md).  And NeoGPS doesn't use the `String` class, although you can safely waste lots of RAM on the Edison.  :P

For an Edison build, you may have to change the PACKED_DATA configuration item, described [here](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Configurations.md#platforms).

(This is an Arduino product, right?)


message:
How do you call to a previous function?

I'm using an Arduino to control a reverse osmosis machine, I would like after a certain number low pressure events to return to the testing routine. Can you call to previous functions?

body:
What do you mean by "previous"? In the call stack or in the code?
Either way, you can call any (public|member|static) function you want at any time, even call the very same function you're already in (recursion, but not recommended on Arduino or any other embedded system).


body:
You need to get your head around the Finite State Machine (FSM).

It is a programming method which allows your program ("Machine") to be in any of a certain number ("Finite") of states ("State").  One state would be reading pressure. Another state would be "testing", or whatever.

I wrote a tutorial ages ago about it: http://hacking.majenko.co.uk/finite-state-machine


message:
Adafruit_GFX setRotation not working when called from within a class

Using an ILI9341. I'm trying to set the rotation from within a class, but it's not working.  The code is very straight forward.

If I rotate in the class, the setRotation code does not work but the text is still printed. The pointer is set properly and the text is still printed, it just doesn't get rotated.

Outside of the class, the rotation works fine.

Any help would be greatly appreciated!

    #include "SPI.h"
    #include "Adafruit_GFX.h"
    #include "Adafruit_ILI9341.h"

    #define TFT_DC 5
    #define TFT_CS 3

    Adafruit_ILI9341 *tft;
    uint8_t newRotationAngle = 0;

    void drawStuff() {
        tft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
        tft->fillRect(0, 0, tft->width(), tft->height(), ILI9341_BLACK);
        tft->setCursor(0, 0);

        tft->print(F("01234567890"));
        delay(250);
    }

    class test {
    public:
        void init(Adafruit_GFX *_p) { ptrTft = _p; };

        void inClassRotation(int newRotation) {
            ptrTft->setRotation(newRotation);
            drawStuffInClass();
        };

        void drawStuffInClass() {
            ptrTft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
            ptrTft->fillRect(0, 0, ptrTft->width(), ptrTft->height(), ILI9341_BLACK);
            ptrTft->setCursor(0, 0);

            ptrTft->print(F("01234567890"));
            delay(250);
        }

        Adafruit_GFX *ptrTft;
    };

    test instance;

    void setup() {
        tft = new Adafruit_ILI9341(TFT_CS, TFT_DC);

        tft->begin();
        tft->setTextSize(2);

        instance.init(tft);
    }

    void outsideClassRotation(Adafruit_GFX *passed) {
        passed->setRotation(newRotationAngle);
        drawStuff();
    }

    void loop(void) {
        newRotationAngle++;

        // This works. No problems.
    //    outsideClassRotation(tft);

        // This does NOT rotate but still prints the text fine.
        instance.inClassRotation(newRotationAngle);

    }

body:
I would actually be quite surprised if `outsideClassRotation()` actually
worked. My guess is that _it does not work as is_. Maybe it did work at
some point, but then you made some subtle changes to your code and did
not check that it is still working.

Here is the deal: there are two `setRotation()` methods:

- `Adafruit_GFX::setRotation(unsigned char)` does very little besides
  storing the rotation angle... which is not used anyway.
- `Adafruit_ILI9341::setRotation(unsigned char)` actually sends commands
  to the LCD asking it to apply the rotation; this is the method you
  want.

The problem is that _these methods are not `virtual`_, which means that
when you call them through a pointer, as in
`some_pointer->setRotation(the_angle);`, you get the method
corresponding to _the type of the pointer_, not the type of the actual
object. For example:

<!-- language: lang-c++ -->

    tft->setRotation(the_angle);     // calls Adafruit_ILI9341::setRotation()
    ptrTft->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()
    passed->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()

I checked this by uncommenting your call to `outsideClassRotation()` and
disassembling the compiled binary: both times you are calling
`Adafruit_GFX::setRotation()`.

**Solution**: change your `Adafruit_GFX *` pointers to be of
type `Adafruit_ILI9341 *`, or patch Adafruit\_GFX.h to make
`setRotation()` virtual.


message:
Spilt string and convert to float to compare

I'm transmitting: Temperature: 28.22C

and on the receiving end I'm receiving the whole tranmission as a string. I'm trying to spilt Temperature to leave it as a string and 28.22 as a float to compare, how do I do that ?

TX end hardware: (Arduino Uno board with Xbee S1)  to computer
RX end hardware: (Arduino Uno board with Xbee S2)  to computer

body:
I suppose your communication is working... In order to retrieve a floating number from a string you might use toFloat() function. You can watch the reference page [here][1] to understand how does it work.

  [1]: http://www.arduino.cc/en/Reference/StringToFloat


body:
Okk very simple approach :-

Suppose this is your string variable inStr = "Temperature: 28.22C"

    String inStr = "Temperature: 28.22C";
    int indexOfSpace = inStr.indexOf(' ');
    //this stores the address of the space character in the string.
    int indexOfC = inStr.indexOf('C');

    String Temp = inStr.substring(indexOfScace+1,indexOfC);
    //as the parameter for the function is supposed to be the starting point of the string to
     be extracted and one more than its ending point.

    //Now to convert to float

    float TempFlo = Temp.toFloat();


message:
esp8266 esp-01 crashing, restarting over and over

I flashed my ESP-01 with the [nodemcu firmware 512k version][1], and everything was working fine.  I testing some lua scripting on init.lua and it was working.  Then, after writing a bunch of code and uploading, the module restarted.  And it restarted.  And it's still restarting, over and over again, and prints to serial

    CÀbc0°ýbcü¨HøNodeMcu 0.9.4 build 20141230  powered by Lua 5.1.4
    ö,3bþÈH

It was always printing the garbage in there before, so I'm not worried about that.  However, I can't send anything to the device--I can't send serial commands, or reflash the device.  I'm thinking I overloaded the memory or something.  Anyone have any ideas for recovering this brick?

  [1]: https://github.com/nodemcu/nodemcu-firmware

body:
Turns out I was pulling up on the GPIO0 pin, instead of down.  Ensure you have the correct pin-out when flashing.

ESP-01 VCC - 3.3v Serial Adapter
ESP-01 GND - Ground or Minus Serial Adapter
ESP-01 RX - Connect to TX on Serial Adapter
ESP-01 TX - Connect to RX on Serial Adapter
ESP-01 CH_PD - 3.3v Serial Adapter
ESP-01 GPIO0 - Pull low by connecting to ground / minus

There also seems to be a problem with NodeMCU not clearing variables in the Ram, so Ram fills up as you run, and this causes the module to crash upon restarting, over and over.  That is also what was happening.  There is some problem with wifi.sta.getap() that exacerbates this.


message:
Fading the brightness of LEDs using MAX7219 and PWM

I am doing a project with bi-color led matrix 8x8 and MAX7219 as the LED driver. I want to implement a fading effect on the LEDs, like mixing the two colors by varying the individual duty cycles.

My idea is the use of the `Iset` parameter; I would connect the PWM pin from Arduino through the `Rset` resistor and feed that into the Iset of the MAX7129 instead of 5V supply. Please suggest whether or not this is possible, if not what can be the alternative approach?

body:
This is possible in two ways:

 1. The MAX72xx has its own internal intensity control register. From the datasheet:

> Digital control of display brightness is provided by an internal pulse-width modulator [...]. The modulator scales the average segment current in 16 steps from a maximum of 31/32 down to 1/32 of the peak current set by RSET [...].

This of course requires no extra components or effort, but you are limited slightly by only a 4-bit intensity resolution. Also, there is no 'off' so you'd have to either manually blank the displays or put the ICs into shutdown mode.

 2. Your suggested way is possible. However, the low frequency of the Arduino's PWM may lead to flickering if the MAX7219's internal segment current reference driver needs a steady voltage. You'll have to consider smoothing the PWM output through a low pass filter - the TL072/TL082 has two op-amps so you can use one for colour A and the other for colour B. I'd choose an op-amp over passive filtering because the current drawn from the Arduino will be negligible and the stability of the current into the MAX7219 will be improved.


message:
Simple LED circuit is not working

This is my first circuit ever (!) and so I'm hoping that I'm just making an easy-to-spot rookie mistake. I am trying to power an Arduino Due with a 9V battery and then have the Due in turn power a red LED. No blinking. No sketchpad/C program flashed to the chip. Just straight up electricity:

![enter image description here][1]

When I connect the battery, several things happen:

 1. There is a green power LED on the Due that lights up; and
 2. Right next to it is an orange LED (on the Due itself) that blinks every few seconds (not sure what this LED is or what the blinking means, but providing that detail for good measure); and
 3. The red LED on the breadboarrd does **not** light up

This is a 2V/15mA LED, and as you can see I'm powering it from the 5V power jack on the Due. So a 220 ohm resistor should be perfect for it (`R = (Vs - V) / I = (5V-2V) / .015A ~= 220 ohms`).

So, for the first time ever, I busted out my multimeter, set it to the voltage setting, and started testing the circuit. First I tested `Vin` and `GND` on the Due (that is, the connection between the battery and the Due), and the multimeter lit up and hovered (correctly) around 5V. So far so good. Next I tested the power and ground connections on the breadboard power rails (indicated in green above). Again, the multimeter reported a roughly 5V power supply. Then I tested the connection from the power rail to the row (purple in pic above) feeding power to the resistor, and to my surprise, the multimeter reports **no power** at those two purple locations.

My *understanding* was that the power rail will power the entire column its connected to (in my case, the left-most column), and then any rows connecting to a power rail/column will also be powered. So I'm not understanding why there's voltage on my power rail/column, but not on the wire connecting my power rail to the resistor. Any ideas?

---

### Update:

Here is my corrected circuit per initial feedback. Please note this is still not working, but I think I'm getting close:

![enter image description here][2]

  [1]: https://i.stack.imgur.com/1dQW0.jpg
  [2]: https://i.stack.imgur.com/lxCrP.jpg

body:
It looks like you've got confused between columns and rows.

You are correct that the power rails run the length of the breadboard -- these are seen as the top and bottom pairs of rows in the diagram below (ignore the middle row). However, the rest of the board is connected up as separate columns. Each column is independent of its adjacent columns.

![breadboard diagram][1]

This means your red wire going from the power rail to the resistor is connected correctly. However, the other end of your resistor is currently going nowhere. It needs to be in the same column as the anode of your LED.

  [1]: https://i.stack.imgur.com/QqY3n.gif


body:
What connects the resistor to the LED?

![enter image description here][1]

Absolutely nothing.

It's hard to work out which holes the LED is plugged into, but I think your current circuit looks something like this:

![enter image description here][2]

You need to connect that resistor and LED together.

For your edit:

Now your circuit looks like this:

![enter image description here][3]

Behind the 5 pins in that column with the ground wire there is a big chunk of metal connecting them all together.  It's no different to if you'd taken the LED and twisted the pins together into one.  There's no way the power can get up one and down the other when they are connected together like that.  You need to separate them into different columns.

And this is how the (black) connections inside are laid out, and how your (red) electricity is flowing:

![enter image description here][4]

And here is how the circuit should look, using a program called Fritzing.  It's a pretty basic design tool, but great for showing wiring.

![enter image description here][5]

You can see how the green highlighting shows the columns that are connected.

  [1]: https://i.stack.imgur.com/E3mmD.png
  [2]: https://i.stack.imgur.com/moMz2.png
  [3]: https://i.stack.imgur.com/zM9rH.png
  [4]: https://i.stack.imgur.com/7Q11H.jpg
  [5]: https://i.stack.imgur.com/X23yu.png


message:
How do I know when the connections is ready between Arduino and QSerialPort

I am trying to send data from QSerialPort to Arduino Mega 2560. The proccess always takes some time to establish the connection.

***How do I know with QSerialPort is the connections is ready to send data?***

I don't know how much time do I have to wait for that and it happens every time when I run the application.

The configuration of my QSerialPort instance is:

    mSerialPort = new QSerialPort();
    mSerialPort->setPortName("COM3");
    mSerialPort->setBaudRate(QSerialPort::Baud9600);
    mSerialPort->setDataBits(QSerialPort::Data8);
    mSerialPort->setParity(QSerialPort::NoParity);
    mSerialPort->setStopBits(QSerialPort::OneStop);
    mSerialPort->setFlowControl(QSerialPort::NoFlowControl);
    mSerialPort->open(QIODevice::ReadWrite);

I check the device configuration of COM port:

![enter image description here][1]

I also changed and play the Arduino delay but nothing changed.

I am sending to Arduino little piece of data. Example:

    X100.10,Y10.23, H9999, ...others

And these data work when I am debugging the functions of my application. Everything is writting and work. So I am lost.

I hope all this information be usefull to give me an answer or at less some tips.

  [1]: https://i.stack.imgur.com/TVVu0.png

body:
I am guessing that what you are seeing is not the port taking some time to open, but the Arduino resetting as soon as you open the serial port.  That means there is a short time while it's in the bootloader looking for an "I am here" signal from avrdude.  The timeout of that signal is configured in the bootloader, and is usually something like 1 second.

The simplest thing you can do is, as one of the first commands in your program, send an "I am ready to receive" signal to the computer (maybe just the word "OK" or something like that), which you then wait for before sending your data.


message:
How do I print the reading serial data sending from Arduino

I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert  the data to read.

![enter image description here][1]

You can see the receive data has some no printer character.

# Workflow of sending and receiving data between QtSerialPort and Arduino

### Sending Data with QtSerialPort

    void MainWindow::sendData(){

        QString m_allData = m_sendEdit->toPlainText();
        int i = 0;
        int size = m_allData.size();

        QString line = "";
        int c = 0;
        while(i < size){
            line.append(m_allData[i]);
            if(c == 24){
                int sended = m_serialPort->write(line.toUtf8(), 24);
                m_serialPort->flush();
                line.clear();
                c = 0;
            }
            i++;
            c++;
        }
        if(c > 0){
            m_serialPort->write(line.toUtf8(), c);
        }
        m_serialPort->flush();
    }

I want to send the data with a buffer size of 24 bytes.

### Reading and Sending Data with Arduino

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

     void loop() {

      delay(1000);

       if (Serial.available() > 0){
         short i = 0;
         int size = Serial.available();
         String data = Serial.readString();
         Serial.print(data);
        }
     }

The Arduino code is simple.

### Receiving Data with QtSerialPort

    void MainWindow::readData(){
        int c = 0;
        char * dataBuffer;
        int size = m_serialPort->bytesAvailable();
        dataBuffer = new char[size];
        c = m_serialPort->read(dataBuffer, size);
        m_receiveEdit->setText(m_receiveEdit->toPlainText() + QString::fromUtf8(dataBuffer));
            delete dataBuffer;
    }

I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?

  [1]: https://i.stack.imgur.com/EaziF.png

body:
You have no warranty that Qt will receive the whole message in a single
chunk. It may receive "no se" as the first chunk, and then "q pasa" as
the second chunk. Since `dataBuffer` is dynamically allocated, it
initially contains garbage, and you are printing the part of this
garbage that you did not overwrite.

An easy fix would be to simply NULL-terminate the buffer:

<!-- language: lang-c++ -->

    dataBuffer = new char[size + 1];            // + 1 byte for '\0'
    c = m_serialPort->read(dataBuffer, size);
    dataBuffer[c] = '\0';                       // terminate the string


message:
How do I receive more that 64 bytes with Arduino

I am using QtSerialPort to send and receive data from Arduino. I am sending **more than 64 bytes** (125, 220, more), I receive the data with Arduino, and trying to sending back the same data, but Arduino **sending only 64 bytes** in its response. Then I am thinking that the problem is with Arduino buffer. I am trying to clear the data but without result.

Here is my Arduino code:

    void loop() {
     if (Serial.available() > 0) {
      int i = 0;
      delay(500);
      int size = Serial.available();
      while (i < size)
       buffer[i++] = Serial.read();

      Serial.print(buffer);
      //delay(500);
      int j = 0;
      while (j < size)
       buffer[j++] = '\0';
      //while (Serial.available()) Serial.read(); I tried it
      //Serial.flush(); Also tried it, but nothing.
     }
    }

body:
Instead of blocking the loop for 500 ms, you should be actively
reading the data as it comes. Otherwise the internal buffer of the
`Serial` object will overflow after only 64 bytes are received.

Here is an example that copies the incoming bytes into a larger buffer
(256 bytes) and, upon receiving an end-of-line character, echoes
back the whole line.

<!-- language: lang-c++ -->

    void loop() {
        static char buffer[256];
        static size_t pos;              // position of next write

        while (Serial.available() && pos < sizeof buffer - 1) {

            // Read incoming byte.
            char c = Serial.read();
            buffer[pos++] = c;

            // Echo received message.
            if (c == '\n') {            // \n means "end of message"
                buffer[pos] = '\0';     // terminate the buffer
                Serial.print(buffer);   // send echo
                pos = 0;                // reset to start of buffer
            }
        }
    }


message:
Reading values from the register of a slave

I am trying to interface MPU6050 with arduino. Found a simple code online, but having a bit of trouble in interpreting it.

    // MPU-6050 Short Example Sketch
    // By Arduino User JohnChi
    // August 17, 2014
    // Public Domain
    #include<Wire.h>
    const int MPU=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
    void setup(){
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    Serial.begin(9600);
    }
    void loop(){
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
    AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
    AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    Serial.print("AcX = "); Serial.print(AcX);
    Serial.print(" | AcY = "); Serial.print(AcY);
    Serial.print(" | AcZ = "); Serial.print(AcZ);
    Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for   temperature in degrees C from datasheet
    Serial.print(" | GyX = "); Serial.print(GyX);
    Serial.print(" | GyY = "); Serial.print(GyY);
    Serial.print(" | GyZ = "); Serial.println(GyZ);
    delay(3330);
    }

Now there are a few things i want to ask regarding this code:
1. Here we have specified that the data from 3B register of the slave should be the first one and master will receive in total 14 bytes. In this case the 14 registers are continuous ([see datasheet here][1]) .Now how should i go about reading the values if i am interested in registers which are not continuous ,let us say alternative?

2.`AcX=Wire.read()<<8|Wire.read();`

This line is taking the first 8 bits and last 8 bits and forming a 16 bit number . But why do we need to shift the first 8-bits byte 8 places to left.Please explain how exactly this line works?

  [1]: https://www.olimex.com/Products/Modules/Sensors/MOD-MPU6050/resources/RM-MPU-60xxA_rev_4.pdf

body:
For reading non-consecutive bytes, the “normal” way would be to do a
one-byte request and a one-byte read for each byte you want. However, if
the bytes you want are close enough (e.g. you want every other byte), it
would be faster to do a contiguous read and just ignore the bytes you do
not want. E.g.:

<!-- language-all: lang-c++ -->

    byte data1 = Wire.read();  // read first byte
    Wire.read();               // read and ignore second byte
    byte data3 = Wire.read();  // read third byte

For your question regarding the meaning of
`Wire.read()<<8|Wire.read();`:

1. `Wire.read()` return a 16-bit integer, where the 8 most significant
   bits are zero and the 8 least-significant bits contain the actual
   data. In binary, it's something like `00000000xxxxxxxx`, where `x`
   are the data bits.
2. `<<8` means “shift left by eight positions”, where the missing bits
   are replaced by zeros. Thus `Wire.read()<<8` is `xxxxxxxx00000000`
   in binary.
3. The second call to `Wire.read()` return another 16-bit integer in the
   form `00000000yyyyyyyy`.
4. The vertical bar `|` is the bitwise-or operator: each bit of the left
   operand is or-ed with the corresponding bit of the right operand to
   give one bit of the result: `x or 0` is `x`, `0 or y` is `y`.
5. Then, the whole expression gives `xxxxxxxxyyyyyyyy`, where `xxxxxxxx`
   comes from the first `Wire.read()` and `yyyyyyyy` from the second.

The problem here is that the “first” and “second” `Wire.read()` in the
sentence above refer to the position of the call in the line, not to the
actual order in which the calls are performed. Thus you may be lucky and
get the the correct byte order... or not. You should instead do a single
read per statement if you want to control the byte order. For MSB first:

    AcX = Wire.read() << 8;  // read most significant byte first
    AcX |= Wire.read();      // then least significant byte

And for LSB first:

    AcX = Wire.read();        // read least significant byte first
    AcX |= Wire.read() << 8;  // then most significant byte


message:
Arduino Uno coding problem voltage varying

I was wondering whether anyone could help me... I am using an Arduino Uno and I am writing my code in the Arduino IDE. I am trying to implement the code so that the output voltage can be varied from 0 - 5 volts using 2 pushbuttons. I want to be able to increment the voltage by +0.5 volts from 0-5 volts every time I push Button A. Also I want to decrement the voltage by -0.5 volts from 5-0V every time I push Button B.

Example: (push Button A): output voltage 0.5: (push Button A): output voltage 1.0 etc.

So far when I upload my code the LED as my test for output just flickers between 2 - 4 volts. Can anyone tell me what I am doing wrong? I am not that good at coding so any help would be awesome.

Here is my code.

    int PWMPin = 6; // output pin supporting PWM
    int buttonApin = 8; // buttonA to pin 9 PWM
    int buttonBpin = 10; // buttonB to pin 10 PWM
    float value = 0; // read the value at 0
    float fadeValue = value;
    float counter = 0;

    void setup() {
      pinMode(buttonApin, INPUT);
      pinMode(buttonBpin, INPUT);
      pinMode(PWMPin, OUTPUT);
    }
    void loop() {
      int port = analogRead(0);
      port = map(port, 0, 10, 0, 255);
      analogWrite(6, port);
      if (digitalRead(buttonApin) == LOW, fadeValue) {
        if (counter >= 10) {
          counter = 10;
        }
        // fade from min to max in increments of 25.5 points: basically (0.5 volts)
        for(fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5) {
          counter = fadeValue;
          // sets the value (range from 0 to 255):
          analogWrite(PWMPin, fadeValue);
          delay(100);
        }
      }
      if (digitalRead(buttonBpin) == LOW, fadeValue) {
        if (counter <= 0) {
          counter = 0;
        }
        // fade from max to min in increments of 25.5 points: basically (0.5 volts)
        for(fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5) {
          counter = fadeValue;
          // sets the value (range from 0 to 255):
          analogWrite(PWMPin, fadeValue);
          delay(100);
        }
      }
    }

body:
There's a number of very basic things wrong with your code - things that aren't doing what you think, or you just telling it completely the wrong things.

Start by formatting your code properly (INDENTS!) and match up all your brackets.  You'll soon see what I see as far as what is wrong.

I'll give you some clues:

----

    {
    if (digitalRead(buttonApin) == LOW, counter)

Where to I start with that one...?

----
    for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)
      counter = fadeValue;
      digitalWrite(PWMPin, fadeValue);
C is not Python!

----

    digitalWrite(PWMPin, fadeValue);
Writing an analog value to a digital pin?!

----

    Serial.println(PWMPin);
Printing the pin number - now what is the point of that?

----

    ... fadeValue += 25.5 ...

Adding a float to an integer - bad practice (and ultimately pointless) - pick one, float or integer, and stick to it.

----

And then there is the whole logic of your program. I can't work out what it's supposed to be achieving.  It looks like you've tried to get it to do all sorts of parts of different things and not got it to do anything at all.  Strip it right out and get it to do ONE thing - provide a specific, STATIC, voltage.  Then add in some way of changing that voltage afterwards.


message:
Problems uploading sketch to Arduino Due

Windows 7 here. I just bought an [Arduino Due](http://www.arduino.cc/en/Main/ArduinoBoardDue) and downloaded the Arduino IDE. I wrote a simple "blink LED" program (see below) and am trying to flash it to the Due.

When I connected the Due to my laptop (via micro USB cable), I got a warning on my laptop that it could not find the correct device driver. So I followed the instructions discussed on [this excellent video tutorial](https://www.youtube.com/watch?v=fCxzA9_kg6s) and went into `Control Panel >> System >> Device Manager >> Arduino` and pointed it to load the appropriate device driver from `C:\Program Files (x86)\Arduino\drivers`. This got rid of the warning. Hooray!

I then Verified & Compiled my program:

    int led = 13;

    void setup() {
        pinMode(led, OUTPUT);
    }

    void loop() {
        digitalWrite(led, HIGH);
        delay(5000);
        digitalWrite(led, LOW);
        delay(5000);
    }

Great success! Now it was time for me to upload the program to my Due. The first time I tried to upload it, I got the following error:

    Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno"
    Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
    avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

        This report would have more information with
        "Show verbose output during compilation"
        enabled in File > Preferences.

So then in the IDE I went to `Tools >> Port` and changed the selection from `Serial` to `COM3` (again, sort of explained in that video tutorial). I tried to upload again:

    Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno"
    Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x09

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

        This report would have more information with
        "Show verbose output during compilation"
        enabled in File > Preferences.

I thought it was interesting that the IDE thinks this is an Arduino Uno. So then I went to `Tools >> Board` and changed the selection from `Uno` to `Duemilanove`, hoping that Due and Duemilanove are compatible for the programmer/flasher tool. This time the error was the same as last, except the first line reads:

    Arduino: 1.6.4 (Windows 7), Board: "Arduino Duemilanove or Diecimila, ATmega328"

So at least the IDE is switching board correctly. :-) I should note that my `Tools >> Board` menu **does not** have an "Arduino Due" option. And when I go to `Tools >> Board >> Board Manager`, searching for Due does not turn up anything either.

I also tried running the upload with verbose output, but that really didn't tell me anything more. I'm happy to post the exact verbose output but figured I could omit it here for brevity. I also *did* peruse the [troubleshooting link](http://www.arduino.cc/en/Guide/Troubleshooting#upload) that the error output recommends, but it looks like I've already exhausted all of those recommendations as well.

I'm stuck and frustrated, any suggestions?

What do I need to do to get the IDE programming my Due?

body:
> ... hoping that Due and Duemilanove are compatible for the programmer/flasher tool.

Not even close. You will need to go into the Boards Manager and download and install the SAM support files, select the Due from the list, and *then* upload the sketch.


body:
Yes, I just had this problem myself..
Unless you use the Boards Manager Menu and install the Arduino SAM Boards (32Bits ARM cortex M3) board info you will not be able to upload your sketch.
After installing in the Boards Manager you will see the Arduio Due programming port and Arduino Native port as an extra options at the bottom or the TOOLS>BOARD menu.
That should fix the problem.(Check which you are connected to and which COM port)
If you still have trouble, disconnect and reconnect the DUE and restart the IDE and if required restart you computer.

This seems to be a common problem when people switch from the Uno or MEGA to the Due. I'm surprised this is not installed as standard in the IDE. I am using 1.6.5r2.

Thanks also to Ignacio Vazquez-Abrams.


message:
Arduino Serial Queue

So I am programming an LED Music Visualizer that uses a combination of Processing and Arduino. I have it all working as I want to but there is a small problem. If I were to stop the music, then the Arduino will keep displaying the visualization for a few seconds. I believe that this issue would be caused by it "catching up" on new serial data from Processing like a queue. So my question is: When arduino uses the Serial.read() function, is it using the most recent value or is it using the next value received after the last one that it used, like a queue of values.

**Example**: Processing sends the values 1,2,3,4,5,6,7,8,9 over serial in 10 millisecond intervals. Arduino only performs Serial.read at 20 millisecond intervals. Would the arduino read the values 1,3,5,7,9 in or would it read the values 1-9 but in twice the time?

Sorry for the confusing question, hopefully somebody could shed some light. At the core, it is a question on how serial works, you can ignore the part about the music visualizer.

body:
It sounds like you figured most of your question out already.

 (Someone correct me here if I'm wrong). The Atmega 328p uC, I believe, has an 8 byte hardware buffer for RX serial data. In software, the Arduino core code defines a maximum ring buffer of 64 bytes that acts as a FIFO queue.

So, what does his mean? Let's just focus on the hardware buffer since it's fairly easy. Say you send your data 1,2,...,10 at 10ms intervals, and you read your data at 100ms intervals (for illustration purposes). The problem is that you send 10 bytes of data but only have room for 8 bytes. So, your first two values (1,2) are pushed out of the buffer and lost. This idea also illustrates a FIFO queue, first in first out.

The same idea can be extended to a ring buffer.

Anyway, like you said, this could explain your problem. If you have 64 bytes, which will obviously be full since your inevitably losing data (20ms read with a 10ms write), you'll be seeing the effects for 64 * 20ms = 1.28s. There's probably some processing delay too which will extend this delay, but it's more than likely minimal if it's efficient code.


body:
> Arduino only performs Serial.read at 20 millisecond intervals.

It sounds like you're using `delay` to pace the reads.  But why?  You'll start to lose data after reading just 3 or 4 characters (60ms to 80ms).  Serial at 9600 can send 1 character per millisecond, 20 times faster than you are reading them.

If you edit your post to include your code, we might be able to make a suggestion to eliminate that delay.


message:
Help understanding how to drive Step motors with Arduino

I am building a 2-Axis gantry system to dispense some thermal paste on boards. I was given two stepper motors in order to do so along with a gantry already built that will arrive in two weeks. So basically I just need to figure out how to drive them on the software side. However the boss demands testable code to be finished by EOB tomorrow, despite the hardware not being here yet. So I drafted some quick code that should drive a stepper motor, it's an easy open loop system, but I'm struggling. The operator will home the gantry after each cycle so it's just a matter of getting the motors moving.

My method was as follows:

    #include <Stepper.h>
    *declaring the stepper and all that goes here*
    void loop(){ etc.
       basic logic flow stuff
       stepper.step(20); // to move forward twenty steps
       stepper.step(-20) // to move back twenty steps

However my boss says this is incorrect as I need to be giving the steppers both *step* and *direction*.

 After some tenuous google searching he recommended I use the AccelStepper library to fix this problem. After looking through this library I'm unsure how this will give me anything I need (distances are so small acceleration is useless) and how I am not giving it both step and direction in my original example code, I give it steps (20) and a direction with my negative/positive coefficient.

Am I correct in my thinking? Is there a better solution neither of us have found? I'd love to understand not just that I'm wrong, but why I am.

body:
I think there is some mis-communication between you and your boss. I do not think your boss is stupid, but I do think he's talking on a different level as you do. You're using arduino which covers up a lot of hardware-interfacing, especially with steppers.
I suggest you check out this video: https://www.youtube.com/watch?v=bngx2dKl5jU
(I haven't watched it, but It will help you get more into the ideas of your boss)

Now you understand your boss's view, you can try to show him your view. When talking about steppers/arduino and how you can put in negative steps, he might think you're talking trash, as steppers require different pairs of coils to be active depending on the direction. (which is all handled by arduino)
The best way is to provide him a visual guidance, so that he can see the relation with his (hardware-view) on the issue and your software/arduino solution.

You could make something like the image below.
I'm not sure if this is what you're trying to tell him.
I guess you should mention/add that the software on the arduino takes integer values, with negative values being clockwise or such. **And that the arduino will convert this to the right coil pairs or direction and step.**

P.S:with *direct driving*, I think he meant toggling the right pins at the right moments so that the stepper will rotate, basically what the stepper library does for you. Maybe he wants you to implement something like the stepper library (is it an internship? so that you can learn?) I suggest you check some tutorials on how stepper motors work, and how you can drive them 'directly' withouth the use of libraries.

![Example][1]

  [1]: https://i.stack.imgur.com/8RlXt.png


message:
How to copy files from local computer to Yun with scp?

I need to transfer files from my local machine to my Arduino Yun.

I have tried:

    scp /Users/SSCirrus/Documents/index.html root@arduino.local:/root
    scp ~/Users/SSCirrus/Documents/index.html root@arduino.local:/root
    # No such file or directory (referring to my desktop)

I have confirmed that the filepath is accurate. What's wrong here?

body:
Try `~/Documents/index.html`

The `~` represents the current user's home directory, so `~/Documents` is the Documents folder for the current user.  It means you don't have to make sure you have spelled the user's home directory exactly right.

Other options are:

* `$HOME/Documents/index.html`
* `Documents/index.html` (if you are in your home directory)
* `cd ~/Documents` then just use `index.html`

... the list goes on ...


message:
Running multiple tasks at once

For a school project we're working on a wearable device to track people's movement and heart rate. We use an Arduino Pro Mini with a heartbeat sensor and an accelerometer. The wearable device uses Bluetooth to send data, but only once or twice a day to save battery.

The problem we currently face is having the Arduino keep track of the accelerometer data while also reading the heartbeat sensor on a select interval. See the pseudo-code underneath. In what way (preferably without implementing too many libraries) could we merge these two loops so the accelerometer is read non-stop while keeping an interval (of about 30 minutes) between the heart beat readings? Any input would be greatly appreciated and if needed I can provide additional information.

    void loop() {
    // Heartbeat sensor loop
      while (array is not full) {
        delay(30 minutes);
        heartbeatArray[index++] = readHeartbeat();
      }
      sendData_Bluetooth(heartbeatArray);
      emptyArray();
    // End of heartbeat sensor loop

    // Accelerometer loop
      while (true)
        if (readAccelerometerData > limit)
          sendAlert();
    // End of accelerometer loop
    }

body:
millis() is your great friend here.

millis() is function that returns the value of a 32 bit counter that is incremented once per millisecond. By adding the current value returned by millis() to a value representing the number of milliseconds that you want to 'delay' for you get a value that can be compared with the ongoing value returned by millis() to see if the time period has elapsed.

You can have as many variables as you wish which hold future timeout values for millis(0 - you perform the related action when millis() returns >= the saved value and reinitialise the value to some new future time.

Variables used to hold values from millis() **MUST** be type unsigned long.
The millis() timer rolls over every 49.7 days.
( = 2^32/1000 ms/s / 3600 s/hr / 24 h/day)

 - If your system may run for longer than that without being reset or powered down then handling millis()'s timer rollover must be known about.

   It's MUCH easier than many people realise but best not dealt with here EXCEPT to know that if you add a constant to millis() and the value exceeds 2^32 and is truncated the comparisons with and subtractions wrt millis() still work correctly if the variable is type unsigned long. ("Why" is for elsewhere)

micros() is like unto millis() but returns the time since reset in microseconds. Depending on the processor used micros() may have a granularity of 4 uS rather than one uS. ie it steps by 4 counts every 4 uS rather than 1 count per uS.
micros() rolls over every 1.19 hours
( = 2^32 / 10^6/3600s/h)

________________

// **Example - not tested:**

    unsigned long DoitNow;

    void setup(){
      DoitNow = millis() + 1800000; // Add half an hour of milliseconds
     }
    void loop(){
       if(millis() > DoitNow)
       { Do heartbeat stuff;
          DoitNow = millis() + 1800000; // Add another half hour of ms
       }
     Do accelerometer stuff;
    }


body:
What you want to do is rather easy task, you just need to forget about `delay()` function. When writing some more complex programs using it is generally a bad idea, as it blocks code execution, so you won't get any sensor readings, communication, anything. Instead try something like this:

    unsigned long delay1 = 100;
    unsigned long delay2 = 1800000; //30 minutes in miliseconds
    unsigned long t1, t2;

    void setup() {
      t1 = t2 = millis();
    }

    void loop() {
      if(millis() - t1 > delay1) { //this will be executed every delay1 ms
        // do one part of code
        t1 = millis();
      }

      if(millis() - t2 > delay2) { //this will be executed every delay2 ms
        // do another part of code
        t2 = millis();
      }

      // here insert the code that should be executed as frequently as possible
      // (every loop passage)
    }

There is also a nice Arduino library called [TaskScheduler][1], that basically does the same thing: periodically executes different functions with different time intervals.

  [1]: http://playground.arduino.cc/Code/TaskScheduler


body:
To keep the 10Hz accelerometer sample rate consistent, you'll need an 10Hz interrupt routine to do the sampling, and probably queue them somewhere, as they will accumulate while you're off measuring the heart rate.

Your main loop can collect any accelerometer samples out of the queue periodically, and at appropriate intervals, read the heart beat. This organization will keep the accelerometer sample rate stead whether your main loop has anything else to do or not.

Make the queue more than long enough to hold all the samples that could collect during a heartbeat measurement, which you should probably make one at a time, even though you might do it in rapid succession, so the main loop gets to drain the accelerometer queue as often as possible.

Otherwise you'll need a queue as large as (10 Hz * 10 sec * maxPossibleConsecutiveHeartBeatMeasurements * factorOfSafety * sizeof(oneSample) bytes; and you don't have a whole lot of memory to play with in an Atmega 328.

Where will you be storing the measurements between Bluetooth connects? If it's an SD card, you'll need some space for its write-buffer, and the main loop will have to manage the card writing.


body:
See https://electronics.stackexchange.com/a/67091/10371 (Since this is another stack exchange site, I won't copy the info)

The short answer is to use timers that trigger interrupts.  Examples are shown in the link.


message:
How to read code from Arduino Uno to Arduino IDE?

we can upload a code into Arduino UNO from our computers, but how about reading code? Can we read and get C codes from compiled codes from Arduino hardwares? My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?

body: You wont be able to get the code in readable C. It would be in Machine code.


body:
> Can we read and get C codes from compiled codes from Arduino hardwares?

While it is possible, even trivial, to disassemble machine code, it is very difficult to convert the assembly code into a higher-level language, and essentially impossible to turn it back into an exact copy of the source code it came from. There simply isn't enough information in the machine code to do so.

> My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?

The debug port will work in tandem with appropriate software that will already have access to the source code, so this is not a method for conversion either.


message:
Powering a 6-12V motor using a lead acid 6V battery with 6Amps of current?

Hi I'm using a adafruit motor shield v2 and I need to power a DC motor 6-12V but I'm not sure if my battery will be okay for the shield. Will it burn the shield? I'm going to be using 6V so it should draw less current?

body:
If you take the "full load" to be the "stall current", then you can work out the resistance of the winding.

R=V/I = 12/14 = 0.857Ω

From that you can then work out the stall current at 6V:

I=VR = 6×0.857 = 5.143A

That, being the *stall current*, is the *maximum* the motor will draw - the current drawn when it is trying to move an impossible amount of load and the rotor cannot move.  At that current you will melt the motor drivers (or they will go into thermal shutdown).

Of course, with a geared motor, that becomes a (comparatively) massive load and would be quite hard to achieve.  You have a 50:1 gear ratio, so the stall load is effectively 50x greater.

So there is going to be a limit to the load that you can drive with the motor before it becomes a problem for the driver.  There are ways of calculating it from the given torque, gear ratio, load/noload current ratings, etc, but I don't have all that at my fingertips right now.

So you can either "play it safe" and invest in a driver that can cope with the stall current, or experiment and measure what current is drawn by the motor with different loads and see if it stays below the 1.2A limit of the shield.


message:
How does changing arduino power supply from USB to Adapter change the circuit?

I have a circuit running with capacitive Sensors, that also has an LED strip. everything works fine when using USB power from a laptop (connected to the mains) and 12v 2A adapter powering 1m LED strip.

When the power supply is split and the arduino is also powered from this supply ( using adapter port ) the capacitive sensor begins to give junk values.

What changes in a circuit that would create such a porblem? Could it be a grounding issue? How else to ground this arduino to behave as it would with a usb connection?

body:
I have run into problems like this before, often it can actually be that the voltage is not steady due to the LEDs sourcing current from it.

You may be able to solve the problem by adding a capacitor inline with the power input (from the +12v to GND). I would probably start with a value of around 10 μF and increase it if the interference continues.

Capacitive sensors and very sensitive to voltage fluctuations, you may even want to put a second capacitor across the VCC and Gnd of the sensor.


body:
Some of the capacitive sensors need a seperate regulated power supply.You can look into the data sheet of the capacitive sensor.Maybe you can try with the same.
I just read the datasheet of At42qt2120 cap sensor.


message:
How do I interface two Arduino boards so they act as one with double the code space?

Can I connect two ARDUINO UNO circuit boards in serial to increase room for more code and more functionality. For instance I wish to connect six sensors to a board. I need code for all six sensors and there is not enough space on one board. If I connect two circuit boards in serial will that provide the space and functionality to run the code for all six sensors.
If not how is this accomplished? I am a beginner with ARDUINO and I have been assigned a big task to make the ARDUINO UNO circuit boards provide six different functions using sensors such as temperature, pressure, humidity, voltage, current and possibly other functions. I am new at this.

body: There is no simple way to combine multiple boards into a unified system. What you will need to do is delegate certain tasks to each board and then have them communicate via SPI, I2C, or UART between a master board and each slave board in the system. The master system will then present the interface of the system as a whole via serial, wifi, console, etc.


body:
What you described is not a big task. I suspect you are new to both the Arduino and computers in general, and so it seems big to you. Hang in there, it is a lot easier than you think.

In many cases, a sensor requires 1 electrical pin (plus ground, which is shared by all).  So even an Arduino UNO can read a dozen or more sensors.  In many cases the instructions to read the sensor is as simple as 'read(x)'  and that takes 2 bytes, so if you got really lucky, the UNO's 32k of memory could read 16k sensors (a 'k' being a thousand if you didnt know).

Reality is it is not quite that simple, but it is not far from it.  You probably want to find a library that matches your sensor, and the only hard part is figuring out how to combine many libraries, which indeed do interfere with each other on occasion.

Step 1, learn the basics.  Get an Arduino experimenters kit or equivalent, play with the examples until you understand them. It will include some of the sensors you may use later.

Step 2, identify which other sensors you will need, find Arduino compatible versions of those.  You will know if it is Arduino compatible if it has an accompanying library, get that also.

step 3, make sure you can make each sensor work by itself first.

step 4, start combining sensors and resolving errors that will show up.

Forget the idea of combining boards, it is an advanced topic and you are no where near ready to try that yet.


body: If you're doing something that exceeds the resources of an UNO, then one simple next step would be to try a MEGA.  It is similar enough to the UNO that porting should be trivial, but has more RAM, more flash, and more I/O ports than two UNO units combined.


message:
Trouble making TMP102 work with any ADD0 other than ground

I'm trying to get an Arduino Uno to run four sensors (all I2C). The first two are TMP102 temperature sensors. The address is controlled by tying the ADD0 pin to GND, VCC, SDA, or SCL (four possible addresses, without multiplexing). I get it to receive data just fine through the GND setting.

I wrote some code to collect from two, but before I was even talking to the second one, plugging it in causes the data stream from the GND one to stop. Unplugging it from the breadboard makes it work again. Either sensor in either location on the breadboard will work fine, as long as it's addressed as ground. Neither sensor will, even by itself, work with any other address. I tried some other sketches from the net (one attached below that should read from any of four different sensors), but all have the same issue.

    #include <Wire.h>
    byte res;
    byte msb;
    byte lsb;
    int val;

    void setup()
    {
      Serial.begin(9600);
      Wire.begin();
    }

    void loop()
    {
      res = Wire.requestFrom(72,2);
      if (res == 2) {
        msb = Wire.read(); /* Whole degrees */
        lsb = Wire.read(); /* Fractional degrees */
        val = ((msb) << 4);   /* MSB */
        val |= (lsb >> 4);    /* LSB */
        Serial.print( "72:");
        Serial.println(val*0.0625);
        delay(1000);
      }
      res = Wire.requestFrom(73,2);
      if (res == 2) {
        msb = Wire.read(); /* Whole degrees */
        lsb = Wire.read(); /* Fractional degrees */
        val = ((msb) << 4);   /* MSB */
        val |= (lsb >> 4);    /* LSB */
        Serial.print( "73:");
        Serial.println(val*0.0625);
        delay(1000);
      }
      res = Wire.requestFrom(74,2);
      if (res == 2) {
        msb = Wire.read(); /* Whole degrees */
        lsb = Wire.read(); /* Fractional degrees */
        val = ((msb) << 4);   /* MSB */
        val |= (lsb >> 4);    /* LSB */
        Serial.print( "74:");
        Serial.println(val*0.0625);
        delay(1000);
      }
      res = Wire.requestFrom(75,2);
      if (res == 2) {
        msb = Wire.read(); /* Whole degrees */
        lsb = Wire.read(); /* Fractional degrees */
        val = ((msb) << 4);   /* MSB */
        val |= (lsb >> 4);    /* LSB */
        Serial.print( "75:");
        Serial.println(val*0.0625);
        delay(1000);
      }
    }

Breadboard:
(image link: the forum kept crashing when I tried to upload the image directly)
https://www.sugarsync.com/pf/D333436_95042359_6938296

Thanks!

body: You see that little solder jumper block on the breakout board labelled "ADD0"?  You need to remove the solder from that.  It's currently connected in a pre-defined position and you trying to use the ADD0 pin is conflicting with that.


message:
Conver char value to variable?

I want to pass the preprocessor values(AT commands) to the Serial.println function. Im trying TCP connection using arduino-SIM900A. I've declared all AT commands to each preprocessor variables like below

    #define A "AT\r"
    #define B "AT+CPIN?\"
    ...
I've assigned all preprocessor variables in char array and pass it into Serial.print using for loop.

    char varAT[12]={'A','B'....};
    for(int i=0;i<=12;i++)
    {
    Serial.print(varAT[i]);
    }

Its not printing AT, instead it print preprocessor variable name A. I searched the google how to convert char value to variable, in C there is a function called "eval". Using eval we can acheive, but it wont work in arduino lang. How to solve this?

Thanks.

body:
Ok, first, `char varAT[12]` indicates an array of 12 characters.

Second, quotes indicate literals - 'A' means, literally, the character 'A'. Variables and constants are without quotes (same way you use  `i`).

I think you mean:

    char *varAT[12]={A,B....};

Also, your constant `B` is invalid - I think you meant for it to end in `\r"`, not `\"`.


message:
Measuring Time Between Inputs

I'm trying to measure the amount of time that has passed between every time a reed switch mounted on a wheel is activated to calculate the speed of a bike in miles per hour and display it on two 7 segment LEDs. This is what I have so far (without 7 seg code, as that works):

    const int reed = A3;
    float circumference;
    float pi = 3.141592653589
    unsigned long time0 = 0;
    unsigned long time1;
    unsigned long revolutionTime;

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

    void loop() {
      circumference = (pi * 26); //26 = the diameter of the wheel
      int reedState = digitalRead(reed);
      if (reedState == HIGH) {
       time1 = millis();
       revolutionTime = (time1 - time0);
       time0 = time1;
       int mph = ((circumference / revolutionTime) * (3600000 / 63360)); //this is the conversion from inches/millisecond to miles/hour.
        Serial.println(mph);
        //And I'd print the result on the 7 segment displays here
      }
    }

This code results in around 25 printed entries in the serial monitor from a single activation of the reed switch, all of which consist of randomly alternating values of either 0 or 4571.

Following each step of the code, I assume that the program would generate a garbage result for the first entry (because the time before the reed is activated for the first time could vary greatly), but that following entries would be the correct mph displayed on the 7 segment displays until the reed switch is activated again and a new mph is calculated.

So how would I go about modifying the code to get useful data?

body:
Imagine your wheel rotating very slow ... imagine time was slowed down.  Imagine the magnet comes to the reed sensor and closes the switch.  You will now take a measurement.  The Ardunio code loop will end and immediately restart ... because time has been slowed (in our story), the wheel will have barely moved and AGAIN you will take another measurement because the reed switch is STILL closed because the magnet hasn't moved far enough.

I believe you need to change your logic such that after you detect the reed switch closing, you then need to detect that the reed switch is OPEN again ... before once more looking for the reed switch to close. Something like:

    if (reedState == HIGH) {
       // do something
       while(digitalRead(reed) == HIGH) {
          // do nothing
       }
    }


body:
Your test `if (reedState == HIGH)` does not tell you when the reed
switch is _activated_, it tells you when it's _active_, which is not the
same. You should instead look at when the switch transitions from `LOW`
to `HIGH`, which means you also have to remember the last state.

For example (untested):

<!-- language: lang-c++ -->

    void loop() {
        static int lastReedState;
        static unsigned long lastTransition;
        int reedState = digitalRead(reed);

        // On a rising transition of the reed switch:
        if (reedState == HIGH && lastReedState == LOW) {

            // Compute time since last valid transition.
            unsigned long now = millis();
            unsigned long revolutionTime = now - lastTransition;

            // Debounce: this transition is valid only if enough time has
            // elapsed since the last valid one.
            if (revolutionTime > 20) {

                // Compute and report speed.
                int speed = circumference / revolutionTime;
                Serial.println(speed);

                // Remember this transition.
                lastTransition = now;
            }
        }

        // Remember last state.
        lastReedState = reedState;
    }

This assumes `circumference` has already been calculated and has the
appropriate unit (miles⋅ms/h if you want the speed reported in mph).
Actually it could be a compile-time `int` constant (4641), which would
avoid having floating point calculations at run time.


body:
Currently your code is not working, because Arduino is fast enough to check the closed switch state many times before it opens again, so before calculating a new speed value, you need to see LOW on the input.

Still, there are at least 2 better ways to do what you want.

**[pulseIn()][1]** - a function intended just for what you are trying to do: measuring lenght of a pulses. If your switch is active HIGH, you need to measure length of a LOW pulse:

    unsigned long duration;
    duration = pulseIn(reed, LOW);
    // calculate speed basing on duration (in microseconds)
Keep in mind, that `pulseIn()` is a blocking function, so no code will be executed, until it receives the pulse. You can counter it bu specifying a timeout, after which, the program will continue.

**External [interrupts][2]** are an another approach. Interrupt handling routines are executed when a specified event occurs, no matter if the microcontroller is busy doing something else or not. They would guarantee, that you will not miss any pulse even if they would have frequency in order of kHz.

    volatile unsigned long lastTime = 0;

    void setup() {
     attachInterrupt(0, readTime, RISING);
    }

    void readTime() {
     unsigned long t = millis();
        // calculate speed basing on t - lastTime
        lastTime = t;
    }

Interrupt handling routine should be as short as possible. Avoid using delays in it, doing Serial.print and other communications. Also, millis() and micros() will not increment during execution of interrupt handler.

**Debouncing** - even with above two methods, things may still not work properly. The most probable cause would be switch "bouncing". You can counter it by

 - software debouncing  - delaying after `pulseIn()` or ignoring interrupts for some period of time after first interrupt is detected
 - adding a small (10-100nF) capacitor at the input, that will act as a low-pass filter, cutting out short pulses
 - using not a reed switch, but a hall sensor with hysteresis

  [1]: http://www.arduino.cc/en/Reference/PulseIn
  [2]: http://www.arduino.cc/en/Reference/attachInterrupt


body:
A: Use interrupts to detect the state change on the reed switch

B: Use a hall sensor instead of the reed, they do not suffer switch bounce

C: Use a debounce circuit, a 74HC14 with a small capacitor connected between ground and the input

Put a 4K7 resistor as pullup between VCC & the input

Put a 100 ohm resistor on the wire coming from the Reed, which is connected to GND on the other side

The 100 ohm prevents discharge damage to the contacts from the capacitor and suppresses RF interference

Ground all unused inputs and feed the output of the active channel to the Arduino
The 74HC series are 3v3 & 5V compatible, the 74HCT series is only 5V compatible but are more suited as level shifters from 3v3 signals to 5V output

D: use a software debounce routine


message:
Are arduino passwords safe?

Is an arduino password controlled lock safe or can the password be seen if they plug it in to a computer?

body:
There are no passwords inherent to Arduino. You can implement them any way you want, resulting in any safety level from zero safely to nearly uncrackable.

**Not so good**: store the passwords straight in EEPROM. No protection of your data means that there's always a way to read them.

**Quite safe**: hash the password before storing it, for instance through SHA-512. Even if you can read the list of hashed passwords, it's pretty hard (read: nearly impossible) to reverse the algorithm to get the password back. For that reason SHA functions are called one-way functions. When you enter a password you run it through the SHA algorithm and check the hash against the list of hashes in EEPROM.


message:
Intializing Serial crashes UNO

I have a somewhat large sketch that uses the `Adafruit_ssd1306`(I2C) library for a 128X64 LCD. The sketch is a designed to be an alarm clock. When I upload the sketch with out initializing serial, it works as designed. However if I do intialize serial:

    Serial.begin(9600);

the program fails to run on my UNO. After many hours of troubleshooting I noticed I have several large char arrays that may be the culprit.

    const char *menusDisplay[] = {"1. Alarm-is Off", "2. Month", "3. Hour", "4. Minute", "5. Exit", "6. Alarm Set", NULL};
    const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec", NULL};
    const int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

The months array as 12 elements. If I shorted it down to 2 elements and upload the programs with serial initialized, the program runs. At first I thought is was a memory leak in perhaps the `Adafruit_ssd1306`. But I also have another LCD library `Adafruit_ssd1306syp` that the issue occurred too. So that ruled out those libraries.

When I compile the sketch without Serial:

    Sketch uses 16,846 bytes (52%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 737 bytes (35%) of dynamic memory, leaving 1,311 bytes for local variables. Maximum is 2,048 bytes.

With Serial:

    Sketch uses 17,862 bytes (55%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 910 bytes (44%) of dynamic memory, leaving 1,138 bytes for local variables. Maximum is 2,048 bytes.

Any ideas of what may be going on? I would load the sketch but its very large. If needed, I can try to cut it down and reproduce the issue.

body:
Since no other code is posted, I am going to guess that you're performing a loop on months[], which has 13 elements (last one is NULL).

You are likely also trying to walk the days[] array (or some other array), which only has 12 elements.

Since days[] or the other (not pasted) array doesn't have 13 elements, you're probably overriding a critical bootloader memory which causes a crash.


body:
@EdgarBonet pointed out in a comment, I need to check my dynamic ram, which could be used by the Heap and Stack. The class can be found [here][1] to measure ram usage. Since links can die, here is the code:

Here is the header:

    /* MemoryFree.h */

    // MemoryFree library based on code posted here:
    // http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1213583720/15
    // Extended by Matthew Murdoch to include walking of the free list.

    #ifndef MEMORY_FREE_H
    #define MEMORY_FREE_H

    #ifdef __cplusplus
    extern "C" {
    #endif

    int freeMemory();

    #ifdef  __cplusplus
    }
    #endif

    #endif

Here is the .cpp

    /* MemoryFree.cpp */

    #if (ARDUINO >= 100)
    #include <Arduino.h>
    #else
    #include <WProgram.h>
    #endif

    extern unsigned int __heap_start;
    extern void *__brkval;

    /*
     * The free list structure as maintained by the
     * avr-libc memory allocation routines.
     */
    struct __freelist {
      size_t sz;
      struct __freelist *nx;
    };

    /* The head of the free list structure */
    extern struct __freelist *__flp;

    #include "MemoryFree.h"

    /* Calculates the size of the free list */
    int freeListSize() {
      struct __freelist* current;
      int total = 0;
      for (current = __flp; current; current = current->nx) {
        total += 2; /* Add two bytes for the memory block's header  */
        total += (int) current->sz;
      }
      return total;
    }

    int freeMemory() {
      int free_memory;
      if ((int)__brkval == 0) {
        free_memory = ((int)&free_memory) - ((int)&__heap_start);
      } else {
        free_memory = ((int)&free_memory) - ((int)__brkval);
        free_memory += freeListSize();
      }
      return free_memory;
    }

From this I was able to see how much ram was used. Of the avialable 2k, I had only 100k left. So now I know why my program is crashing, I need a solution. The solution was to store the static content in program memory (PROGMEM):

    const char* const months[] PROGMEM =
     {
          "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
       };

    const uint8_t days_of_month[] PROGMEM =
     {
      31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
     };

  [1]: http://playground.arduino.cc/Code/AvailableMemory


message:
How can I handle the millis() rollover?

I need to read a sensor every five minutes, but since my sketch also has
other tasks to do, I cannot just `delay()` between the readings. There
is the [Blink without
delay](http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay) tutorial
suggesting I code along these lines:

<!-- language: lang-c++ -->

    void loop()
    {
        unsigned long currentMillis = millis();

        // Read the sensor when needed.
        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            readSensor();
        }

        // Do other stuff...
    }

The problem is that `millis()` is going to roll over back to zero after
roughly 49.7 days. Since my sketch is intended to run for longer
than that, I need to make sure the rollover does not make my sketch
fail. I can easily detect the rollover condition
(`currentMillis < previousMillis`), but I am not sure what to do then.

Thus my question: what would be the proper/simplest way to handle the
`millis()` rollover?

body:
<!-- language-all: lang-c -->

Short answer: do not try to “handle” the millis rollover, write
rollover-safe code instead. Your example code from the tutorial is fine.
If you try to detect the rollover in order to implement corrective
measures, chances are you are doing something wrong. Most Arduino
programs only have to manage events that span relatively short
durations, like debouncing a button for 50 ms, or turning a heater
on for 12 hours... Then, and even if the program is meant to run
for years at a time, the millis rollover should not be a concern.

The correct way to manage (or rather, avoid having to manage) the
rollover problem is to think of the `unsigned long` number returned by
`millis()` in terms of [modular
arithmetics](http://en.wikipedia.org/wiki/Modular_arithmetic). For the
mathematically inclined, some familiarity with this concept is very
useful when programming. You can see the math in action in Nick Gammon's
article [millis() overflow ... a bad
thing?](https://www.gammon.com.au/millis). For the problem at hand,
what's important to know is that in modular arithmetics the numbers
“wrap around” when reaching a certain value – the modulus – so that
1 − modulus is not a negative number but 1 (think of a
12 hour clock where the modulus is 12: here 1 − 12 = 1).

For those who do not want to
go through the computational details, I offer here an alternative
(hopefully simpler) way of thinking about it. It is based on the simple
distinction between _instants_ and _durations_. As long as your tests
only involve comparing durations, you should be fine.

**Note on micros()**: Everything said here about `millis()` applies
equally to `micros()`, except for the fact that `micros()` rolls over
every 71.6 minutes, and the `setMillis()` function provided below
does not affect `micros()`.

## Instants, timestamps and durations

When dealing with time, we have to make the distinction between at least
two different concepts: _instants_ and _durations_. An instant is a
point on the time axis. A duration is the length of a time interval,
i.e. the distance in time between the instants that define the start and
the end of the interval. The distinction between these concepts is not
always very sharp in everyday language. For example, if I say “_I will
be back in five minutes_”, then “_five minutes_” is the estimated
_duration_ of my absence, whereas “_in five minutes_” is the _instant_
of my predicted coming back. Keeping the distinction in mind is
important, because it is the simplest way to entirely avoid the rollover
problem.

The return value of `millis()` could be interpreted as a duration: the
time elapsed from the start of the program until now. This
interpretation, however, breaks down as soon as millis overflows. It is
generally far more useful to think of `millis()` as returning a
_timestamp_, i.e. a “label” identifying a particular instant. It could
be argued that this interpretation suffers from these labels being
ambiguous, as they are reused every 49.7 days. This is, however,
seldom a problem: in most embedded applications, anything that happened
49.7 days ago is ancient history we do not care about. Thus,
recycling the old labels should not be an issue.

## Do not compare timestamps

Trying to find out which among two timestamps is greater than the other
does not make sense. Example:

    unsigned long t1 = millis();
    delay(3000);
    unsigned long t2 = millis();
    if (t2 > t1) { ... }

Naively, one would expect the condition of the `if ()` to be always
true. But it will actually be false if millis overflows during
`delay(3000)`. Thinking of t1 and t2 as recyclable labels is the
simplest way to avoid the error: the label t1 has clearly been assigned
to an instant prior to t2, but in 49.7 days it will be reassigned
to a future instant. Thus, t1 happens both _before_ and _after_ t2. This
should make clear that the expression `t2 > t1` makes no sense.

But, if these are mere labels, the obvious question is: how can we do
any useful time calculations with them? The answer is: by restricting
ourselves to the only two calculations that make sense for timestamps:

1. `later_timestamp - earlier_timestamp` yields a duration, namely the
   amount of time elapsed between the earlier instant and the later
   instant. This is the most useful arithmetic operation involving
   timestamps.
2. `timestamp ± duration` yields a timestamp which is some time after
   (if using +) or before (if −) the initial timestamp. Not as useful as
   it sounds, since the resulting timestamp can be used in only two
   kinds of calculations...

Thanks to modular arithmetics, both of these are guaranteed to work fine
across the millis rollover, at least as long as the delays involved are
shorter than 49.7 days.

## Comparing durations is fine

A duration is just the amount of milliseconds elapsed during some time
interval. As long as we do not need to handle durations longer than
49.7 days, any operation that physically makes sense should also
make sense computationally. We can, for example, multiply a duration by
a frequency to get a number of periods. Or we can compare two durations
to know which one is longer. For example, here are two alternative
implementations of `delay()`. First, the buggy one:

    void myDelay(unsigned long ms) {          // ms: duration
        unsigned long start = millis();       // start: timestamp
        unsigned long finished = start + ms;  // finished: timestamp
        for (;;) {
            unsigned long now = millis();     // now: timestamp
            if (now >= finished)              // comparing timestamps: BUG!
                return;
        }
    }

And here is the correct one:

    void myDelay(unsigned long ms) {              // ms: duration
        unsigned long start = millis();           // start: timestamp
        for (;;) {
            unsigned long now = millis();         // now: timestamp
            unsigned long elapsed = now - start;  // elapsed: duration
            if (elapsed >= ms)                    // comparing durations: OK
                return;
        }
    }

Most C programmers would write the above loops in a terser form, like

    while (millis() < start + ms) ;  // BUGGY version

and

    while (millis() - start < ms) ;  // CORRECT version

Although they look deceptively similar, the timestamp/duration
distinction should make clear which one is buggy and which one is
correct.

## What if I really need to compare timestamps?

Better try to avoid the situation. If it is unavoidable, there is still
hope if it is known that the respective instants are close enough:
closer than 24.85 days. Yes, our maximum manageable delay of
49.7 days just got cut in half.

The obvious solution is to convert our timestamp comparison problem into
a duration comparison problem. Say we need to know whether instant t1 is
before or after t2. We choose some reference instant in their common
past, and compare the durations from this reference until both t1 and
t2. The reference instant is obtained by subtracting a long enough
duration from either t1 or t2:

    unsigned long reference_instant = t2 - LONG_ENOUGH_DURATION;
    unsigned long from_reference_until_t1 = t1 - reference_instant;
    unsigned long from_reference_until_t2 = t2 - reference_instant;
    if (from_reference_until_t1 < from_reference_until_t2)
        // t1 is before t2

This can be simplified as:

    if (t1 - t2 + LONG_ENOUGH_DURATION < LONG_ENOUGH_DURATION)
        // t1 is before t2

It is tempting to simplify further into `if (t1 - t2 < 0)`. Obviously,
this does not work, because `t1 - t2`, being computed as an unsigned
number, cannot be negative. This, however, although not portable, does
work:

    if ((signed long)(t1 - t2) < 0)  // works with gcc
        // t1 is before t2

The keyword `signed` above is redundant (a plain `long` is always
signed), but it helps make the intent clear. Converting to a signed long
is equivalent to setting `LONG_ENOUGH_DURATION` equal to
24.85 days. The trick is not portable because, according to the C
standard, the result is _implementation defined_. But since the gcc
compiler [promises to do the right
thing](https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html),
it works reliably on Arduino. If we wish to avoid implementation defined
behavior, the above signed comparison is mathematically equivalent to
this:

    #include <limits.h>

    if (t1 - t2 > LONG_MAX)  // too big to be believed
        // t1 is before t2

with the only problem that the comparison looks backwards. It is also
equivalent, as long as longs are 32-bits, to this single-bit test:

    if ((t1 - t2) & 0x80000000)  // test the "sign" bit
        // t1 is before t2

The last three tests are actually compiled by gcc into the exact same
machine code.

## How do I test my sketch against the millis rollover

If you follow the precepts above, you should be all good. If you
nevertheless want to test, add this function to your sketch:

    #include <util/atomic.h>

    void setMillis(unsigned long ms)
    {
        extern unsigned long timer0_millis;
        ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
            timer0_millis = ms;
        }
    }

and you can now time-travel your program by calling
`setMillis(destination)`. If you want it to go through the millis
overflow over and over again, like Phil Connors reliving Groundhog Day,
you can put this inside `loop()`:

    // 6-second time loop starting at rollover - 3 seconds
    if (millis() - (-3000) >= 6000)
        setMillis(-3000);

The negative timestamp above (-3000) is implicitly converted by the
compiler to an unsigned long corresponding to 3000 milliseconds before
the rollover (it is converted to 4294964296).

## What if I really need to track very long durations?

If you need to turn a relay on and turn it off three months later, then
you really need to track the millis overflows. There are many ways to do
so. The most straightforward solution may be to simply extend `millis()`
to 64 bits:

    uint64_t millis64() {
        static uint32_t low32, high32;
        uint32_t new_low32 = millis();
        if (new_low32 < low32) high32++;
        low32 = new_low32;
        return (uint64_t) high32 << 32 | low32;
    }

This is essentially counting the rollover events, and using this count
as the 32 most significant bits of a 64 bit millisecond count.
For this counting to work properly, the function needs to be called at
least once every 49.7 days. However, if it is only called once per 49.7 days, for some cases it is possible that the check `(new_low32 < low32)` fails and the code misses a count of `high32`. Using millis() to decide when to make the only call to this code in a single "wrap" of millis (a specific 49.7 day window) could be very hazardous, depending on how the time frames line up. For safety, if using millis() to determine when to make the only calls to millis64(), there should be at least two calls in every 49.7 day window.

Keep in mind, though, that 64 bit arithmetic is expensive on the
Arduino. It may be worth to reduce the time resolution in order to stay
at 32 bits.


body:
**TL;DR** Short version:

An `unsigned long` is 0 to 4,294,967,295 (2^32 - 1).

So lets say `previousMillis` is 4,294,967,290 (5 ms before rollover), and `currentMillis` is 10 (10ms after rollover). Then `currentMillis - previousMillis` is actual 16 (not -4,294,967,280) since the result will be calculated as an **unsigned** long (which can't be negative, so itself will roll around). You can check this simply by:

`Serial.println( ( unsigned long ) ( 10 - 4294967290 ) ); // 16`

So the above code will work perfectly fine. The trick is to always calculate the time difference, and not compare the two time values.


body:
Wrap the `millis()` in a class!

Logic:

 1. Use id's instead of `millis()` directly.
 2. Compare reversals using id's. This is clean and rollover independent.
 3. For specific applications, to calculate exact difference between two id's, keep track of reversals and stamps. Calculate the difference.

Keeping track of reversals:

 1. Update a local stamp periodically faster than `millis()`. This will help you find out if `millis()` has overflown.
 2. The period of the timer determines accuracy

<!-- language: lang-c++ -->

    class Timer {

    public:
        static long last_stamp;
        static long *stamps;
        static int *reversals;
        static int count;
        static int reversal_count;

        static void setup_timer() {
            // Setup Timer2 overflow to fire every 8ms (125Hz)
            //   period [sec] = (1 / f_clock [sec]) * prescale * (255-count)
            //                  (1/16000000)  * 1024 * (255-130) = .008 sec

            TCCR2B = 0x00;        // Disable Timer2 while we set it up

            TCNT2  = 130;         // Reset Timer Count  (255-130) = execute ev 125-th T/C clock
            TIFR2  = 0x00;        // Timer2 INT Flag Reg: Clear Timer Overflow Flag
            TIMSK2 = 0x01;        // Timer2 INT Reg: Timer2 Overflow Interrupt Enable
            TCCR2A = 0x00;        // Timer2 Control Reg A: Wave Gen Mode normal
            TCCR2B = 0x07;        // Timer2 Control Reg B: Timer Prescaler set to 1024

            count = 0;
            stamps = new long[50];
            reversals = new int [10];
            reversal_count =0;
        }

        static long get_stamp () {
            stamps[count++] = millis();
            return count-1;
        }

        static bool compare_stamps_by_id(int s1, int s2) {
            return s1 > s2;
        }

        static long long get_stamp_difference(int s1, int s2) {
            int no_of_reversals = 0;
            for(int j=0; j < reversal_count; j++)
            if(reversals[j] < s2 && reversals[j] > s1)
                no_of_reversals++;
            return stamps[s2]-stamps[s1] + 49.7 * 86400 * 1000;
        }

    };

    long Timer::last_stamp;
    long *Timer::stamps;
    int *Timer::reversals;
    int Timer::count;
    int Timer::reversal_count;

    ISR(TIMER2_OVF_vect) {

        long stamp = millis();
        if(stamp < Timer::last_stamp) // reversal
            Timer::reversals[Timer::reversal_count++] = Timer::count;
        else
            ; // no reversal
        Timer::last_stamp = stamp;
        TCNT2 = 130;     // reset timer ct to 130 out of 255
        TIFR2 = 0x00;    // timer2 int flag reg: clear timer overflow flag
    };

    // Usage

    void setup () {
        Timer::setup_timer();

        long s1 = Timer::get_stamp();
        delay(3000);
        long s2 = Timer::get_stamp();

        Timer::compare_stamps_by_id(s1, s2); // true

        Timer::get_stamp_difference(s1, s2); // return true difference, taking into account reversals
    }

[Timer credits][1].

  [1]: https://electronics.stackexchange.com/questions/26363/how-do-i-create-a-timer-interrupt-with-arduino


body:
I loved this question, and the great answers it generated. First a quick comment on a previous answer (I know, I know, but I don't have the rep to comment yet. :-).

Edgar Bonet's answer was amazing. I've been coding for 35 years, and I learned something new today. Thank you. That said, I believe the code for *"What if I really need to track very long durations?"* breaks unless you call millis64() at least once per rollover period. Really nitpicky, and unlikely to be an issue in a real-world implementation, but there you go.

Now, if you really did want timestamps covering any sane time range (64-bits of milliseconds is about half a billion years by my reckoning), it looks simple to extend the existing millis() implementation to 64 bits.

These changes to attinycore/wiring.c (I'm working with the ATTiny85) seem to work (I'm assuming the code for other AVRs is very similar). See the lines with the //BFB comments, and the new millis64() function. Clearly it's going to be both bigger (98 bytes of code, 4 bytes of data) and slower, and as Edgar pointed out, you almost certainly can accomplish your goals with just a better understanding of unsigned integer math, but it was an interesting exercise.

    volatile unsigned long long timer0_millis = 0;  // BFB: need 64-bit resolution

    #if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
    ISR(TIM0_OVF_vect)
    #else
    ISR(TIMER0_OVF_vect)
    #endif
    {
     // copy these to local variables so they can be stored in registers
     // (volatile variables must be read from memory on every access)
     unsigned long long m = timer0_millis;  // BFB: need 64-bit resolution
     unsigned char f = timer0_fract;

     m += MILLIS_INC;
     f += FRACT_INC;
     if (f >= FRACT_MAX) {
      f -= FRACT_MAX;
      m += 1;
     }

     timer0_fract = f;
     timer0_millis = m;
     timer0_overflow_count++;
    }

    // BFB: 64-bit version
    unsigned long long millis64()
    {
     unsigned long long m;
     uint8_t oldSREG = SREG;

     // disable interrupts while we read timer0_millis or we might get an
     // inconsistent value (e.g. in the middle of a write to timer0_millis)
     cli();
     m = timer0_millis;
     SREG = oldSREG;

     return m;
    }