text:
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?

Powering using 9V battery or same 12v 2a shared connection in the Vin port produces a different set of problems, where the sensor loses its range. How are the various methods of powering the board changing the behavior so much?

They should share the ground connection. Also, do you have any drawings? Of the working situation and where it goes wrong?

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.

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.


text:
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.

You don't.   Two Unos do not equal a Mega (or a cheaper ARM Cortex with a reasonable amount of resources).  With some care you can probably fit everything you just described in the Uno's ATmega328p, but the ground rules of the assignment really need to be called into question, as unless there is closet full of hardware that is already paid for it is likely they were written by someone ill-informed.

It would probably be easier to optimize your code so that it fits. Reading six sensors doesn't sound too complex for an Uno.

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.

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.

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.

source: Stack Exchange

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

sort: votes


text:
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!

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.

Well, that's not obvious :)
Would soldering the other pair of contacts together tie ADD0 to VCC?

Most likely, Yes.

I just used a jumper to set the second address, rather than soldering, but... it works! Thanks for the help!

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


text:
2 Arduino Unos Connected with 1-Wire and Receiver Pin getting Stuck High

I am trying to accomplish 1-wire communication between 2 Arduinos and so I wanted to start off by having 1 Arduino toggle a digital output pin and have the other read the state of that pin. To accomplish this, I have 2 computers with Arduino IDE installed and each one is connected to one Arduino Uno. Both Arduino Uno's are connected with a single male-male jumper cable on Pin 13 of the header. I am watching the state of the pin by looking at the prints in the Serial Console on both computers.
Here is a diagram of my setup:
Computer1 ---> Arduino1[Sender] --------> Arduino2[Receiver] -----> Computer2

The problem I have is that I am seeing when I first start both Arduinos - the sender is definitely toggling the output pin high->low->high forever - but the receiver Arduino only shows its input pin as toggling for a few seconds and then it gets stuck high. Sometime later, it may go low for 1 iteration, but then sticks at high again. What is going on? I would expect to see the sender and receiver show high->low->high forever. The code seems simple but I must be doing something wrong - thanks for your help.
Sender Code:
int led = 13; // Comm Pin

// Setup pins
void setup() {

  // put your setup code here, to run once:
  Serial.begin(9600);

  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);

}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.println("high");
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  Serial.println("low");
  delay(1000);               // wait for a second
}

Receiver Code:
int led = 13; // Comm Pin

// Setup pins
void setup() {

  // put your setup code here, to run once:
  Serial.begin(9600);

  // Pin is an input - normal state high
  pinMode(led, INPUT);

}
void loop() {

  // Put your main code here, to run repeatedly:
  Serial.println(digitalRead(led));
  delay(1000);

}

Do both Arduino share common GND? If not, your circuit just cannot work the way you want.

You should try to reduce the refresh time period on the receiver to 100ms and check if this still happens.

You should add a random delay in setup of receiver and reduce the sampling time of the receiver to 200ms.
That said, digital communication is an INSANELY EXTREMELY complex process, especially on the physical layer. This is not the correct way for two arduinos to digitally communicate.
Unless you are a teacher and are trying to demonstrate why this would fail, (not criticising), you mustn't use it.
You should use the Arduino wire library to establish communication instead. You can send whole integers, and it's totally reliable (it uses hash checks, guaranteeing correct communication even at 1152000 baud). As a comparison, you're at 1 baud.
You can get a tutorial here: http://www.instructables.com/id/I2C-between-Arduinos/.


text:
How to splice into existing buttons?
I want to control a kettle. It has 4 buttons and a digital disply of the temp. I would like the buttons and disply to remain functional. I just want to make the buttons remoteky pressabke. The buttons are at 5v. There is an almost bread‐board like set of little sockets where they connect to the higher voltage part of the kettle. (Where I see the kettle's built in relay, that powers the buttons and displsy.)k
If I have a 2nd set of wires to my arduino feed into these sockets would there be an issue with the signal from arduino going to the buttons?
Also, I think I might need a relay if I later adapt this for spark/particle core because it is 3.3v is there such a relay?

It might be useful to post a photo of the circuit board/connections.

From safe to less safe, use an opto-isolator; transitor; resistor; direct connection.


text:
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.

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 \".

Thanks AMADANON. Its working. but i used char pointer char*. Once again thank you.


text:
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?

Where is the debouncing?

@IgnacioVazquez-Abrams If I include a debouncing portion, would the Arduino still register every reed switch activation at high wheel speeds?

That depends. Do you expect the wheels to spin in excess of 10kRPM?

As an aside you may find the shock of cycling too great for the reed switch and might want to use a hall sensor instead.

I like to think I'm fast, but I'm no where near that fast. I'll look into adding in that debounce.
And what do you mean when you say "the shock of cycling?"

Not every bike ride is on smooth, even ground. Rough terrain may cause damage or spurious inputs.

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() - 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 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

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

As the 74HC14 is an inverter, you can use a second one to invert the signal, then feed 2 inputs to the Arduino, this will make it easier to write 2 interrupt routines to detect the state changes and measure the time period between pulses

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
   }
}

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):
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.


text:
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?

Most of the time you don't even need to connect a computer to it. Don't use a microcontroller for any sort of security unless you've spent at least a couple of months researching all the possible security issues.

When using no other tools than the regular Arduino IDE for programming the device, it is trivial to retrieve all its memory, including flash and EEPROM and with that the program, password or encryption keys. It is possible to lock the memory down, but the you can't reprogram the device any more and there are companies that specialize in reading AVR memory even when locked.

The trick here is to put the arduino behind the lock. So, unless they break the lock, which would make the password redundant? They have physical access to the arduino. And can use their debugging tools on it.
How were you thinking of inputting the password? By only giving them access to some I/O pins on the outside, I believe it becomes difficult if not impossible to retrieve the code/debug info. Be sure not to use any pins that double as programming/communication.
If someone has physical access, it's unlikely to make any protection. As they can read/re-program/bypass the arduino.

@jippie: You can reprogram a locked AVR: you just have to reset the lock bits first. This requires a chip erase though.

If "they" can get at the Arduino to "plug it into a computer" they can just activate whatever pin it is that unlocks the safe, so the question is redundant.

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.

But note that "quite safe" isn't "perfectly safe"; there are a number of security attacks that don't require you to ever access the memory of the device.

@Ignacio: Yes, that's why I used the word "quite" deliberately. For applications where security is prime (no pun intended) you wouldn't use just an Arduino anyway, but for instance an Arduino combined with this Crypto-shield.


