text:
Motor Control Help
Here is my objective:
If the value of EMGv is at or above 900, start moving the motors left. The motors should continue to move left for a maximum of one second, provided EMGv stays at or above 900. If during this time EMGv goes below 900, the motors should move right for one second. Then the motors should stop. At any time after this should EMGv go above 900 again, the process should repeat.
In simpler terms, the project is a robotic hand, wired to an EMG circuit. When the EMG signal gets above 900 the hand should close by the motors all turning left for one second and when the signal goes below 900 the hand should open by the motors turning right for one second.
Here is my loop atm when move(motor #, speed, direction (1 for left, 0 for right)) is the function to move the motors and stop() stops all motors
void loop(){

  unsigned long starttime; //time limit for hand movement
  int EMGv = analogRead(EMG);
  starttime=millis();
  while(EMGv >= 900){
    if (millis()-starttime < 1000) //limit on 1000ms
    {
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left
    } else {
      stop();
    }
  }
}

Perhaps you can edit this question to incorporate some examples and the specification you wrote for a later question.

I suspect you would do well to first write (in English) the exact set of rules you want it to follow -- don't worry about the code to begin with - get it clear in your head what you want the code to do.  (If this is already clear to you, then just write it :-) )
Here's what I think you might mean -- although it's not exactly what you wrote.
If EMG is at or above 900, start moving the motors left.  The motors should continue to move left for a maximum of one second, provided EMG stays at or above 900.  If during this time EMG goes below 900, the motors should move right for one second.  Then the motors should stop.
Once you have that, turning it into code looks well within your ability, judging by the code you've posted.  Here's my attempt - note that it'll only be correct if I have correctly stated your desired rules.  (And if I've correctly guessed how the move API works - I guess it starts the motor moving, that you need to cancel it to stop it moving.  Please say if this is wrong.)
I've used LEFT and RIGHT instead of 1 and whatever, for clarity.
void loop(){
  // If EMG is at or above 900
  int EMGv = analogRead(EMG);
  if (EMGv >= 900)
  {
    unsigned long starttime = millis();

    // Start the motors moving left
    move(0, 255, LEFT); //motor 1, full speed, left
    ...and the other motors...

    // Continue for a maximum of one second, and while EMG stays at or above 900
    while ( (millis()-starttime < 1000) && ((EMGv = analogRead(EMG)) >= 900)) {
      // Just wait
      delay(1);
    }

    // If during this time EMG goes below one second...
    if (EMGv < 900) {
      // ...the motors should move right for one second
      move(0, 255, RIGHT); //motor 1, full speed, right
      ...and the other motors...
    }

    // Then the motors should stop.
    move(0, 0, LEFT); //motor 1, stop, left
    ...and the other motors...
  }

// More stuff here, otherwise it will immediately go round the loop again and start moving again
}

If you want to know what exactly he is trying to do, look at his previous question.

I did, and I get the gist of it, but I still wasn't confident I understood exactly what was wanted.

Thank you for your help! Ive uploaded this code and what it seems to do at the moment is turn the motors forward when the value is above 900 but it does not limit that to one second nor does it reverse them when the value falls below 900. I'm gonna work on debugging but if you have any idea why please let me know! Thanks.

My suspicion is that I incorrectly guessed how to switch the motors off.  My guess was move(0,0,LEFT);.  Is that correct?  Also, I just fixed a bug which would have prevented the reverse from working.

ok ill try it thank you. I suspect an easy way to run the reverse would be: If EMG goes from above 900 to below 900, run reverse for one second. Im just not sure what the Arduino code for that is.

also ive written a function to stop the motors that is simply stop()

Currently, the loop you have provided successfully turns the motors but does not limit them to one second or reverse them when the value goes below 900. Thank you again for your help.

Are you saying that you don't know how to make the motor run in reverse? If that's the case, find that out before getting bogged down with whether the loop is working. (I strongly suspect it is.)

Also, have you done something to stop the main loop() from going round immediately? If not, it'll do just that, meaning it will immediately start turning again (if value >900).

Let us continue this discussion in chat.


text:
XBee: How do I create a packet?
I am currently using a simple protocol I created to send three bytes (unit information, data, and XOR) individually over an XBee radio (3 bytes are considered a single transmission). However, this is not always reliable if a byte is dropped. For this reason I'd like to encapsulate each individual byte as a packet in a way that the Arduino could identify which byte is which and if a byte is lost then just wait for the next transmission. What I am not sure about is creating a packet. I haven't been able to find any tutorials or example code.

The biggest mistake people always make with serial communications of any form is to just send raw data over the connection. While you might just about get away with that on a 100% reliable direct serial connection over a short distance, as soon as you introduce anything with any form of uncertainty to it you are, as you have seen, doomed to failure.
So you have to come up with a reliable method of transferring data in such a way that the receiver knows that it has received valid data, and how to find valid data.
So you need to create a packet. That's not something where you just wave a magic wand and a packet is created. A packet starts it's life in your own head.
In order to reliably transfer data there are a few things you need to consider from the point of view of the receiver:

Where is the start of my data?
How much data is there?
Is this data correct?

The receiver has to have some way of knowing where the start of a packet is amid the torrent of bytes it is being sent. It needs to look out for something unique, something it cannot mistake for anything else. This is called synchronisation. It is often done with a specific sequence of bytes (known as a preamble) that can, through various means, never appear anywhere else.
And at that point things start to get a little more complex, for now you need some way of wrestling that kind of thing into a system that can only send bytes of 0 to 255 with no way of distinguishing raw data from control information like this synchronisation sequence. And that is where the concept of escaping comes in. This is where you nominate certain byte values as control bytes and decide that these bytes will never appear in your data without some kind of marker to say they are data bytes. A common escape marker is 255 (used in the telnet protocol) or 27 (the ANSI ESC character) although any character can be chosen.
For instance if you choose to have a synchronisation sequence of 0xAA, 0x55, you can then decide that neither of those bytes will ever appear in your data without first being preceeded by character 0xFF. So if you happened to have that sequence in your data you would expand it out to 0xFF, 0xAA, 0xFF, 0x55.  But what if you want to send the value 0xFF, in your data? How do you handle that? Well, you also escape 0xFF as well. 0xFF, being the escape character, has no actual value in the data. It only says that the next character must be interpreted as data. So to send 0xFF you would actually send 0xFF, 0xFF. Your receiver sees the first 0xFF and thinks "ah, the next byte that arrives, whatever it is, just be data." It then gets a second 0xFF and knows it is data. (Actually this is the opposite of escaping which says the next character is a control character, but the underlying concept is the same).
If it ever sees 0xAA, 0x55 then it knows, without a shadow of a doubt, that this is the start of a packet, or random noise. And that is where the next two points above come in: Validating your packet.
If your packets are always the same size then all you need to know is how many bytes to expect, which can be hard coded into your software. If you have different sizes of data to send then you also need to tell the receiver how big the data is. This forms part of the packet header. A small block of meta data that preceeds the actual data that holds information about the packet. Depending on your topology that could be things like the size of the data, where the packet came from, where it is going, etc, and maybe a checksum, though some people like to put the checksum after the data since it simplifies sending.
And then there is the checksum. Possibly the most important thing next to the synchronisation. And so easy to get wrong.
Having a checksum that is too simple is not so good. It can be fooled. That is, if values get corrupted in the data with a simple checksum it is far more likely that the checksum still says it's correct than with a more complex checksum. You should read up on existing checksum algoritms, such as Cyclic Redundancy Check (CRC) and things like the checksums used in IP packets. All are good lessons on how to deal with checksums properly.
So far we have just tackled the serial equivalent of UDP - throw a packet at a receiver and hope it gets there. Doing anything more reliable becomes much more complex. If you want to know if your packet actually got there you will need your receiver to acknowledge reception, possibly including some information about the packet it received, such as a sequence number. If the transmitter never receives that acknowledgement it needs to send the packet again, which means it needs to remember what the packet is that it sent. So you need a packet buffer, or even better, a packet queue. And timeouts. And sequence numbers.
That latter is most important. A sequence number is a unique (or unique over a reasonable period of time) identifier for a packet. When a transmitter doesn't receive an acknowledgement is it because the receiver never got the packet, or that the receiver did get the packet but the acknowledgement never made it back to the transmitter? If the latter then the receiver is liable to get the same packet multiple times through retransmission. By including a sequence number the receiver can go "hang on a moment, I have seen this packet already" and it can throw it away sending a new acknowledgement in the process.
So as you can see, reliable communication isn't as simple as just sending data, or even sending data in the form of a struct. There is a whole lot more to learn and understand.
I suggest you read some of the IP networking RFCs to learn more about reliable packet transmission and reception.
Oh, and I haven't even touched on sliding window reception and such like for how to best program your receiver software...

Perfect! This is far superior to anything else I have read online

The x-ctu xbee config tool has a few options worth exploring
such as error checking. This means the xbee would do the work.

OR using the Arduino(s)

Adding a couple more bytes to you your current system with a checksum
of the first 3 bytes would be a simple way to check for a valid
packet.
You could also use a struct of values (along with a checksum).
      Bill Porter has written an Arduino Library called Arduino Easy    Transfer. The library is designed to send and receive a
struct    along with checksum validation. This is an overview page for the library.
Sending and receiving structs over Serial is also covered here

source: Stack Exchange

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

sort: votes


text:
Adding fade to this RGB LED IMU
I've built an accelerometer based dice. It changes colour based on what side of the dice faces up. All is well and good, except I'd like the RGB to fade from one colour to the next instead of changes instantly.
Here's the code:
include <Wire.h>
include <Adafruit_Sensor.h>
include <Adafruit_LSM303_U.h>
include <Adafruit_9DOF.h>
include <Adafruit_L3GD20_U.h>

/* Assign a unique ID to the sensors */
Adafruit_9DOF                 dof   = Adafruit_9DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);

// OUTPUT: Use digital pins 9-11, the Pulse-width Modulation (PWM) pins
// LED's cathodes should be connected to digital GND
int redLEDPin = 11;   // Red LED,   connected to digital pin 9
int greenLEDPin = 10;  // Green LED, connected to digital pin 10
int blueLEDPin = 9;  // Blue LED,  connected to digital pin 11

// Program variables
int red = 255;   // Variables to store the values to send to the pins
int green = 255;
int blue = 255;

int lastOrientation = -1; // previous orientation

void initSensors()
{
  if(!accel.begin())
  {
    Serial.println(F("No LSM303 detected"));
    while(1);
  }
  if(!mag.begin())
  {
    Serial.println("No LSM303 detected");
    while(1);
  }
}

void setup() {

  Serial.begin(115200);
  Serial.println(F("RGB Dice... go!")); Serial.println("");

  /* Initialise the sensors */
  initSensors();

  pinMode(redLEDPin, OUTPUT);   // sets the pins as output
  pinMode(greenLEDPin, OUTPUT);
  pinMode(blueLEDPin, OUTPUT);

  int lastOrientation = -1; // previous orientation
}

void loop() {

  /* Get a new sensor event */
  sensors_event_t event;
  accel.getEvent(&event);

  int orientation = - 1; // dice orientation
  String orientationString; // string for printing orientation
  /*
   * orientation:
   * 1: cyan
   * 2: blue
   * 3: green
   * 4: magenta
   * 5: yellow
   * 6: red
   */

  // read accelerometer
  int x = event.acceleration.x;
  int y = event.acceleration.y;
  int z = event.acceleration.z;

  // calculate absolute values, and determin largest
  int absX = abs(x);
  int absY = abs(y);
  int absZ = abs(z);

  if ( (absZ > absX) && (absZ > absY)) {

    //base orientation Z
    if (z > 0) {
      orientationString = "1, cyan";
      orientation = 1;
      red = 255;
      green = 0;
      blue = 0;

    } else {
      orientationString = "6, red";
      orientation = 6;
      red = 0;
      green = 255;
      blue = 255;
    }

  } else if ( (absY > absX) && (absY > absZ)) {

    //base orientation Y
    if (y > 0) {
      orientationString = "2, blue";
      orientation = 2;
      red = 255;
      green = 255;
      blue = 0;

    } else {
      orientationString = "5, yellow";
      orientation = 5;
      red = 0;
      green = 0;
      blue = 255;
    }
  } else {
    //base orientation X
    if (x > 0) {
      orientationString = "4, magenta";
      orientation = 4;
      red = 0;
      green = 255;
      blue = 0;

    } else {
      orientationString = "3, green";
      orientation = 3;
      red = 255;
      green = 0;
      blue = 255;

    }
  }

  // if orientation changes, print out a description
  if (orientation != lastOrientation) {
    Serial.println(orientationString);
    lastOrientation = orientation;
  }

  analogWrite(redLEDPin, red);   // Write values to LED pins
  analogWrite(greenLEDPin, green);
  analogWrite(blueLEDPin, blue);
  delay(100);

}

Every fading example I have adopted has broken the code so far. I guess my initial code isn't set up for it. Any ideas for a workaround?

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.

What have you tried so far? In each case, how did it break your code? What prevented you from modifying your code to get it to work?

You might get some inspiration here: https://hackingmajenkoblog.wordpress.com/2016/10/02/flexible-led-fading/

You need to be a little clearer about the time that can exist between the sensor values changing. If you fade to slowly the correct value might never be reached before the sensor changes again. Maybe that's what you want?
You can't use a delay().
You need a currentRed, currentGreen and currentBlue so you can fade to the values of red, green and blue.
unsigned long last_reading_ms;
int red = 255;   // Variables to store the TARGET rgb target values for each pin
int green = 255;
int blue = 255;
int currentRed = 0;   // Variables to store the current rgb values of the pins
int currentGreen = 0;
int currentBlue = 0;

void setup()
{
   last_reading_ms=millis();
}

void loop()
{
  /* read sensor every 100ms and set red, green,blue if changed */
  if (millis()-last_reading_ms > 100)
  {
    /* Get a new sensor event */
    sensors_event_t event;
    accel.getEvent(&event);
    //the rest of your sensor reading code here

    last_reading_ms=millis()
  }

  /* if orientation changes, print out a description */
  if (orientation != lastOrientation) {
   Serial.println(orientationString);
   lastOrientation = orientation;
  }

  calculateRGBFadeTo();

  analogWrite(redLEDPin, currentRed);   // Write values to LED pins
  analogWrite(greenLEDPin, currentGreen);
  analogWrite(blueLEDPin, currentBlue);

  //*** do not use a delay or use a very small one to slow the transition ***
  //delay(100);

}

/* get values 1 step closer to target red, green, blue */
void calculateRGBFadeTo()
{
  /* fade to required rgb values */
  if (currentRed<red)
   currentRed ++;
  else if (currentRed>red)
   currentRed --;

  if (currentGreen<green)
    currentGreen ++;
  else if (currentGreen>green)
    currentGreen --;

  if (currentBlue<blue)
    currentBlue ++;
  else if (currentBlue>blue)
    currentBlue --;

}

Notes:
The fade can be slowed down either with a small delay such as 5 ms. or by using another millis() variable to determine the time since the led was last set.
For example: if (millis()-last_rgb_write_ms > 5)
It's also possible to speed up the fade by using a larger increment. An increment of two, for example, currentRed+=2; instead of currentRed++;
Reminder, the comparison of when the target red, green, blue has been reached will be more complex with an increment greater than 1.
An increment of 2 and a sensor read frequency of 128ms (instead of 100) would ensure the correct RGB values are always reached. Alternatively reading the sensor every 255ms (4-5 times per second) would also ensure the correct RGB values has been reached.
Using millis() and avoiding delays allows many more tasks to be performed with more accurate timings.

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


text:
Waking up async the Arduino while it's sleeping periodically
I´m using LowPower.h and PinChangeInt.h libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.
I´ve reached to wake up the Arduino every 8 seconds using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF) but I can´t combine that periodical awakening with the asynchronous awakening.
Here is my code:
void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

Can anyone help me? Thanks

Only the INT0 (pin2) and INT1 (pin3) pins can wake the arduino from SLEEP_MODE_PWR_DOWN. So I don't know how the buttons could have worked in the first place. Are you sure the uC was really sleeping?

But I´m using the PinChangeInt.h to use any pin to generate the interrupt and it works.