text:
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.

The reported percentage of “dynamic memory” used is actually the percentage of RAM used by static and global variables. A significant amount of RAM can be used by the heap and the stack, which is not reported here as it can only be measured at run time. C.f. this answer and this answer on how to measure the amount of free RAM.

@EdgarBonet That was it. I ran out ram. Make this answer so you can get the credit. I have 2k of ram (Arduino) to start with. With serial initialized & my code, I have around 100 at the start of the program. I am sure that's the issue.

@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 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
    };

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.


text:
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 tutorial
suggesting I code along these lines:
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?

Editorial note: This is not exactly a question of mine, rather a tutorial in a question/answer format. I have witnessed a lot of confusion on the Internet (including here) about this topic, and this site seems like the obvious place to search for an answer. This is why I am providing this tutorial here.

I would do previousMillis += interval instead of previousMillis = currentMillis if I wanted a certain frequency of results.

@Jasen: That's right! previousMillis += interval if you want constant frequency and are sure that your processing takes less than interval, but previousMillis = currentMillis for guaranteeing a minimum delay of interval.

We really need a FAQ for things like this.

One of the "tricks" I use is to lighten the load on the arduino by using the smallest int that contains the interval. For instance, for max 1 minute intervals, I write uint16_t previousMillis; const uint16_t interval = 45000; ... uint16_t currentMillis = (uint16_t) millis(); if ((currentMillis - previousMillis) >= interval) ...

@frarugi87: I sometimes do the same. Note however that, if that type turns out to be smaller than int (uint8_t, but also uint16_t on ARM), you have to cast the result of the subtraction to the appropriate type. Otherwise, because of integer promotions, you end up with the wrong type. BTW, the cast you did write (casting millis()) is redundant.

@EdgarBonet I never totally understood the automatic promotions, so forgive me if this question seems stupid, but.. if all the elements (currentMillis, previousMillis, interval) are uint16_t, will it "promote" the subtraction to let's say int32_t (and so break what I wanted to do)? As for the cast, it's just out of habit (implicit casts raise MISRA warnings, so I tend to avoid implicit casts)

@frarugi87: For each binary operation, if both arguments are smaller than a plain int, then they are both implicitly promoted to int. Otherwise the smaller is converted to the type of the larger, with a preference to the unsigned types (I am oversimplifying a bit, but it's the main idea).

@EdgarBonet thanks for the explanation; I need to keep this in mind when doing <250ms cycles on 8-bit processors to save memory... (8-bit operations on 16-bit processors, as well as 8/16-bit operations on 32-bit processors, do not save memory nor flash)

I wish some answer included opinion on restarting your device, or solution where you manually detect overflow (millis() < 1000) and reset variables timestamps that use nextUpdateMillis as if (currentMillis <= nextUpdateMillis) { }.

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. 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?. 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:

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.
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,
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.

So, you are saying that the code written in the question will actually work correctly?

@Jasen: Exactly! I've seem more than once people trying to “fix” the problem that did not exist in the first place.

I'm glad I found this. I've had this question before.

One of the best and most useful answers on StackExchange! Thanks a lot! :)

This is such an amazing answer to the question. I come back to this answer basically once a year because I am paranoid of messing rollovers.

This is a fantastic answer, except that it doesn't appear possible to "see" timer0_millis from a sketch anymore; you can declare it extern but the linker does not see it. wiring.c does not declare timer0_millis as static so I'm not sure what exactly they're doing, but the answer may need an update.

@AndrewKohlsmith: I just tested setMillis() on an Uno, with the Arduino IDE 1.8.10. It works as expected.

+1. Such an in depth answer that I think my millis() rolled over reading it.

For the use-case of scheduling future events, I really like the compare timestamp forms, rather than forcing them into the common pattern of comparing always non-negative durations since past events.  // You tested the three timestamp-comparison codes on GCC, do you know of compilers that do the the wrong thing/behave differently with the different codes?  // Would if ((t1 - t2) & 0x80000000)  // test the "sign" bit actually be portable on machines with wider unsigned long sizes?

@DaveX: Re: “do you know of compilers that do the the wrong thing [when converting an unsigned integer to signed]?”: I don't, and I don't think such a compiler would be easy to come by. Reducing an n-bit integer modulo 2^n is the only option that makes sense with two's complement, and other signed integer representations are practically gone. Note that, since C++20, this behavior is mandatory. Even though Arduino may not be using C++20, I take this as a sign that most current C++ implementations already do this.

@DaveX: Re: “Would if ((t1 - t2) & 0x80000000) [...] be portable on machines with wider unsigned long sizes”: That wouldn't test the sign bit (which is 0x8000000000000000 on a 64-bit long), but it would still work if t1 and t2 are less than 2^31 ms apart.

Thanks for this answer! If I am only interested in very short durations (say only debouncing switches), it seems like there's no reason to use the "unsigned long" type. I could go with a byte, as long as I don't intend to have durations longer than 255 ms,  right? (I understand that millis() returns an "unsigned long" but I could write my own function that returns a byte in this case)

@RobD: In principle, yes. You have, however, to be aware of the implicit conversions performed by C++. If started and now are bytes (type uint8_t), then now-started is a (potentially negative) int. Using unsigned int would be safer (no integral promotion) as long as you do not write an expression like millis()-started, which would implicitly convert started to unsigned long.

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.

How about a 15ms before rollover and a 10ms after rollover (ie 49.7 days after). 15 > 10, but the 15ms stamp is nearly a month and a half old. 15-10 > 0 and 10-15 > 0 unsigned logic, so that is no use here!

@prakharsingh95 10ms-15ms will become ~49.7 days - 5ms, which is the correct difference. The math works until millis() rolls over twice, but that is very unlikely to occur to the code in question.

Let me rephrase. Suppose you have two timestamps 200ms and 10ms. How do you tell which is(are) rolled over?

@prakharsingh95 The one stored in previousMillis has to have been measured before currentMillis, so if currentMillis is smaller than previousMillis a rollover occurred. The math happens to work out that unless two rollovers have occurred, you don't even need to think about it.

Ah, ok. if you do t2-t1, and if you can guarantee t1 is measured before t2 then it's equivalent to signed (t2-t1)% 4,294,967,295, hence the auto wraparound. Nice!. But what if there are two rollovers, or interval is >  4,294,967,295?

Intervals larger that 49 days will be a bit more difficult, but in most applications not very useful, as the arduino crystal is not that accurate. Over 49 this inaccuracy could result in hours of error. Multiple rollovers can't occur since previousMillis is change when the interval has passed. PS the formula would actually be (t2-t1+4,294,967,295) % 4,294,967,295 since modulo will also give negative values (e.g. -3%2==-1)