@Gerben According to Nick Gammons How do interrupts work on the Arduino Uno and similar boards? refference Q/A and the comments bellow, it woks (I've tested it). The External Interrupts in all modes and PinChange interrupts too.

This is an exact duplicate of https://arduino.stackexchange.com/q/31659/17196

This one works for me:
#include <PinChangeInterrupt.h>
#include <LowPower.h>

// I want to know when it was interrupted by PCINT:
volatile byte flag = 0;
void handler() {
    flag = 1;
}

void setup() {
  Serial.begin(115200);
  pinMode(A0, INPUT_PULLUP);
  attachPCINT(digitalPinToPCINT(A0), handler, CHANGE);
}

void loop() {
  Serial.println("entering powerDown sleep mode");
  Serial.flush(); // wait for sending all data

  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  if (flag == 1) {
    flag = 0;
    Serial.println("Pin change interrupt");
  } else {
    Serial.println("Timeout");
  }
}

However if you use RISING (or FALLING), it also wakes up from the sleep when pin changes back to the oposite state (and it'll be reported as Timeout).


text:
Using Arduino with Assembly on MacOS
I'm trying to use an Arduino UNO board with Assembly on MacOS, but I couldn't find any documentation about it.
How can I compile and upload Assembly files to the Arduino with MacOS?

You can add source code to the sketch in the Arduino IDE. When adding a new source code file make sure the extension is uppercase .S
Files with .S extension will be compiled as Assembly.
There is an Arduino IDE for the mac but if you want to use an external editor you have many options.
The simplest is to switch on File>Preferences>External Editor in the Arduino IDE. This makes the IDE work in "read-only/auto-reload" mode allowing edit in a different code editor but compile and upload (without reopening the code) in the Arduino IDE.
There are also the File>Preferences Verbose Compile and Verbose Upload options in the Arduino IDE. These options will show you the commands used to compile, link and upload. You will see that the IDE runs other programs, outside of the IDE, such as avrdude and g++. Therefore a small script file can be created to call the same commands from a different IDE if the external editor doesn't have a facility to run external commands.
The verbose output will show where the tools and sources for build and upload are located. Normally for Uno (avr) they are below [IDE Folder]\hardware\arduino.

Yes, I know how to use Assembly, because I'm using it in a module on my course. :) It's based on Linux and I've been using the labs to work on it, but it'd be easier on my Macbook. Is there a way to compile/upload it via emacs?

Okay I have edited my answer, I hope it helps. Maybe a good idea to edit your question with the additional clarity.


text:
Update Variable via Arduino to Arduino I2C
I am attempting to send a simple 1 byte value from one arduino to another using I2C with the Wire library. From reading I see that this is typically done using the event monitor supplied by the Wire library, but this has caused problems for me because the handler function may only have one argument and it must be a void function or else the library throws errors during compilation. So I have a couple of questions about what is or is not possible with the Wire library short of modifying the source:

Should the Wire.available() function respond to attempted transmissions if the event handler referenced above does not exist? My first idea was to simply write my own function that would be called whenever this value is not 0, but it appears that this value never changes - unless the event handler is used.
Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments? Because recall from above that I cannot pass any arguments besides the one specified for the number of bytes received.

I cannot understand how this library could be useful for Arduino to Arduino communication if it is literally not possible to use the transmitted values anywhere other than inside of the event handler. My next step is start modifying the source to suit my needs, but I would imagine what I'm describing is a basic thing and would be shocked to find out that it's not possible without modification.

Why do you think it's not possible to use it elsewhere? What about global variables and volatile modifier?

One word: Scope. Google it.

I have thought about the volatile modifier, but I was under the impression that this simply means the variable can be changed by an interrupt which means the variable can change in the middle of an iteration of the main function. However, I do not believe this translates to a regular void function having access to that variable. Scope is exactly the problem here is it not? If I set variables using Wire.read() inside of the event handler (in the scope of that function) then how am I supposed to get those values into the scope of the main function without passing that function pointers?

I see now what the issue was. But to answer my questions:

Wire.available(); will not work if called outside of an event handler. I confirmed this while reading through the Wire.cpp source code and it explicitly states that the function should only be called from an event handler.
It is as simple as only a matter of updating global variables. I feel quite silly for not realizing that simply declaring variables outside of a function gives ANY function access to it rather than only the main function.

I see that the other answer mentions applying the volatile modification to the variables, but this is only necessary when the function in question is attached to an interrupt handler.

this is only necessary when the function in question is attached to an interrupt handler. - yes, which applies in your case. :)

Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments?

Yes, that's exactly what global variables are for. Make them volatile as they will be updated inside an ISR (or more exactly, a function called from an ISR).

authors: Максим Жуков


text:
Arduino Serial Response is Slow when in While Loop
Good evening all,
I'm having an issue with a quick "test" project that I am tinkering with (learning the "do's" and "don'ts") the NeoPixel LED strip.  I've been piecing together excerpts from other folks and so far everything is great.
I'm doing it over serial sending switch/case with numbers from the keyboard for different options.  The issue I am currently having is "case 1:", when I hit the "1" key and it fires off, I want to be able to interrupt it immediately by using key "0".  So basically, I'd like it to loop forever after hitting key "1" but terminate after hitting "0".
However, when hitting key "1", then key "0" immediately, the while loop repeats twice, then breaks.  I haven't done any C/C++ since I was 12 and now I'm 38 so now it is all trial and error based so please pardon my syntax.  Any help would be appreciated.
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>

#define PIN 6
#define LEDs 16

int LED_Fade_Interval = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {

  Serial.begin(9600);

  strip.begin();
  strip.show();

}

void loop() {

  while (Serial.available() == 0);

  int numKey = Serial.read() - '0';

  uint32_t low = strip.Color(0, 0, 0);

  switch(numKey)
  {

    case 1:
      Serial.println("LED Strip is ON - BLUE FADE");
      while (numKey != 0)
      {
        int numKey = Serial.read() - '0';
        delay(50);

        ws2812_FadeInOut(0, 0, 255, LED_Fade_Interval);

        if (numKey == 0)
        {

          for( int i = 0; i<LEDs; i++){
            strip.setPixelColor(i, low);
            strip.show();
          }

          break;

        }

      }

    case 0:
      Serial.println("LED Strip is OFF");
      for( int i = 0; i<LEDs; i++){
          strip.setPixelColor(i, low);
          strip.show();
      }
      break;
   }
}

// *******************************************
// FADER Function
// *******************************************
void ws2812_FadeInOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

What you are doing is a Scheduler. You can look for already made solutions like jm_Scheduler: https://git.io/v1L0a

Serial.read() reads one character from the Serial stream, or returns -1 if there are no characters to read.
When you send a 1 from the Serial Monitor, the Arduino board first receives an Ascii 1, and then receives a line-end character (eg, an LF from Linux) or characters (eg, a CR and LF from MSWindows).
Since none of 1, CR, or LF are equal to an Ascii 0, the numkey value computed at the fourth line of case 1 is not 0, so the exit condition isn't met.  Thus the fade loop continues running, until it sees a 0 character.
Instead of continuing to read characters within while loops within the switch/case statement, test if more serial input is available.  Note, avoid exiting early from case 1, after you read a digit at the beginning of loop(), read and discard the line-ending characters that follow.

NeoPixels' timing requirements are pretty tight - not necessarily high frequency but high accuracy, for at least certain parts of the serial pulse train. To achieve that, I believe the (Adafruit) NeoPixel library takes over one of the timers during the transmission and turns off interrupts for at least some of the time. That will have a negative impact on any background processes. Read through the NeoPixel library code; it should be clear.
However, while researching my answer (so as to not embarrass myself too badly!), I found this article at josh.com that describes driving NeoPixels with a much lower impact and goes on to demonstrate his technique with a video of a 1000 NeoPixel string(!) driven at 30 FPS by an old, apparently Atmega 168-based, Duemilanove.


text:
Getting the DS18B20 detected and temperature read
I'm quite new with the electronics part of Arduino, but I thought that this was the basic way to get the DS18B20 temperature device hooked up. However, I can't detect it in my program using OneWire and DallasTemperature.
This is an image of my connections:

Basically my approach was like this:
Connect ground on ground on the DS18B20.
Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).
Between the 5V and the two yellow cables, I connected a 4.7K resistor.
Vdd on the DS18B20 is not connected to anything.
Anyone have any idea why this is not working as expected for me?
Thanks in advance!

I can't see the DS18B20 in your picture. Can you please sketch up (eg. on paper) your wiring? I can't quite follow your description.

Vdd on the DS18B20 is not connected to anything.

According to the datasheet:

When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground

Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).

That means port 2 would always be high, right?

According to Temperature Sensor DS18B20 this is the wiring for non-parasitic power:

If you want the two-wire version (parasitic power) it would be:

I didn't get the parasitic power version to work, but the top image explained how the rasistor should be placed in the non-parasitic version, and that did the trick! Thanks a lot!

Glad it worked. The design is the standard "open drain" concept where the output is "pulled high" by the resistor, and the device drives it low when it wants to output a zero. This allows multiple devices to share that wire because it doesn't do anything any harm if multiple devices drive it low at the same time.


text:
How do you figure out an efficient battery setup for a project?
I have a project where I need an Arduino Uno and 4 DC motors to run on batteries. My first thought was that I'll just hook up 3 or 4 AAs to the Arduino and a 9V to the motor drivers.
I googled to be safe and the internet consensus seemed like that method would be very inefficient. Voltage wasn't the problem, but apparently 9V have very low current and I'd be wasting money, and the Arduino wastes current like a madman. Most solutions involved buying additional hardware.
Is there a way I can efficiently power my project without buying more chips?

Our beloved admin Nick Gammon has made a very neat articile on this subject, I suggest you read it and apply as many of the methods he described.
Also, it can be worth to check the requirements of your project, how long should it work on battery to be acceptable? Set some realistic boundarys to avoid getting lost in (trying to) optimizing beyond all practical purposes.
There are two places where you can save power:
In software
The Atmega328P has a few tricks to save power.
Most notably is powering down peripheral devices and/or using sleep modes.
I believe the P version of the Atmega328 also has more power saving modes/ is more efficient overall.
Also take a look at this.
In hardware
An Arduino board has a lot of chips that may not even be neccesary on your battery project.
Most notably the USB interface chip, if you're going to run off battery, you most likely won't need this chip.
But also, the voltage regulator on the Arduino is, I believe, a linear regulator and is likely to be inefficient.
Also power/status LED's will some current.
You can choose to put a ATMega328P on a breadboard, and power it directly with a source that will be between the min/max voltage of the ATMega328P. This way you don't get the losses that a regulator will have.
If you want to use a regulator (for a higher voltage source) you should use a switching regulator, they're typically more efficient.
Mind that on low voltages, the ATMega328P can't do a 16Mhz, but it's actually a pretty interesting point, since it will consume less power on 8Mhz, or even less on 1Mhz.

But wait, you're using motors?
In a project like this, the motors are likely to consume a lot more power as the Arduino. It may not really be worth it to decrease the power useage of the Arduino.

If you can't run the motors for long enough. You will need a more efficient motor driver and/or probably a bigger battery.

Agreed, the DC motors would drain the 9V in no time.
Consider the other way around. The 9V powers the Arduino and the 4 AA batteries power the motor.
Then again, you probably don't need the 9V at all, just power everything off of the 4 AA batteries.
I suggest using a large capacitor (something in the 470-1000uF region) to hold up the supply to the Arduino. Adding a diode before the capacitor will prevent the capacitor discharging to the motors when the motors are drawing a lot of current.
Using 4x 1.5V batteries will result in a voltage of just over 6V. The diode will have a voltage drop of around 0.6V, so the resulting voltage would be 5.4V.
This voltage is to low for the onboard voltage regulator on the Adruino. It is within limits for the raw 5V input (ie. 5.5V).
Optionally you can add a 5V zener diode across the Arduino's power input to protect ti from overvoltage. A 6.8 ohm resistor is added to limit the current flowing through the zener diode. As the voltage drops below 5V, the zener diode will turn off, allowing the micro to operate down to 4.5V. If you change to a lower frequency crystal/resonator you can operate the microcontroller down to 2.7V (1.8V is possible is the clock frequency is 4MHz or less but I doubt the motors will run).

simulate this circuit – Schematic created using CircuitLab

What if you put the resistor on the same line as the zener diode? And not between the capacitor and 5V?

@Paul, The resistor would have a voltage potential across it, meaning that  the voltage across both the resistor and zener would be greater than 5V (ie. 5V + Vresistor). In short, it wouldn't limit the voltage into the Adruino to 5V. I hope this makes sense.


text:
Analog Reference (AREF) pin on Arduino MKR1000 not working?
Has anyone successfully used the AREF pin on MKR1000?
I'm trying to use an EXTERNAL voltage reference (I need 1.5V instead of the default 5V) with:
analogReference(EXTERNAL)

But when I compile I receive the following error message:

MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]

In the documentation (for analogReference) I found the following:

DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
  INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
  INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)
  INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)
  EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.

Thanks,
Corrado

What doesn't work. What have you tried and in what way did it fail?

Please edit your question with this information and any more that you have. Also, try to make your question more specific.

Voted to reopen, you've edited the question and I think it's a very good question now.

The compiler error
MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]

Is actually really simple once you understand what it means.
analogReference(EXTERNAL);

The function analogReference takes an integer as a parameter, but you are passing it EXTERNAL which is an enumeration.  Its probably an enumeration that uses integers for its values, but to the compiler there is a difference.
If you want to disable the warning then you can use the -fpermissive flag on the compile command line, this is not a good idea because it invalidates the "type-safeness" of the language for the whole program.  Instead it is better to address them on a case by case basis and just cast EXTERNAL to an int.
analogReference((int)EXTERNAL);

Interesting, it's somewhat a bug of the 'analogReference()' function to expect an int (could be much more than just one of the enum values)?

Its not a bug, its a feature :)
I think it stems from the tightening of implicit type conversion within the gcc compiler.  I knew it straight away, because I see it so often at work, dragging some legacy code into this century.   Someone could raise it as a fault and have it changed, but its not going to be a priority.

Well, yeah, if you keep it too long out there, people will go use integers to choose the reference. And then correcting it may break those peoples code again. But your answer is a very good one.

In fact, the documentation suggests that for SAMD boards (MKR1000 is based on Zero) a different enumeration should be used where each value is prefixed with AR_ so for example you should use analogReference(AR_EXTERNAL);.

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


text:
How to turn on Solenoid based on Soil Moisture value?
I am powering solenoid with 24 volt as required however I am using TIP122
transistor that has base connected to Arduino Digital Pin 6 via a 1K Resistor.
And the collector is connected to negative side of 1N4001 diode, this also serves as the Negative out for solenoid. and emitter is connected to the 24 volt power input.
The positive input from power source is connected to positive terminal of diode is directly connected to solenoid.

As per the logic I am trying to turn on Solenoid based on Signal from Arduino PIN 6, but for some reason Solenoid doesnt power up.
In my code below I want to turn on solenoid if soil moisture goes above 60. the signal is coming from Pin 6 but solenoid doesnt power up.
#include <SPI.h>

int solenoidPin = 6;    //This is the output pin on the Arduino we are using

int GLED = 5; // Wet Soil Indicator at Digital PIN D5
int RLED = 9; // Dry Soil Indicator at Digital PIN D9
int SENSE = 1; // Soil Sensor input at Analog PIN A1
int val = 0;

int greenLedPin = 2; // LED on pin 2
int yellowLedPin = 3;
int redLedPin = 4;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  pinMode(solenoidPin, OUTPUT);           //Sets the pin as an output

  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  pinMode(greenLedPin, OUTPUT); // LED on pin 2
  pinMode(yellowLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);

  pinMode(GLED, OUTPUT);
  pinMode(RLED, OUTPUT);

}

void loop() {
  val = analogRead(SENSE);
  val = val / 10;
  analogValue = analogRead(lightSensorPin);
  Serial.print("LDR value: ");
  Serial.print(analogValue);
  digitalWrite (redLedPin, analogValue < 55) ;
  digitalWrite (yellowLedPin, analogValue >= 55 && analogValue <= 100) ;
  digitalWrite (greenLedPin, analogValue > 100) ;

  Serial.print(" Soil Moisture: ");
  Serial.println(val);
  digitalWrite(GLED, (val < 50));
  digitalWrite(RLED, (val > 50));
  // Turn on Solenoid Valve if soil moisture value greater than 60
  digitalWrite(solenoidPin, (val > 60));

}

I am doubting on the diode to use , because I am  powering solenoid of 24 volt and not sure if the diode is correct , as per my knowledge, diode can get direct if higher voltage is passed.
Any help will be greatly appreciated.

Maybe connect it to pin 6 instead of to pin 4?

Also 24V on Vin is pretty big voltage. Power regulator might be (and it will be) overheating.

Sorry ignore power input shown in image above as I mention sources of power are different for solenoid and Arduino Vin is not connected to anything

Determine whether it's a problem with your code or a problem with your circuit by connecting the yellow wire to the 5v output of the Arduino - see whether the solenoid actuates.

@MarkSmith I have added updated Fritzing as per the code .  With above circuit solenoid is getting 3.4 volts whether the soil moisture sensor is dipped in water or out of water. Is TIP122 perfect for 24 Volt/3Amp input coming from power adapter

My suggestion is still the same - except for the wire colour as you changed it: break the problem into smaller parts.  Determine whether it's a problem with your code or a problem with one of your circuits by connecting the light blue wire to the 5v output of the Arduino - see whether the solenoid actuates.

@Mark Smith, +1 for breaking down in smaller parts. That way you can find and resolve problems one by one.

J Picqurd's answer is correct BUT a look at your original diagram shows it cannot  work as shown. You show a single wire between Arduino proper and output system. You MUST have two wires (minimum so that one supplies voltage relative to the other. Ground in both systems is usually joined and then the Arduino output voltage relative to ground is produced by the ARduino and "seen" by the controlled circuit.

When looking your schematic and assuming that J1 connector is not powered by your MacBook as your Arduino board, the main problem is located to the GND signal.
In order to have a commutation current to the Base of the TIP122 through the 1K resistor, you need to link the GND signal its Emitter with the GND signal of your Arduino board.
See a proposed schematic from "High-Power Control: Arduino + TIP120 Transistor"

would it be ok, if I take power from 5volt pin of UNO and use stepup xl6009 to convert to 24 volts and power solenoid ?

O boy I used xl6009 to convert 5 volt to 24 volt and supply to solenoid with common ground as you mentioned and its working as expected


text:
Multiple (3) RF transmitters to a single receiver?
How can I have three remote transmitters send distinct signals to a single receiver?
My project requires 3 remote controls, each with 2 inputs.
I need to distinctly identify these 6 signals from the 3 remotes onto one arduino board.
Is this possible to do with one receiver?
Would I be able to pair one remote to one receiver (so 3 receivers), or will there be noise / interference?
What is the simplest and/or cheapest solution to this?
FYI I am going to be using a 315 Mhz remote / receiver (remote control has 4 inputs). I am waiting for them to come in the mail but I want to start thinking about how I will build this.

What transmitters?

Please provide exact reference to these transmitters/receivers. Also, what Arduino library do you use to interface with these devices?

Why all of the down votes? What dose this question lack? Despite the absence of the exact library and device, this concept of this question is clear I think

These transmitter all transmit on the same frequency so if you have multiple receivers they will all get the same signal.
The only way I can see you can do this is make some type of protocol where you send data with a station ID and only the receiver with the station ID matching the message will act on it.
EDIT:
Sorry have to get used to the double-enter making a send.
@JamesWierzba your 'remotes' will need to be more than just a push button to send a HIGH or LOW signal via the transmitter.
Your 'remotes' will need to each have a unique ID, we usually use DIP switches for this. A small microcontroller will need to read these DIP switch and compose the message to be send to the receiver.
A simple message like "ID_BUTTON_PRESS" where ID is the decimal or hex equivalent of the DIP switches.
On reception of the message the microcontroller receiving the message will know which remote it comes from by looking at the ID part of the message.

So each transmitter  will have a unique ID? In the message?

Well, without code they don't, you would have to make your own code to do so.

Oups pressed sent too fast.
You could use the VirtualWire library -> https://www.pjrc.com/teensy/td_libs_VirtualWire.html

Let's give a simple example. You program each receiver with an ID (1, 2 or 3). At the start of every transmission you put the ID of the device you'd like to send to. For example: 2,test. All your receivers get this message, but only the receiver with ID equals 2 will use it. The rest will discard the message.

@Len I'm broadcasting from 3 tramistters, not trying to receive on 3 different receivers (although I can if necassary). The basic problem is this: I have 3 remotes ( 3 people each hold a remote). I need to know which person pressed it. IS that more clear?

Yes, but same principle applies. Let each transmitter send their ID as well and you know which transmitter was used.

@JamesWierzba your 'remotes' will need to be more than just a push button to send a HIGH or LOW signal via the transmitter.