does one need to cast the calculation result to unsigned long? Or will this be automatic if the calculation is executed with two variables already declared as unsigned long?

The accepted answer is very good but didn't explain this part.

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;
}

You are right, my millis64() only works if it is called more frequently than the rollover period. I edited my answer to point out this limitation. Your version does not have this issue, but it carries another drawback: it does 64-bit arithmetics in interrupt context, which occasionally increases the latency in responding to other interrupts.

Wrap the millis() in a class!
Logic:

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

Keeping track of reversals:

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

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.

I edited the code to remove the maaaaany errors that prevented it to compile. This stuff will cost you about 232 bytes of RAM and two PWM channels. It will also start to corrupt the memory after you get_stamp() 51 times. Comparing delays instead of timestamps will certainly be more efficient.

Isn't that full static class effectively like namespace?

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


text:
Arduino Servo circuit by example
I have an Arduino program that uses the Thread library to create two concurrent threads, where:

Thread #1 blinks an LED every 500ms; and
Thread #2 blinks another LED every 250ms

I wired things up, flashed the program to my Arduino Due, and it ran beautifully.
I am now trying to add a 3rd thread that sweeps a servo back and forth.
Here's my design:

And the schematic that Fritzing generated for me:

And an accompanying actual picture of the wire up:

If you can see it, I've rigged Pin 10 as an OUTPUT, and attached the servo's signal line to Pin 9. Here's the code:
#include <Thread.h>
#include <ThreadController.h>
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;
int SERVO_PWR_PIN = 10;
int LED_1_PIN = 12;
int LED_2_PIN = 13;

Servo servo;
int pos = 0;

static bool LED_1_STATUS = false;
static bool LED_2_STATUS = false;

Thread blinkLED1Thread = Thread();
Thread blinkLED2Thread = Thread();
Thread servoThread = Thread();
ThreadController master = ThreadController();

void setup() {
    pinMode(LED_1_PIN, OUTPUT);
    pinMode(LED_2_PIN, OUTPUT);
    pinMode(SERVO_PWR_PIN, OUTPUT);

    servo.attach(SERVO_SIGNAL_PIN);

    blinkLED1Thread.onRun(blinkLED1);
    blinkLED1Thread.setInterval(250);

    blinkLED2Thread.onRun(blinkLED2);
    blinkLED2Thread.setInterval(500);

    servoThread.onRun(runServo);

    master.add(&blinkLED1Thread);
    master.add(&blinkLED2Thread);
    master.add(&servoThread);
}

void loop() {
    master.run();
}

void runServo() {
    // Give the servo a few seconds to reset to the starting position.
    servo.write(0);
    delay(5000);

    while(true) {
        for(pos = 0; pos < 180; pos += 1)  {
            servo.write(pos);
            delay(15);
        }

        for(pos = 180; pos >=1; pos-=1) {
            servo.write(pos);
            delay(15);
        }
    }
}

void blinkLED1() {
    LED_1_STATUS = !LED_1_STATUS;
    digitalWrite(LED_1_PIN, LED_1_STATUS);
}

void blinkLED2() {
    LED_2_STATUS = !LED_2_STATUS;
    digitalWrite(LED_2_PIN, LED_2_STATUS);
}

When I flash this to the Due, two disappointing things happen:

The LEDs, which previously blinked at the correct rates, now stay lit and do not blink at all; and
The servo doesn't move

Now perhaps I have a bum servo, or perhaps I haven't wired it up correctly, but the most concerning thing to me is that the LEDs are no longer blinking. I have a feeling that once I get those blinking again, the servo will probably start sweeping as well.
Can anyone spot anything that jumps out at them as being wrong here, wiring and code alike?

The whole point of the (misnamed) Threads library is to avoid calling delay(). Do not delay() inside a thread!

Thanks @EdgarBonet (+1) - can you confirm that delay(...) called in one "thread" would block/lock progress in other threads? Thanks again!