text:
Arduino DUE deadlock problem, watchdog not working
I am using Arduino DUE in my project. The project is massive (about 7000 lines of code in total, with massive schematic), so I decided not to post the whole code and schematic, except explain the hardware and configuration I am working with:

Arduino DUE;
12V switching power supply;
LTC1660 DAC (used withstandard SPI library);
Nextion HMI (Used with standard library #include Nextion.h        //INCLUDE NEXTION LIBRARY);
DS3231 RTC module on I2C bus (Library used: Wire #include <DS3231.h>)
24LC256 EEPROM on same I2C bus (Library used: Ext EEPROM #include <extEEPROM.h>)

The base line, is that on power-on the controller just freezes besides, it can't be the problem with power as I get this problem using both 12 V from switching PSU and 5 V USB cable. I can not really analyse the problem, as the deadlock occurs even before the program start to execute content of void setup(). My best guess is that the deadlock occurs due to infinite loops in the Arduino's twi.cpp where infinite loop can occur if the controller receives no acknowledge
bit. But then again I can not be sure here. However when I push restart button on the Arduino or enable Serial monitor in Arduino IDE when the circuit is powered on , it starts to work, and it works just as expected.
After reading the datasheet for the DUE's μC, I've found that it have the watchdog option embedded:

After a Processor Reset, the value of WDV is 0xFFF, corresponding to
  the maximum value of the counter with the external reset generation
  enabled (field WDRSTEN at 1 after a Backup Reset). This means that a
  default Watchdog is running at reset, i.e., at power-up. The user must
  either disable it (by setting the WDDIS bit in WDT_MR) if he does
  not expect to use it or must reprogram it to meet the maximum Watchdog
  period the application requires. The Watchdog Mode Register (WDT_MR)
  can be written only once. Only a processor reset resets it. Writing
  the WDT_MR register reloads the timer with the newly programmed mode
  parameters.

I've started to explore it, and as I got it, the watchdog is ON by default, and its timer period is 16 seconds by default, so as it is not normally used in DUE, I assumed, that somewhere it is just disabled, and in main.cpp I found the following:
int main( void )
{
   // Initialize watchdog
   watchdogSetup();
   init();
   initVariant();

where watchdogSetup() led to:
void watchdogDisable(void)
{
   WDT_Disable (WDT);
}
void watchdogReset(void)
{
   WDT_Restart (WDT);
}
extern "C"
void _watchdogDefaultSetup (void)
{
   WDT_Disable (WDT);
}
void watchdogSetup (void) __attribute__ ((weak, alias("_watchdogDefaultSetup")));

As I got it, due to this, the watchdog was disabled for DUE by default, and commenting out watchdogSetup(); in int main() would allow the watchdog to work (as watchdog is on at power on by default, according to datasheet).
I've also added the WDT_Restart (WDT); to void loop() of the program in order to kick watchdog every program cycle.
Well, for some reason, that did not help me, and I'm still receiving the deadlock when I power on the controller, even through the watchdog is technically not disabled, after 16 seconds it still do not restart the system. And, pressing the reset button or the Serial monitor in Arduino IDE makes the system run as expected. Am I missing something out? Your help and suggestions are appreciated, shall any additional info be needed, just let me know, I need to get this project running so badly.
By the way, my void setup() function is quite long, and if I set the watchdog to 1 second, using
void watchdogEnable (uint32_t timeout) instead of commenting out watchdogSetup() in main.cpp, and use reset button after power on, I can see the watchdog working as it can't get to void loop() in time in order to reset watchdog (as void setup() takes about 3 seconds due to delays).

Do you know what the purpose of the weak attribute is?

You don't need to comment out the Arduino core source code. Just add the watchdogSetup function to your own code. Try creating a simple sketch first to make sure you get the WDT to work properly before adding it to your existing code

@Majenko, no I dont know what the meaning of the attribute is, can you explain ?

@Gerben, you see, the problem is that the deadlock occure even before the content if void setup() is executed.

@SlavaKrasnikov - I believe you have misidentified the cause. The watchdog (in the state set by the default s/w init code) is disabled (as highlighted by Majenko). Don't complicate your problem by enabling the watchdog! Your original code, with default watchdog configuration, executes the same instructions whether it is starting from a power-on reset, or pressing the rest button, yet the latter "works", which confirms default watchdog config works OK. Previously I saw similar behaviour due to various h/w design issues, but testing your h/w would need more help than fits into a comment. :-(

@SamGibson , I do understand that the problem with the controller freezing might be caused by the external hardware that is connected to my controller, but I was just thinking that the watchdog is kinda "magic pill" against controller deadlock related problems. The fact that the controller freeze on power-on is not as upsetting to me as the fact that the watchdog can not get the controller out of the deadlock by resetting it.

@Slava - "controller freeze on power-on is not as upsetting to me [...]" - Experience tells me this absolutely would be upsetting to me; finding & fixing root cause is vital to preventing recurrence. "watchdog can not get the controller out of the deadlock by resetting it" - I don't understand all your earlier story about this, but I'm not surprised. IMHO you have overestimated what typical internal MCU watchdog is designed to protect against, and what h/w failures it can cope with. You might be able to workaround your (unknown) problem using an external delayed POR circuit. Good luck!

Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on. There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.

Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on.
There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.
The ATmega16u2 can be reprogrammed so that on power-on it provide short "HIGH" period to AT91SAM3X8E reset pin. The program for ATmega16U2 can be found here:
https://forum.arduino.cc/index.php?action=dlattach;topic=167492.0;attach=52901
The updating precision is given here:
https://www.arduino.cc/en/Hacking/Upgrading16U2Due
I've performed the given precision using Arduino UNO as programmer and can confirm that it worked properly.The problem's gone now.


text:
Can't connect to serial port
I'm trying to make my Arduino's LED blink for the first time, but when I try to upload the code I get the following error in the Serial Monitor:

Error opening serial port '/dev/ttyACM0'.
  Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission

BTW, I have serial.debug_rate=9600, so I don't think that's the problem. Can anyone help me with this please?

Did you consider following the provided link and trying the things it suggests?

You can also find more information and tips here: https://hackingmajenkoblog.wordpress.com/2016/08/24/diagnosing-arduino-problems-in-linux/

It seems your serial does not have the right permissions to be opened in user mode. Try adjusting that by typing
sudo chmod a+rw /dev/ttyACM0

on the console (open it by CTRLALTT).

That issue is due to your username not being in the dialout group.
Try: sudo usermod -a -G dialout yourusername and rebooting to load the changes, then check again if the problem still persists...
I wrote an article about that here: Solving Arduino IDE upload problem, and serial monitor error on Ubuntu.


text:
Receiving a packet via XBee radio
I am sending a packet of sensor information over an Arduino XBee setup. The first byte of the packet is the packet header for synchronization. The second byte is the number of bytes in the packet (excluding header and packet size byte). The first byte of the packet payload is an identifying number for the sensor. The second payload byte is the data from the sensor. The third payload byte is an XOR for simple error checking. The first payload byte for the sensor ID will never need to be escaped, but the other two payload bytes may need to be escaped. The following is code I wrote for sending a single packet:
Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(calculatePacketSize(data, XOR)); // Size of packet
Serial.write(unitInfo);
// Check if the data byte needs to be escaped
if(data == ESCAPE || data == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(data);
// Check if the XOR byte needs to be escaped
if(XOR == ESCAPE || XOR == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(XOR);

What I am unsure about is how to process a packet on the receiving end. One issue I see is that because there are a variable number of payload bytes, I cannot check via Serial.available() whether or not there are enough bytes to process the payload during this run through of loop(). How do I go about processing a packet, and making sure the packet was received error free? I need to just discard incomplete packets or anything without a header.

A state machine is what you want. That and to increase your preamble to two bytes, not one.  The reason being is that due to the escaping of the preamble character in the data it is impossible to have that character twice in a row. By then having it twice in a row as the preamble it is unambiguous that it is the preamble.
You should also (if needed) escape the packet size:
Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(PACKET_HEADER); // Packet header for synchronization
uint8_t ps = calculatePacketSize(data, XOR); // Size of packet
if(ps == ESCAPE || ps == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(ps);
Serial.write(unitInfo);
... etc ...

You might like to abstract the escaping into a function:
void sendEscape(uint8_t c) {
    if (c == ESCAPE || c == PACKET_HEADER) Serial.write(ESCAPE);
    Serial.write(c);
}

Then you can just call:
sendEscape(calculatePacketSize(data, XOR));

etc.
Now for receiving. Implement a Finite State Machine. In that machine you have a number of states, such as look for first preamble, look for second preample, look for size, look for id, and look for data. As bytes arrive they trigger the next state.
So you start by looking for the first preamble byte. When that arrives it triggers looking for the second preamble byte - any other byte besides the second preamble byte causes the FSM to reset. If it arrives, then it triggers the reading of the packet length. And so on.
In pseudocode it may be something like:
State is idle.
If character available:
    Read character into variable C

    Select on state:
        State IDLE:
            If C is PACKET_HEADER:
                Set state to PREAMBLE
        State PREAMBLE:
            If C is PACKET_HEADER:
                Set state to GETSIZE
            Else
                Set state to IDLE
        State GETSIZE:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable SIZE
                Clear array DATA and prepare for reception
                Reset Seen ESCAPE flag if needed
                Set state to GETID
        State GETID:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable ID
                Reset Seen ESCAPE flag if needed
                Set state to GETDATA
        State GETDATA:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Append C to array DATA
                Decrement variable SIZE
                Reset Seen ESCAPE flag if needed
                If SIZE is 0
                    If checksum matches
                        Process packet
                    Set state to IDLE

The main thing to watch is the remembering (and subsequently forgetting) that you have just seen an ESCAPE. That way you can know if you have two ESCAPE characters in a row and you only discard the first one - the second gets handled as a real character.
The beauty of an FSM is that at any point in the sequence, if you decide that the packet is invalid (maybe the size is too big, or the sensor ID is invalid) you can just reset the FSM to the IDLE state and reset any flags/counters and you instantly start looking for a new packet.


text:
Arduino bug when "myFile = SD.open" is inside loop()
My Arduino resets / bugs each time I put myFile = SD.open in loop().
In setup() it works fine.
I have a 20*4 LCD and an RTC connected to I2C, an SD card reader connected to SPI, and a fingerprint sensor.
Here is my code:
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
#include <DS3231.h>;

LiquidCrystal_I2C lcd(0x3f,20,4);
DS3231  rtc(SDA, SCL);
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
Sd2Card card;
SdVolume volume;
SdFile root;

int etat = 0;
int getFingerprintIDez();
const int chipSelect = 10;
SDFile myFile;

void setup() {
  lcd.init();
  lcd.backlight();
  rtc.begin();
  finger.begin(57600);
  SD.begin();

  // Reglage Heure
  //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
  //rtc.setTime(10, 57, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(24, 11, 2016);   // Set the date to January 1st, 2014
  if (finger.verifyPassword()) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Initialise");
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Deconnecte");
  }
  delay(2000);
  if (SD.exists("data.csv")) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("data.csv OK.");
    delay (1000);
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Creating data.csv...");
    myFile = SD.open("data.csv", FILE_WRITE);
    myFile.close();
    delay (1000);
  }
}

void loop() {
  if (etat == 0) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Put Finger");
    getFingerprintIDez();
  }
  if  (etat == 1) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("ID #");
    lcd.setCursor(4,0);
    lcd.print(finger.fingerID);
//  myFile = SD.open("data.csv", FILE_WRITE);
//  myFile.print(rtc.getDateStr(1));
//  myFile.print("\t");
//  myFile.print(rtc.getTimeStr(1));
//  myFile.print("\t");
//  myFile.println(finger.fingerID);
//  myFile.close();
    lcd.setCursor(0,2);
    lcd.print("Loged");
    etat = 0;
  }
  delay(1000);
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Found ID #");
  lcd.setCursor(14,0);
  lcd.print(finger.fingerID);
  etat = 1;
  return finger.fingerID;
  delay(1000);
}

Each time I uncomment lines using SD, the Arduino resets at the end of the loop.
What is the problem?

You shouldn't repeatedly open the file, even if you close it in between.  Both the nature of flash based storage and the limitations of object oriented techniques in an Arduino's tight memory mean you should avoid unecessary operations like that.  Also you should check the validity of the file object before you try to do operations on it.

The solution to your problem is to extend your 2 states machine in a multiple states machine.
Declare the enum eState before setup():
typedef enum e_State {
    STATE_START = 0,    // starting the loop (add some initialisation)
    STATE_READ_FINGER,  // Step1: read the finger print
    STATE_DISP_FINGER,  // Step2: display the finger print
    STATE_OPEN_LOGGER,  // Step3: open the log file
    STATE_WRITE_LINE,   // Step4: append a timestamp finger print
    STATE_CLOSE_LOGGER  // Step5: close the log file
} eState;

And update the loop() function with the state-machine:
void loop()
{
    static eState LoopState = STATE_START; // to store the current state

    eState NextState;  // for the next loop

    switch (LoopState) {
    case STATE_START:
        // add additional settings
        NextState = STATE_READ_FINGER;
        break;
    case STATE_READ_FINGER:
        etat = 0; // keep use your 'etat'
        // or return a boolean from your 'getFingerprintIDez()'
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Put Finger");
        getFingerprintIDez();
        if (etat == 1) {
            NextState = STATE_DISP_FINGER;
        }
        break;
    case STATE_DISP_FINGER:
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("ID #");
        lcd.setCursor(4,0);
        lcd.print(finger.fingerID);
        NextState = STATE_OPEN_LOGGER;
        break;
    case STATE_OPEN_LOGGER:
        myFile = SD.open("data.csv", FILE_WRITE);
        if (myFile) {
            // record only if file is opened
            NextState = STATE_WRITE_LINE;
        }
        else {
            lcd.setCursor(0,0);
            lcd.print("Can't open file");
        }
        break;
    case STATE_WRITE_LINE:
        myFile.print(rtc.getDateStr(1));
        myFile.print("\t");
        myFile.print(rtc.getTimeStr(1));
        myFile.print("\t");
        myFile.println(finger.fingerID);
        myFile.flush();
        NextState = STATE_CLOSE_LOGGER;
        break;
    case STATE_CLOSE_LOGGER:
        myFile.close();
        lcd.setCursor(0,2);
        lcd.print("Loged");
        NextState = STATE_READ_FINGER;
        etat = 0;
        break;
    default:
        NextState = STATE_START;
    }
    // next loop()
    LoopState = NextState;
    delay(200);
}


text:
Run 'Serial.begin(9600)' before loop()
My sketch looks somehow like this:
ClassA classA;

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

    classA = ClassA();
    Serial.println("Bar")

    ...
}

void loop() {
    classA.functionFoo();
}

The constructor of ClassA however calls some internal methods that perform a Serial.println().
My problem is, that the first (implicit) call of the constructor of ClassA comes in the first line of the sketch with
ClassA classA;

This is before the Serial interface has been initialized (with Serial.begin(9600)). Therefore the Serial.monitor cannot interpret the first messages coming from the serial interface.
How can I either suppress any Serial.writes before the setup function or otherwise make sure that the Serial interface is initialized before the setup function?

Make classA a pointer and create the new object with new.

You can make your current object a pointer so it isn't instantiated:
ClassA *classA;

Then create an object with new:
classA = new ClassA();

The constructor is then only called when the object is made.
Note that you will have to change your accessors to ->:
classA->myFunction();

Adding the classA = new ClassA(); in the setup() function just after calling  Serial.begin(9600); will be a quite good solution, but as for the use of bool bSerialReady solution, the rework will be important (replacing classA.<function()> by classA-><function()>.

In order to be sure that your classA object doesn't use the Serial.println() function before the baudrate is defined, it is necessary to add functions in your class ClassA and to inform from setup() your classA object.
The simplest way is to add:

a boolean bool bSerialReadyto keep the status of the Serial object,
in all ClassA constructors, initialize that bSerialReady = false;,
add a function void SetSerialReady() to switch the status bSerialReady = true;. The function should be called in the setup()function just after Serial.begin(9600);,
and in all functions of ClassA, add a if-condition if (bSerialReady) before calling the Serial.println().

Your class ClassA will become:
class ClassA
{
private:
    bool bSerialReady;
public:
    ClassA() {
        // ...
        // Initialize bSerialReady
        bSerialReady = false;
    };
    void SetSerialReady() {
        bSerialReady = true;
    };
};

Your setup() function becomes:
void setup() {
    Serial.begin(9600);
    classA.SetSerialReady();
    ...
}

And in functions of ClassA, it looks like:
if (bSerialReady) {
    Serial.println("Bar");
}

Plus, you'll probably want some logic to store and re-issue the messages that would have been issued before bSerialReady became set.

not a bad solution, however, it is only about debug messages. I wouldn't want to change my code too much for them...

@speendo, could you provide an example of your class ClassA source code using the Serial.println() function to display debug message ? Did you have used the same template in the rest of the source code ?


text:
Scan multiple ESP8266
I am working on wifi based LED project which involves various ESP to be connected to router. Basically grouping of ESP has to be done. The android app sends HTTP command to IP address which is given by router to the ESPs, the IP are not static and expires after some time. Now my question is how can mobile app can get the IP of all the ESP connected to router?
Does using HTTP protocol complicates the process? Shall I switch to multicast UDP? or use UnPn Protocol for scanning (Sounds complicated though).
Please help!

HTTP is a 1:1 connection. If you want 1:many you need a different protocol. Multicast UDP is possibly the best way to go - then the ESPs subscribe to the multicast address and you don't care what their IPs are.

So how exactly UDP works? The packets sent to multiple ESPs at once reaches at the same time? For example I am sending value of RED led 254 to 6 ESP, all 6 ESP will glow to RED at once?

https://en.wikipedia.org/wiki/IP_multicast

And who creates the multicast address? Router? or A master ESP is needed?

That link tells you.

This may also help: http://www.esp8266.com/viewtopic.php?f=29&t=2464 - it's wonderful what you find on Google...

It is said that UDP is very unreliable protocol. Packets get lost. How can I make sure they are sent and if not sent, receive feedback and retransmit again.

With great difficulty. It is best if you create your system in such a way that it doesn't care if you lose a packet or two.

Anyway, UDP isn't very unreliable. It's "unreliable" in that there is no built in mechanism for guaranteed delivery. It doesn't mean that packets go astray all the time.

Okay, I understand that.

@Majenko Can I use this app for testing multiple ESPs?? https://play.google.com/store/apps/details?id=com.hastarin.android.udpsender&hl=en

Possibly. Try it and see. Personally I use nc on Linux.

Any option to use with Macintosh?

Not from me. nc (NetCat) may be available in homebrew, or it may not. You'll have to look for yourself. Or ask Google, which contrary to popular belief, isn't my name.

Hahaha, Okay!! By the way, you are not any less than Google

I would go with UDP broadcast, since multicast may need to be set up correctly.

@Paul What is the difference between UDP multicast and broadcast? What is the advantage of using it over multicast?

With multicast it'll get switched to specific groups, broadcast will go to every UDP server on the network.

You can go with UDP Multicast.

The best protocol for these kind of applications is MQTT.
Read more here

MQTT has delay. I need instant response within milliseconds

Yes, Multicast is the only option.

Can you back up your answer with some explanations please?


text:
Does an I²C IO Expander needs additional resistors for outputs?
I have following setup (see also schematic in the end)
Arduino Nano is connected via I²C to the PCF8575C (link) IO Expander.
Both, SCL and SDA have 10kOhm pull-ups to 5V.
The Expander pins are connected to a MOSFET-driver that turns on/off 12V LED stripes.
The Expanders Bus address is set via Expanders A0-A2 pins to 0 (0x20).
The MOSFET driver pins have to be pulled to logic 1 (above 2.2V) in order to turn on the stripe.
Currently Arduino runs an blink example, that turns all Expander IO pins on/off every second (using Arduino Wire Library), but the MOSFET-driver does not turn on/off any Stripe.
I can manually turn on Stripes by connecting MOSFET-driver pins to Arduinos 5V (or 3.3V)
The power supply to the IO Expander is O.K.
By measuring the resistance between GND and IO pins of the Expander, I can see that it alternates every second (so I²C communication to the Expander works also)
Curious thing: While measuring this resistance (holding the multimeter test leads) to GND and to the IO pin of Expander, the MOSFET-driver turns the Stripes on and off! When I take the test leads away it stops working! Magic?!
What am I missing? Do the output pins of the PCF8575C need some extra pullup/pulldown resistors or something else?
Thank you in advance!
Schematics:

What does the datasheet for the chip tell you? (hint: table on page 3...)

@Majenko oh, I see – I need for each output a 1kOhm pullup (to 5V), right?

You need a pullup - the actual value depends on your application. 10KΩ is probably better than 1KΩ since it will reduce current wastage.

Yes, according to the datasheet (which should always be your first port of call for any chip) the outputs are Open Drain. That means you require a pullup resistor, exactly as if the outputs were simple buttons.

I need a pullup resistor? So one and not 15 (for each output)?
Does that mean, I can use single common resistor for all outputs?

No, one pullup resistor per pin you use as an output.

okay, thank you, I'll test that today! But anyway, how can this "mysterious" behavior with the Multimeter be explained?

When you measure resistance you are applying a voltage. That voltage is acting like a pullup resistor.

Adding of missing pullup resistors to the outputs did the trick. Thank you!

Think of the oped drain output (or open collector) as a pin that connects to ground when the device is on. If you connect the anode of an LED to plus and connect the kathode to the open drain pin, then you do not need a pull-up resistor (you may need a current limiting resistor though)
The test leads of the Ohmmeter produce a current to masure resistance, it also provides a current path to ground if the that's where you placed one of the leads. This would explain the Magic
More here about open collector outputs.


text:
Can't run two separated DC Motors
I'm trying to build Bluetooth RC car, but I can't run only one DC motor.. only both of them. Everything works fine, the bluetooth, the app but when i try to go forward/backward/left/right nothing happens, only when i run both of them. I'm running the Arduino Nano with usb cable. The bluetooth connection is stable, The DC motors are working. I don't know what I'm doing wrong. Thanks!

const int AIA = 2;
const int AIB = 3;
const int BIA = 4;
const int BIB = 5;
byte vSpeed = 255;
int state;

void setup() {
pinMode(AIA, OUTPUT);
pinMode(AIB, OUTPUT);
pinMode(BIA, OUTPUT);
pinMode(BIB, OUTPUT);

// Initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
}

void loop() {
  //Save income data to variable 'state'
    if(Serial.available() > 0){
      state = Serial.read();
    }

  /***********************Forward****************************/
  //If state is equal with letter 'F', car will go forward!
    if (state == 'F') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
  /**********************Forward Left************************/
  //If state is equal with letter 'G', car will go forward left
    else if (state == 'G') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Forward Right************************/
  //If state is equal with letter 'I', car will go forward right
    else if (state == 'I') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***********************Backward****************************/
  //If state is equal with letter 'B', car will go backward
    else if (state == 'B') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
    }
  /**********************Backward Left************************/
  //If state is equal with letter 'H', car will go backward left
    else if (state == 'H') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Backward Right************************/
  //If state is equal with letter 'J', car will go backward right
    else if (state == 'J') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***************************Left*****************************/
  //If state is equal with letter 'L', wheels will turn left
    else if (state == 'L') {
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /***************************Right*****************************/
  //If state is equal with letter 'R', wheels will turn right
    else if (state == 'R') {
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /************************Stop*****************************/
  //If state is equal with letter 'S', stop the car
    else if (state == 'S'){
      analogWrite(AIA, 0);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
}

What is meaning "The DC motors are working." ? Are you able to control one DC motor using your analogWrite() calls ?

Most likely unrelated, but...  You can only use analogWrite (PWM) on pins 3, and 5. Also the backwards section seems to be missing settings for BIA and BIB.

It means that are functional. The thing is i can't run only one of them.. only both of them at the same time.

AIA and AIB ar for forward and backward, BIA and BIB for left and right. that's why it's missing at backward.. i don't need to run the left and right motor

Which cases work?    graphics-wise board looks like some sort of a dual L9110S thing.  Is it like https://www.bananarobotics.com/shop/How-to-use-the-HG7881-(L9110)-Dual-Channel-Motor-Driver-Module  ?   Does the board work as expected if you jumper it up manually?

It's L9110S. And works only forward-left and forward right, backward-left and backward-right.. that's it.. IF i disconect the batteries and plug the board in and i put the bridge on VIN and GND it's working great but it doesn't have power. I need power, that's why i connected the bridge to external batteries and the board to another battery. But now it's doing this..

Oh -- probably the separate grounds are causing weirdness.  Tie them down.

Unrelated, but, are you uploading code over bluetooth?

I upload it via usb.

Connect the Nano ground to the driver board ground.  Since they do not share a common ground, they can have odd behavior as their ground planes float.
You need only connect the grounds, the USB can still provide +5 to the Nano, and the +9 can still provide power to the driver.  The only energy that will flow through the black wire connecting the grounds is the energy that flows between pins 2,3,4,5 and the driver's AIA, AIB, BIA, BIB, for the logic signals, which I'd bet is in the sub-uA range.

If I connect the gnd of the driver to nano, then i have to connect the nano gnd to batteries (i e black wire) right? Then i have nano and driver sharing the same power source. But i want to make the driver run on 9v batteries alone and the nano on another power source. So i can have full power to motors. Is it wrong? How am i supposed to make the circuit to achieve what i said?

One more thing. If i connect the nano with usb power source and the driver to nano (gnd and 5v) everything works fine but the motors aren't receiving enough power. The problem is when I'm separating the power sources and make the motors run on their own power, that's when i get the behavior..

Yep, just the black wire.  See update above.  No need to power the Nano with the +9 if you do not want to.


text:
Serial question : Going from Mega to Uno
I have a code sample that uses serial3 (RX3 on a Mega) which I want to try and get working on a Uno.  It reads on RX3 and streams to USB.  What I had read, you use Serial for RX0, however Serial seems to be used for USB
 /*
Arduino Neato XV-11 Laser Distance Scanner
Motor control board v0.2 by Cheng-Lung Lee

XV-11 LDS adapter reads LDS data from RX3 then relay to TX. Also extract the speed
data from the data stream to do speed control on LDS motor. Everythin can power
from USB no extra power required.

Change log:
V0.2 Add simple speed control code update PWM 3 times per rev.
V0.1 Opend loop control version.

This code is tested on Arduino Mega 1280
I/O:
Motor drive by low side driver IPS041L connect to PWM Pin4, Motor power from 5V
Neato XV-11 LDS Vcc(red) : 5V
Neato XV-11 LDS TX(Orange) : RX3

 */

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

 void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

  // prints title with ending line break
  Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

  // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

UNO only has one hardware UART, hence only one Serial, which is linked to USB, but you could still use it for something else by connecting to directly to D0 & D1. However, if you need 2 UART then go for SoftwareSerial.

Thank you, so I need to read on 1 serial (lidar) and stream to the USB?

If you need only RX on one side (lidar) and only TX on the other side (USB), then that should work, provided both links work at same speed and settings (parity...) Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with lidar input.

Oh great thats awesome, maybe post that as the answer.  So I am fine to read from RX0 and write to Serial (USB)

Arduino UNO only has one hardware UART, hence only one Serial available, which is linked to USB, but you could still use it for something else by connecting directly to D0 & D1.
However, if you need 2 separate, independent, UART then go for SoftwareSerial for the second one.
Now, if you need to connect 2 devices, one to exclusively get data from, the other exclusively to send data to, then you can use just one UART, i.e. Serial for both devices, as long as both links work at the same speed and settings (parity...)
Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with input from the first device.
The non USB device providing input to the Uno should be connected to D0 (RX).

authors: บรรพต โสดากุล


text:
Arduino Nano + ESP8266 and saving to EEPROM
I am going to create a project with a friend, but I have some technical questions.
The Arduino Nano has an EEPROM capable of storing the known WiFi connections. Basically what I want is say "Arduino, connect to this WiFi and remember it". When I then disconnect the Arduino completely, it should still save that information. Can the EEPROM store that without power?
I need an easy, but rather small, WiFi module to work with the Arduino Nano. I've looked at the ESP8266. I don't mind soldering the ESP8266 to the Arduino Nano once, but doing it more times (perhaps because I need more GPIO or something) is not a variable solution. If I get the ESP8266 ESP-12, I would only have to solder it to the Nano once. However:

Is the ESP8266 ESP-12 compatible with the Arduino Nano?
I like the ESP-05 because it's small and simple. Would that work?

Are there perhaps better ways of doing this whole thing? Should I go for something else than the Arduino Nano? I need to hook up:

WiFi
Microphone (smallest and easiest way)
LEDs

All these questions are very easily answered using google. You should look at the possible solutions and come back with specific questions. What were your attempts, what did you not understand, etc..?

@WesleyLee I did search using Google, but I haven't been able to get a good answer. I assume the EEPROM would be able to store it while disconnected. I know the ESP8266 works with the Arduino Nano. I come here seeking help on my specific case, as I haven't been able to find answers that clearly describe them.

Quick search shows EEPROM solutions to save data w/o energy both on the Arduino Nano and ESP8266. Another search shows many projects with ESP12, ESP05 and Arduinos. "Better" ways of doing this is not a good format of question for SE and even if it were, we know nothing of you application, so no way we can suggest anything (whats good for your application: less power, availability of parts, reliability, etc etc?).

@WesleyLee What's good for my application is what I tried to explain: WiFi, microphone, and LEDs. I was simply wondering if all of that is achievable using an Arduino Nano. Already now, I see I'm going to have an issue with the microphone and WiFi because of the serial connectivity, so I would have to find a solution to run multiple serial connections.

What does mic has to do with serial? Look up Software Serial. Also, you might not even need an Arduino..

@WesleyLee Oh I agree. Anything that works, works. If it's easy to develop on (like Arduino), it's small (like Arduino), and it's versatile, I'm all ears. All microphones I have seen use serial.

What I meant was.. you can develop with Arduino IDE directly on an ESP12. Look up nodeMCU.

@WesleyLee Oh! So I wouldn't have to get an Arduino Nano, I could simply use the ESP8266 ESP-12E with the NodeMCU firmware?

Yes, but it has trade-offs, might want to look into them before deciding. There's actually a nodeMCU board (and clones) with the USB>Serial adapter embedded which makes prototyping much easier.

@WesleyLee That's what I'm talking about! I've been researching this for a few hours, and this is the first time I've seen this. Damn. Grabbing something like this this (right click -> translate) would work? I can then either create a hotspot or connect to a WiFi network :O That's awesome, man.

"Site available only for Denmark. If you mistakenly nevertheless have been banned(...)" but well, you get the idea. Good luck with your project.

@WesleyLee Ah, I didn't even know. Wow that sucks. I get the idea indeed! Thanks a lot, I've ordered the ESP8266 ESP-12E! :)

I'm sorry for prolonging this but, when I said nodeMCU I meant something like this with an ESP + USB/Serial converter (not a standalone ESP, which is doable but more of a hassle). Not endorsing any vendor in particular. You can use either LUA/or Arduino IDE, I tried LUA and didnt like it very much.

@WesleyLee Oh yeah no problem. This is the one I got: http://i.imgur.com/B065aZt.png

The ESP8266 is a SoC (System On Chip) that includes a microcontroller. For most applications, you’ll need only the ESP without the Nano. ESP-12E boards are very handy for tinkering. You can program the ESP in different languages, even in Arduino C (https://github.com/esp8266/Arduino/).
Note that the ESP is only 3.3V tolerant, so it is not that easy to use it with a Nano that works at 5V. It is of course possible to use logic level shifters, but frankly, I would rather use the ESP alone.
You don’t have to worry about storing WiFi connection settings, they are usually hard-coded in the main program.
Connecting LED is described everywhere on the internet, so I don’t think that is a major problem. If you need a lot of LEDs, you can buy LED strips.
For the microphone I suggest that you search for I²C modules.

Thanks for the comment! The beauty of this is if no known wifi has been found, create hotspot and let the user connect. Then I tell it to connect to the known WiFi, which it should then remember. The LEDs are basically just a couple of WS2812B, so it shouldn't be a problem to power those off 3.3v. I've ordered a ESP-12E NodeMCU and I'm looking forward to that!

It sounds like you are quite new to all this stuff.  In summary I think you are taking the wrong approach and need to re-think things.
EEPROM is capable of storing data without any power.
Both the devices have EEPOROM, also you could look at external devices, which would be easier to replace if you wear them out (limited number of write cycles - see their data sheets for details but they are usually in the tens of thousands).
The difference between the ESP8266 range are the number of GPIO lines they offer up, to the 12E has more than the 5, etc.
You shouldn't be soldering this stuff more than once.  You should design it right in the first place (easier said than done!)  What you could do is mount the Nano on a board that took all the lines off to a single 30 odd pin connector the design a series of daughter boards for the ESP8266 which were compatible with the base board, so you could switch between the different ESPs.
Also, don't forget you will need logic level conversion between the 5V Arduino and the 3.3V ESP8266 unless you are planning on smoking electronics.
What do you think you are doing with the MIC connector?  Are you planning on processing sound on the Arduino?  You might want to research that before you design it.
Are you aware that the ESP8266 can be programmed via the Arduino and has a 80MHz processor and 256KB of RAM (compared to the Nano's 32Mhz & 32KB) so using the ESP as a slave to the Arduino is not necessarily the best idea.
If you are interested this is the approach I would take:
 1. Solder some male pins to the Nano so you can put it into a bread board.
 2. If you have a 12E, Buy a ESP8266 mounting board (£1 for 10 from you favourite Chinese web market) and solder pins to that.
 3. If you have a 5 then solder pins to that.
 4. Make all you other parts breadboard-able and try it all out.
 5. Once it works download Fritzing and draw it up.
 6. Make a Vero board version and play with it for real.

Thanks! Yeah I'm quite new to this. I've bought an ESP-12E NodeMCU and I plan on going with Arduino C on it :)


text:
How to restart void loop if condition is met
This should be a quick question.
I'm trying to figure out how I can restart void loop() if a certain condition is met. In this instance, if (s>10), I want the loop to restart. Any help will be appreciated.
 void loop() {

  if (getDistance(0) == true)                   //if the car passed the first sensor
  {
    while (getDistance(0) == true && getDistance(1) == false);
    unsigned long currentMillis = millis(); //time when the passed the first sensor

    while (getDistance(1) == true && getDistance(0) == true); //wating car to pass the second sensor

    unsigned long endMillis = millis(); //time at which the car passed the second sensor

    unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
    float timeSeconds = timeMillis / 1000.0; //because 1000ms = 1s

    float s = sensorDistance / timeSeconds; //speed = distance / time

    if(s>=7 && s<=10) // for red to turn on
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[2] = {'h','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 2); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low

    }
    else if (s<7)
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[4] = {'h','e','l','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 4); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low
    }

    delay(2000);
  }
}

loop() is just called in a... loop. Hence, if you just return from it, it will be called again.

Of course you could mean you want to restart loop() halfway through the code in loop, in which case you should use the return; statement,  which will cause the current function call to exit immediately and return control to the calling function.  In the case of loop() this will cause it to be restarted.

When programming with arduino IDE, you declare 2 functions, setup() and loop().
Before compilation, arduino IDE basically expands to :
int main(void)
{
    /* run the Arduino setup */
    setup();
    /* and the event loop */
    while (1) {
        loop();
    }
    /* never reached */
    return 0;
}

So, from here you can see that setup() is called once at startup and then, loop() is called in an infinite loop.
Il you return from within your loop function, it will be called again.

To expand on what jfpoilpret said setup() and loop() are called by the code you can't see in every program.  setup() is called once and loop() is called in a while(true) loop until the program crashes or the universe ends.
To call you code while a condition is met you could either wrap it in a loop or an if, within the loop() function, so something like this:
void loop ()
{
    if (s > 10)
    {
        // Your stuff....
    }
}

This will only call your code IF s > 10.  Something you need to watch for is ensuring that there is some code that can cause s to be greater than 10.
You can also move "// Your stuff..." into a function of its own
void MyCode ()
{
    // Your stuff ...
}

and then call this function from inside the if statement.  This makes you code easier to read and easier to fix.
If this answer wasn't what you meant then feel free to comment and I'll see if I can come up with a better answer.

I hate to bring this up, but I've now been programming for 58 years. One curious and often overlooked feature of the C & C++ languages is the GOTO keyword. It can be very useful. My second language was FORTRAN I. I know, now I'm relegated to the 9th circle of he|| where the miscreants are frozen into glaciers head down with their legs protruding?

Regarding the last bit, perhaps not at the hands of the arduino.cc people, since  bothered to mention goto in the official documentation.

goto has legitimate uses, but there is no point in using it if you instead can simply return: “_ If there is no cleanup needed then just return directly_”.

frozen into glaciers head down ... that's one way to keep a cool head