One thing that immediately jumps out at me is you are trying to power the servo from a digital pin.  That is very very wrong.
The servo must be powered from the +5V pin (or +3.3V pin if it's a 3.3V servo) and only the "pulse" pin is connected to an Arduino's PWM capable IO pin.
Also, I don't know how the "Threads" library works, but it looks to me like it's not real threads, but a "round robin" execution of function with time delays.  If one of your functions never returns (like your servo one) then the whole system will lock up.  You need to make your servo function non-blocking like your LED functions.  Give it a 15ms time setting and only move one step of the servo each time it gets called.
Ok, according to comments and research I can confirm that in fact the Thread library is really badly named.  It doesn't run threads, it just runs different functions at different times.  Those functions MUST be "single shot" - i.e., they MUST complete before anything else can happen.  There is absolutely no concurrency whatsoever.  It is entirely up to you to ensure that all your "threads" are fairly simple repetitive operations which are to be run at specific points in time.
Basically the operation is thus:

Add a function and its time to a list.
Work through the list to find a function whose time has expired
Call that function
Continue through the table
Go back to the beginning

If you have two functions both with the same time then one function will be called first and execute to completion, then the other function will be called afterwards, to execute to completion.  Only when a function returns is the system able to move on to the next entry in the function list.
You must not use delay() in your "thread" functions for anything more than maybe 1-2ms of delay in total.  You MUST return from your thread with enough time for your next timed event to execute, otherwise it will be delayed, or never run at all.
So your servo thread would look something like this:

Add my current "direction" to the servo value
If the servo value < 0 or > 180 then invert the direction and limit the value to 0-180.
Write the value to the servo

That is then triggered every 15ms by the thread library.
So as real code it may look like:
void runServo() {
    static int direction = 1; // 1 = up, -1 is down
    static int value = 0;

    value += direction;
    if ((value <= 0) || (value >= 180)) {
        direction = 0 - direction; // Change direction from + to - or - to +
    }

    value = max(min(180, value), 0); // Clamp it to between 0 and 180

    servo.write(value);
}

You are right about the Threads library not implementing threads. It's only for scheduling tasks implemented as functions. master.run() will check whether any registered task is due to run and, if it is the case, call the corresponding function.

Thanks @Majenko (+1) - please see my question under Edgar Bonnet's comment (under the original question) - I have the same question for you! Thanks again!

See my edit. It makes it plain.

Replace value = 0 - direction; by direction = -direction.

@EdgarBonet What's the difference?  In my version it shows that you are subtracting it from 0. In your version you are subtracting it from 0 but not showing it.  It's explicit in mine, and results in the same code.

Besides the fact that unary minus more clearly shows the programmer's intent, the difference is that I would store the result in direction, not in value.

That part I have to admit I didn't notice - a pure and simple typo ;)  The 0 stays though :P


text:
What to with reset pin when laying out Arduino PCB?
I'm designing a PCB with a standard arduino ATMEGA328 DIP IC. Do I need to make a connection to the reset pin?

You absolutely need one! What if you have to reset your processor but you can't detach from the power supply?

"Atmel AVR042: AVR Hardware Design Considerations"

+1 for the ref. “The reset line has an internal pull-up resistor, but if the environment is noisy it can be insufficient and reset can therefore occur sporadically.” So it seems one could possibly live without in “quiet” environments...

Certainly. None of my prototypes use the above circuit, but my final products do.

I don't get the diode however, if you only connect a button. Can noise really cause it to enter high-voltage-programming-mode?

Yes, you do.  The pin needs to be pulled up to Vcc via a pullup resistor - typically 10KΩ.  Also, if you are using the Arduino bootloader and want to program via serial then this pin should be connected to your serial interface's DTR pin through a 100nF (typically) capacitor.  It is also often desirable to provide a reset button which switches this pin to ground.
You should examine the Arduino Uno's schematics and use them as a reference.


text:
New Language - Interfacing with AVR
So I'm taking a class where the project is to create a new embedded language. We are using OCaml for the compiler, so I was looking for a way to interface with AVR or its C library in such a way as I can write programs in my language, then compile and somehow get it on the arduino I have. I was curious if there's a library for OCaml or some sort of white paper for interfacing with the board at a high level or even at a low level where I can get this to work.

The OCAML compiler can emit C code and the Arduino IDE takes C code, so in theory it is possible.
You would need to get the OCAML runtime code ported over to the Arduino IDE. At very least, I think this would be a lot of work. At worst, the Arduino might not have enough memory to support it.

You don't need the Arduino IDE to compile Arduino code: just call avr-g++, like the IDE itself does.

I have no experience with OCaml or with writing compilers, but I would
suggest that you first learn how to program the Arduino, then teach
your compiler to do so.
You may start by using the Arduino IDE and a couple basic tutorials.
There is an option in the IDE for displaying all the commands it runs to
get your program compiled and linked. Take note of these commands, then
throw the IDE away. Alternatively, you can download one of the few
Arduino Makefiles that float around the Web.
You will see that the basic toolset you need is the following:

The AVR flavor of GNU GCC and the binutils. This allows you to program
the AVR in assembly, C and C++. Calling these tools from your own
compiler should be as easy as calling them from the command-line.
The avr-libc, which is a port of
the libc for the AVR, together with some AVR-specific stuff, and the C
runtime. It does not provide a hardware abstraction layer.
The Arduino core library, a beginner-oriented C++ library built on top
of avr-libc. It does provide a hardware abstraction layer and is
source-level compatible with non-AVR based Arduinos.

In terms of language and API, your main choices are: AVR assembly, C +
avr-libc, C++ + avr-libc, C++ + Arduino core + avr-libc. There are
others, of course, these are just the better known. Pick your favorite,
learn how to use it, then teach your compiler.


text:
Hot regulator 7.7V Vin @ 135mA
Sorry folks, I understand this question has been asked quite few times, but I wasn't able to find a definitive answer: my Mega 2560 R3 is powered by 7.7V from Vin, and runs at a steady 135mA (in theory it's 2.7 x 0.135 = 0.38W dissipation). But the regulator with a heat sink still gets hot. Not burning hot but definitely to a point where you'd question whether it's a good idea to leave it running for months.Is this normal? Also is this a sustainable plan for a long running project?The 7.7V (7.7 because I remember the regulator needs a voltage around that to work) is coming from a variable step down module that could deliver a 5V. However I've noticed although it does stabilize at 5V , when the power just comes on it would surge to ~9V for a fraction of a second. My understanding is the 5V input on arduino is assuming clean 5V, so I hesitated there. Any suggestions? Thanks!

That is indeed odd.  How you you measuring the power consumption?  Is there anything else connected to the board?  If you hold the processor in reset, does the regulator remain cool?   How did you measure the 9v spike? It is entirely possible that it is real, but many meters have an "overshoot" in their response to step input changes, so it could also merely be an artifact of how your were measuring.  A storage scope would be useful, but obviously even today costs a few hundred dollars.

5V connects Vin, Gnd connects to multimeter, meter connects to negative. Current fluctuates a bit around 135mA but never goes over 140. For the voltage, the buck converter has a display that tells the output voltage, and it'd show ~9V and then quickly goes down to 5V. You could be right that it's overshooting but again it's a cheap ebay item..

@ChrisStratton The board is driving a GPS module and 10 basic logic chips of various kind, but the current meter should measure all these combined, and I think 140mA is still in the acceptable range of a mega, no?

Using a multimeter to measure current directly is a bad idea. Get a very low value shunt resistor and measure the voltage across it instead,

If you have any communications cables connected which have their own grounds, trying to measure current in the power ground path will be inaccurate anyway, since those grounds may be lower impedance than the one going through the meter's burden voltage.  You really need to unplug everything that unplugs in the way of peripherals and cables and test just the board by itself, both with the chip in reset and running.  Then add things back one by one.

@IgnacioVazquez-Abrams what's wrong with the shunt resistor that is already present in the multimeter?

@Gerben: In the milliampere ranges the resistance is far too high, leading to a not-insignificant burden voltage.

@IgnacioVazquez-Abrams e.g the fluke 83 uses a 1Ohm resistor in the mA range. That will only give a drop of 0.135V. I don't get it. How is this not-insignificant?


text:
Same Arduino Sketch when uploaded from a Linux machine does not work
I am trying out some code using the Arduino IDE. The code basically tries to connect to a server and push some data to it.
When I upload the sketch to the Arduino from Mac (Apple PC running on Mac OS) the code works as expected without an error.
However, when I upload the same code/sketch from a Linux machine on Ubuntu, the arduino does not operate as expected.
I tried taking a diff comparison of the HEX files created in both machines to check whether there are any differences (expecting very few). But found that there a lot of differences.
What am I missing? Why isn't my code working when uploaded via the Linux PC!!!!!

Make sure you're using the correct versions of libraries / IDE you use. Compiler version could be different, but should not matter in most cases. Also you need to give more details, otherwise guesswork is all we can do.

Just got it sorted. Like you said the problem was with the Libraries used. Different version were used in both PCs

'MAC' == Media Access Control, the unique ID given to each Ethernet or WiFi interface. 'Mac' is (sometimes) used as a nickname for Apple, Inc.s desktop and laptop computers. I've edited the question.

I  close this question because it is not reproducible

Got this sorted.
The issue was that different versions of the library was being used in both the PCs. One we made sure that the Linux PC used the same as the MAC one it all worked fine!!!
Thanks Guys


text:
16u2 programming
How does one go about programming the 16u2 on an Uno? I have the isp header (for the 16u2) hooked up to another Uno programmed as ArduinoISP I'm not talking about DFU or USB->UART, I'm talking about using it like a standalone chip (Like, say, a Leonardo or Yun [the 32u4, not the Linux, obviously])

Do you want to use it for something else, or do you want to extent the current firmware on it? I've done the latter to duplicate the reset-output to one of the JP2 headers, so I could use the uno board to program and external atmega over serial. I used DFU to upload, but if you don't care about this DFU bootloader you can use an Arduino-as-ISP to program it. To use the arduino IDE you'd have to create a new board. You can probably copy all/most of it from an ATMega32u4 board.

First you need to write a program for it. There is no Arduino core for the 'XU2, so you will need to write it out longhand. Then you compile it. Then you upload it using ISP. Then you run it. Note that the only pins you have access to on the board are the UART pins, the two on the LEDs, and the 3 on the ISP header.

Plus 4 on jp2, making 9 easily usable gpios, plus 2 status LEDs. And how would I go about making a program, and uploading?

As the OP said, with the ISP, it costs a few bucks on eBay.
Or you can google on how to use one Arduino to program another. That might work too.

@AlexanderM: You use the correct tool.

It doesn't appear to have a linux build. Will try with wine, though.

Uh-Oh, it failed, alternatives?

There's no need to use atmel studio for this - the same compiler installed with the Arduino suite will work - see the source of the existing firmware in the Arduino repositories for an example.  However, that does not mean that the chip will be supported in the IDE or the Arduino libraries, unless you find a version which someone has extended for this.

True, but getting USB and QTouch working is much easier with AS than trying to get the standalone libraries to work with standalone GCC.


text:
What is Reverse Current through an Arduino?
Can someone explain (in a non-wiki technical way) what reverse current is through an Arduino ? Cheers y'all

It's current flowing "the wrong way".
The electronics inside the main chip are designed such that the + side (Vcc) must be at a significantly higher voltage than the - side (GND).  By significantly I mean 2.1-5.5V higher.
Because of that it is expected that the current will flow through the components in one direction (or in a couple of pre-determined directions depending on settings).  Any situation which causes a reversal of that current through the internals is bad, and as called "reverse current".
It could be caused by something as simple as connecting a power supply backwards, or more technical things like the "Back EMF" from an inductive load (motor, relay, etc) entering a pin that is an output and flowing backwards up to Vcc, or "Back Powering" where the chip is not powered but some external device connected to it is powered, and it "leeches" power backwards through IO pins to power the chip.
All of those situations are bad and should be avoided.

Many thanks for getting back. Other then checking my connections/jumpers are the right way round...how do I "spot the signs", test & prevent a reverse current in a circuit b4 "frying" my chips in the Arduino ?

Make sure all inductive loads have flyback diodes, and ensure that external circuitry is never powered without the Arduino powered.

Adding resistor between the arduino, and signals that might have a higher voltage than that of the arduino. This will help prevent to much current going through the clamping diodes (and break) inside the arduino chip. I can't find the specific value for the clamping diodes but I thinks it's around 1-2mA max.


text:
Arduino Servo is behaving strangely
I am trying to use the Arduino Servo library to drive a simple servo and am having some difficulty getting it to even move.
Here's the setup:

And the schematic that Fritzing generated for me:

And the code:
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;

Servo servo;
int pos = 0;
bool GOING_UP = true;

void setup() {
    // Attach the servo and give it a few seconds to reset to the starting position.
    servo.attach(SERVO_SIGNAL_PIN);
    servo.write(0);
    delay(5000);
}

void loop() {
    if((GOING_UP && pos < 180) || pos == 0) {
        GOING_UP = true;
    } else {
        GOING_UP = false;
    }

    int step = 1;

    if(!GOING_UP) {
        step *= -1;
    }

    pos += step;

    servo.write(pos);
    delay(15);
}

When I run this, nothing happens. When I attach a multimeter and set it to the "6V" setting, I have found some strange readings:

When I connect the red multimeter lead ("red lead") to the 5V line connecting the Arduino to the breadboard, and the black multimeter lead ("black lead") to the black GND line connecting the Arduino to the breadboard, I get readings around 5V; but...
When I connect the red lead to the red power line going to the servo, and the black lead to the black GND line coming back from the servo, I get a voltage reading of roughly -20V!!!

I'm not sure what this means/implies. Is anything jumping out at anyone? Anything I can troubleshoot here? Thanks in advance!

The odd voltages might suggest that the servo isn't actually (fully) connected to the Arduino. As it's a diagram of the breadboard layout, not a photo, I can't say for sure, but on some breadboards the +ve/red and -ve/black rows are sometimes split in the middle. i.e. if you were to connect the Arduino's +5v to one end of the breadboards red row, and the servo to the other end, they might not be joined (same applies for -ve/black). Just a thought; apologises in advance if I’m stating the obvious.


text:
Custom Arduino library problem
I have made my custom serial(UART) library.
So I made uart.h and uart.cpp files as following.

uart.h

#ifndef UART_H
#define UART_H

#include <avr/io.h>
#include <stdlib.h>

//creating class named uart
class uart{

  public:

    // creating constructor
    uart(void);

    //function to start uart at given baudrate
    void start(int baudrate);

    // function to read uart input
    unsigned char read();

    // function to print data on serial monitor
    void print(unsigned char data);

    // function to print string on serial monitor
    void print(char *string);

    // function to print data with given base
    void print(unsigned char data,unsigned int base);

    //function to print data like printf
    void print(char* str,unsigned char data);

    // function to read data by printing string
    unsigned char read(char* string);

};

#endif

uart.cpp

#include "uart.h"

uart::uart(void);

void uart::start(int baudrate){

    long BAUDRATE = ((F_CPU)/(baudrate*16UL)-1);

    UBRR0H = (BAUDRATE >> 8);

    UBRR0L = BAUDRATE;

    // enable recieve and transmit
    UCSR0B |= 1 << RXEN0 | 1 << TXEN0;

    // data size is equal to 8 bits
    UCSR0C |= 1 << UCSZ00 | 1 << UCSZ01;
}

unsigned char uart::read(){

    //wait until receive complete.
    while(!(UCSR0A & (1 << RXC0)));

    // return received byte
    return UDR0;
}

void uart::print(unsigned char data){

    // wait until UDR is empty
    while(!(UCSR0A & (1 << UDRE0)));

    //place data into UDR
    UDR0 = data;
}

void uart::print(unsigned char* string){

    int index = 0;

    // print string character by character
    while(string[index] != '\0'){

        print(string[index]);

        index++;
    }
}

void uart::print(unsigned char data,unsigned int base){

    //buffer to store converted data
    char buffer[10];

    //convert data to ascii
    itoa(data,buffer,base);

    //print converted data
    print(buffer);
}

// function to print data like printf(%d,data);
void uart::print(char* str,unsigned char data){

    int index = 0;

    // print string character by character
    while(str[index] != '\0'){

        if(str[index] == '%'){

            index++;

            if(str[index]=='d') print(data,10);

            else if(str[index] == 'b') print(data,2);

            else if(str[index] == 'x') print(data,16);

            index++;
        }
        print(str[index]);

        index++;
    }
}

unsigned char uart::read(unsigned char* string){
    // print given string
    print(string);
    // return read char
    return(read());
}

test.cpp

#include "uart.h"
int main(){
    uart.start(9600);
    uart.print("Hello world\n");
}

Now all of above function works if i write all function and declations in single .h file and don't divide my header file in .h and .cpp file. if i compile this given program i get following error.

Error

src/uart.cpp
src/uart.cpp:3:16: error: declaration of 'uart::uart()' outside of class is not definition [-fpermissive]
 uart::uart(void);
                ^
src/uart.cpp:39:6: error: prototype for 'void uart::print(unsigned char*)' does not match any in class 'uart'
 void uart::print(unsigned char* string){
      ^
In file included from src/uart.cpp:1:0:
src/uart.h:31:7: error: candidates are: void uart::print(char*, unsigned char)
  void print(char* str,unsigned char data);
       ^
src/uart.h:28:7: error:                 void uart::print(unsigned char, unsigned int)
  void print(unsigned char data,unsigned int base);
       ^
src/uart.h:25:7: error:                 void uart::print(char*)
  void print(char *string);
       ^
src/uart.cpp:30:6: error:                 void uart::print(unsigned char)
 void uart::print(unsigned char data){
      ^
src/uart.cpp:91:15: error: prototype for 'unsigned char uart::read(unsigned char*)' does not match any in class 'uart'
 unsigned char uart::read(unsigned char* string){
               ^
In file included from src/uart.cpp:1:0:
src/uart.h:34:16: error: candidates are: unsigned char uart::read(char*)
  unsigned char read(char* string);
                ^
src/uart.cpp:20:15: error:                 unsigned char uart::read()
 unsigned char uart::read(){
               ^
.build/uno/Makefile:166: recipe for target '.build/uno/src/uart.o' failed
make: *** [.build/uno/src/uart.o] Error 1
Make failed with code 2

PS:  I use inotool to compile and upload my programs to arduino and it works great. So you will find src/ in error.

Please help me. I'm stuck here.

You don't even need the constructor in the first place if it does nothing

Instead of implementing all the variations of print(), you should just subclass Print and only implement size_t write(uint8_t). This way you avoid code duplication, as there are many classes in the Arduino libraries inheriting Print.

I am making these libraries for learning purpose.i have worked with AVR microcontollers but arduino libraries amazed me.i like its code structure its very well managed.but i found one disadvantage is that memory consumption with its libs.any way thanks for suggestion.

If you solved the question, please mark the asnwer that asnwer the question or make your own answer. And edit the topic removing the [SOLVED]

uart::uart(void);

That's a prototype, not a function.  It needs a body.  Also, using "void" to say "no parameters" is really confusing.  Better to leave it out all together.
uart::uart() {
}

uart.start(9600);
uart.print("Hello world\n");

uart is a class, not an instance.  You should be using uart::start(9600) if you first set your functions to be static, or create an instance from the uart class:
uart myUart;

int main() {
    myUart.begin(9600);
    myUart.print("Hello world\n");
}

Watch your random unsigned entries...
uart.h:
unsigned char read(char* string);

uart.c:
unsigned char uart::read(unsigned char* string){

... There may be others too.

Thank you for your reply.i will correct my mistakes as you mentioned.and let me see if it works or not.

It may take a few iterations. Can't see the wood for the trees at the moment ;)  Get rid of these errors first and we'll see where we can go from there.

is it mandatory to use constructor in class,in my case uart::uart(){ }.

If you don't specify a constructor a "default" empty constructor will be provided.  It's good to be explicit and provide one thought.  You could have it all in the header file though for simplicity...  uart() {}

thank you so much @Majenko ,now my header file is working.thank you so so so much..i was stuck from past two days on this error


text:
Arduino Uno not appearing under ports
I have an Arduino Uno attached to my MacBook Air running the Arduino IDE 1.6.4.
The Arduino was visible in the Serial port section this morning, but then it just disappeared. The ON light on the Arduino still comes on, but I cannot connect to it through the port section. I attached the Uno to another computer and it did not appear there either. However, when a different Arduino is connected to my computer it does show up. I also tried using a different IDE version, and it did not appear there either.
All of the other topics I found regarding this were saying it is the OS's fault, but since I was able to see the other Arduino, I am pretty sure it is not. I updated the FTDI drivers, and I tried using a powered hub and it is still not there.
UPDATE:
When I took the chip out of the UNO that is not appearing and put it into a working UNO, I was able to see it, is it possible that the Serial port is just not working, and if so how would I fix that
Any help would be appreciated.

Have you consider that your arduino is may be burned.

Is anything plugged in to the arduino? does its power light come on? Can you tell if its running the last program you uploaded still?

This doesn't seem to be the case since it works on another computer...

Step one: from a terminal, run sudo dmesg and note the last line.  Step two, plug in the Arduino.  Step three: run sudo dmesg again and find the same last line.  Step four: post what comes after that line into your question.

@BrettAM There were things pluged into the arduino but I took them off and the arduino still did not show up, the power light is on, and I am not sure is the last program running because all it did was print to the serial monitor.

@Akkilah I do not think so, as the power light still comes on

@Majenko On both times the last line remained the same, it is 'Google Chrome He (map: 0xffffff80145feb40) triggered DYLD shared region unnest for map: 0xffffff80145feb40, region 0x7fff97c00000->0x7fff97e00000. While not abnormal for debuggers, this increases system memory footprint until the target exits.'

Are you plugging it directly into the mac or into a hub? If it's a hub, is it a powered hub?

@Majenko I am plugging it directly into my mac

I have an UNO where I have to hold the cable at the right angle for it to register.  The fault is with the USB socket on the UNO.  Try applying pressure to the plug from different angles.

@Majenko No that did not work, I do not think it is the cables fault, as the same cable works fine with another uno

As I said, the fault with mine is the socket, not the cable - the contacts inside the socket don't make good contact with the plug.

@Majenko The same socket also works fine with another arduino using the same cable

That makes no sense - I am talking about the socket on the Arduino itself - how can you swap that to another Arduino?!

@Majenko Sorry I was quick reading, I tried holding the cable at different angles to the uno's socket but it is still not appering up on the computer

@Akkilah Is there a way to check

@user10529: if you got anther PC go and try on it

@AnnonomusPenguin: at first i though i didn't read his post correctly , but after reading it again , there was no mention of him trying the problematic UNO in a different PC

@Akkilah I tried it on another computer on another computer and it still did not show up

@user10529 : if it for my i would count it as fired, but you can  check this link if you really wanna make sure its burned  http://goo.gl/gtHtgR

@Akkilah The green led on mine does come on. The led on pin 13 does not come on because I have changed the sketch

@Akkilah Is there anything I can do if it is fried

@user10529 : Im wondering if your older sketch ( the last  one u uploaded to the bored) still working ?

@Akkilah Unfortunately all that sketch did was print something to the Serial Monitor(it was a I2Cscanner)

@user10529: you can check the answer given in this link http://goo.gl/BDJJwZ as im actually run out of idea

@Akkilah Is there a way to check what part of it is fired

@user10529 : have you tried to re-upload bootloader to ur UNO

@Akkilah No i looked into it but you need to get special equipment

@user10529 : just use on of ur working arduino as AVRISP Programmer, u can check this link http://www.arduino.cc/en/Tutorial/ArduinoISP

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.

If the Arduino doesn't show up on multiple computers, and others do, it may be bricked, or dead. You might try reflashing the chip, and hope that solves your issue. If it doesn't, chances are it's toast.
If however the device simply doesn't show up on one computer, but does on another. It's either a software issue, or a USB issue with that computer.
If winblows OS, try reinstalling, or updating the drivers for the USB, as well as the Arduino. And check your power management on the USB as well. I've seen Windows USB poop the bed if a device is connected / disconnected, or restarted several times in rapid succession. When this happens, sometimes Windows will think the port or device is faulty, and simply stop responding to its presence.
If *nix, make sure you've configured it properly.

When an Arduino stops appearing, it is usually because it's fried. Especially if other machines appear when connected, and the faulty machine appears on no other machine.
Try burning the bootloader.

I do not the bootloader is broken as when I took the chip out of the board and put in into another board that board was able to be seen


text:
Arduino Serial Monitor shows strange ASCII characters
I connected an ArduiMU v3+ via a FTDI-cable to my Mac (OS X 10.10) (latest VC FTDI driver is installed and loaded).
Inside the Arduino-software the Serial Monitor (monitoring /dev/cu.usbserial-AJ038NZ3) shows
a lot of weird ASCII characters.
What could be the reason for this problem?

Here's part of the code I uploaded to the ArduiMu:

void setup() {

// Init Serial for use by Send.cpp and Receive.cpp
Serial.begin(115200);

}

void loop() {
    Receive::doTasks();
}

    void Send::flexSensorData() {
    char packet[64];
    int packetLength = 0;
    IntUnion intUnion;
    FlexSensors::read();    // read sensors before sending
#ifdef BINARY_PACKETS
    packet[packetLength++] = 'F';
    intUnion.intVal= (int)FlexSensors::channel[0];
    packet[packetLength++] = intUnion.msb;
    packet[packetLength++] = intUnion.lsb;
    intUnion.intVal= (int)FlexSensors::channel[1];
    packet[packetLength++] = intUnion.msb;
    packet[packetLength++] = intUnion.lsb;
    intUnion.intVal= (int)FlexSensors::channel[2];
    packet[packetLength++] = intUnion.msb;
    packet[packetLength++] = intUnion.lsb;
    intUnion.intVal= (int)FlexSensors::channel[3];
    packet[packetLength++] = intUnion.msb;
    packet[packetLength++] = intUnion.lsb;
    intUnion.intVal= (int)FlexSensors::channel[4];
    packet[packetLength++] = intUnion.msb;
    packet[packetLength++] = intUnion.lsb;
    intUnion.intVal= (int)FlexSensors::channel[5];
    packet[packetLength++] = intUnion.msb;
    packet[packetLength++] = intUnion.lsb;
    packet[packetLength++] = calcChecksum(packet, packetLength);
#else
    packet[packetLength++] = 'F';
    packet[packetLength++] = ',';
    IntValToChars(packet, &packetLength, (int)FlexSensors::channel[0]);
    packet[packetLength++] = ',';
    IntValToChars(packet, &packetLength, (int)FlexSensors::channel[1]);
    packet[packetLength++] = ',';
    IntValToChars(packet, &packetLength, (int)FlexSensors::channel[2]);
    packet[packetLength++] = ',';
    IntValToChars(packet, &packetLength, (int)FlexSensors::channel[3]);
    packet[packetLength++] = ',';
    IntValToChars(packet, &packetLength, (int)FlexSensors::channel[4]);
    packet[packetLength++] = ',';
    IntValToChars(packet, &packetLength, (int)FlexSensors::channel[5]);
    packet[packetLength++] = ',';
    IntValToChars(packet, &packetLength, calcChecksum(packet, packetLength));
    packet[packetLength++] = '\r';
#endif
    Serial.write((uint8_t*)packet, packetLength);
}

You're sending non-ASCII data.

Or a wrong Baud rate is set.

I tried all baud-rates. It is always the same.

You only need to try one: the one you gave to Serial.begin().

I added to code I've loaded on the Arduino to the initial question.

This code is not sending anything through the serial port.

@EdgarBonet Oops, exchanged it for one of the write-function. They all use Serial.write((uint8_t*)packet, packetLength);

As already said, you are sending binary data so what you receive is (probably) right. Try to send "Hello world" and see if it works.

The code you posted is incomplete; there is no evidence here that Send::flexSensorData() is called. Also, since your code includes conditional compilation, you should indicate the value of BINARY_PACKETS so we don't try to guess it from your code...

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


text:
How to control a large number of devices with an Arduino
I'm doing some initial research on a project I have in mind. I am super new to all this Arduino stuff so taking it slow and gathering lots of info.
I want to control around 1000 small linear actuators to push/pull a very small load. The purpose of this question is specifically how to manage that many devices. The devices won't ever need to start their own transmissions so the Arduino can get everything done by polling them ...I hope ...and I don't think it would be a lot of data to each device but I imagine overall it may be. I want to control each device at the "same" time, all with the same cabling distance (around 2m). From what I can tell, a CANbus  is exactly what I need, where I can assign a unique ID to each device (node) and then write some code to control the network array.
In summary, is a CANbus the ideal bit of hardware here to work with an Arduino to control in real time such a high number of devices?
Thanks,
Nick.
Edit: Sorry for the vagueness, I'm very new to all this so really just looking for keywords to help scope my project out before asking more complex specific questions. It's difficult to formulate what's in my head to experienced people without sounding like a goose. I'm experienced on the software side, but the hardware i/o is all brand new.
Ultimately, I am wanting to sample a grey scale image/sequence of images and depending on the value sampled in a 0-255 range which is mapped to the extension capabilities of each actuator to extend/contract in that pixel.
Hope that is more helpful. Thanks.

Perhaps edit your question to clarify some things.  Why do your devices (linear actuators) need to send any data to the Arduino?  Does "control each device at the "same" time" mean you want all the devices to move simultaneously, or just that all of them are in-circuit ready to be controlled?  If the latter, what are your desired and required limits on reaction times and position update frequency?

CAN bus is a solution but possibly overkill for what you want. How are actuators powered and switched. On/off or linear control.  They will need power switching . CAN bus will require node electronics per actuator. CAN bus physical layer is almost identical to RS422 hardware and you can implement multi slave R@422 hardware very cheaply. 1000 devices will require proper design of bus loading for any system and depending on whether control is open loop (one way) or closed loop (to and fro data) a star network topology may suit. More information will help people provide better answers.

@jwpat7 ...have added more project details. The actuators won't ever need to communicate back to the Arduino ...yes I mean move each device  simultaneously and at the number i am investigating, I think will need some special attention in the design.

@Russell McMahon ...thanks very much for your reply. I have updated my question with some more info but your reply is super helpful and helps me expand my research. I have no time limit and this is a learning experience for me so thanks for your suggestions, I can further look into what you have mentioned. I have allot of programming experience but not for devices or in electrical design.

What kind of control signal do your actuators expect?

An ordinary (ATmega-based) Arduino is the wrong choice for this job.  Consider you would use half your RAM just keeping track of the desired state of each actuator.  There are far more capable processors at similar price points for the bare chip, and actually quite a bit cheaper assembled on a board.  Of course you should start by proving your concept with only a handful of actuators, but you might as well start on a platform that is a plausible fit for your goal.

@Edgar Bonet ...that's completely open at the moment. I've not settled on anything in particular. Very early stages so am also looking into what would be the best fit. The biggest question I have at the moment is, can I control that many devices simultaneously. If you have any suggestions, would be super to hear them.

@Chris Stratton ...this is my number one concern at the moment for me as a total novice. Allot of devices and yeah will need to track where they are in realtime. I do plan to start with a proof of concept but am no where near that yet. I want to collect as much info first so I can put a design together. Would REALLY like to hear your suggestions on what might be more capable. Thanks very much.

First thing to do is figure out what it takes to control a single device in the manner you need.  Then think about the required per-device electronics, as that is what will kill your cost/complexity.  You might look at WS2812/etc LED strings for inspiration, or even (if you current requirements are tiny) drivers.  In terms of the master controller, the decision will be driven a lot by the complexity of decision making.  If that requires something the power of a PC, you'll be looking at a comparable embedded board (Beaglebone, etc).  If not, probably an ARM Cortex M0, M3, or M4.

@Chris Stratton ...excellent this is a great start. Thanks very much. Will start looking into these options. Much appreciated. Cheers

Can you expand info on time requirements? How long is acceptable to change 1000 units? How many max can change at once? How important is synchronisation of movements? Afuller explanation of what it does and how may help ensure answer matches need.

This is just a suggestion, certainly not the only possible approach.
Step 1: Get a handful of small linear actuators with a builtin
controller. Some actuators have no controller, and will require one
H-bridge and one analog input each. You do not want these. I have seen
some actuators with built-in controllers that can be driven just like
servos, I would suggest you get some of those. At this point you should
carefully look at costs when choosing the actuators.
Step 2: Learn how to drive those actuators from an AVR-based
Arduino, like an Arduino Uno, using the Servo library. I believe you can
drive up to 12 actuators with a single Arduino.
Step 3: Drive them using two Arduinos in a master-slave
configuration. The master would be a beefy Arduino, like a Mega or a
Due. It would send commands to the slave using, say, an I2C bus. After
sending the set points for the actuators, it would send a "go" order to
the I2C broadcast address. The slave would be the Uno. It would
interpret the commands and actually drive the actuators.
Step 3b: Change the master's program to pretend it is controlling
many slaves, and a total of 1000 actuators. In reality, all the
slaves would have the same I2C address: that of the unique slave
actually available. This will tell you whether your master is powerful
enough for the job, and you will see how the performance scales.
Step 3c: Optimize the slave's code. Try to have it work with an
8 MHz clock, and use as little flash and RAM as possible.
Step 4: Replace the slave Arduino with a bare AVR chip. You will
have to learn how to program it via ISP, but the information is widely
available. An Uno is an ATmega328P at heart, but depending on the
program size, you may get away with an ATmega48A, which is the same
thing only with less memory, and dirty cheap. Or even with a still
cheaper ATtiny. If you can make your program work with an 8 MHz
clock, then use the internal oscillator, which will save you having to
buy an external resonator. All this is to keep the costs reasonable.
Step 4b: Test, test, test. Last chance to change your mind before
committing big bucks.
Step 5: If everything works at this stage, it's time to scale up.
The same master Arduino, and one bare AVR for each dozen actuators, each
with it's own I2C address.

Thanks very much Edgar ...as good a place than any to start. Very much appreciated :) cheers

@NickvanDiem: I just added a few sub-steps.

.@Edgar Bonet ...worthy additions, thank you :) ...do you offer a consultanting service for Arduino projects?

Not formally, but if I can help, and you provide some contact info in your profile, I would be happy to give a try.

.@Edgar Bonet ...great have updated! Ping me a msg