body:
Fixing the typos in your original code, so that it should probably read:

    #include <Streaming.h>

    //setup
    void setup() {
     Serial.begin(9600);  //The faster the better
    }   //Close the setup

    //main loop
    void loop() {
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(1) << endl;
      delay(1000);
      Serial<< _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(2) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(3) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(4) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(5) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(6) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(7) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(8) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(9) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(10) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(11) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(12) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(13) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(14) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(15) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(16) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(17) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(18) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(19) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(20) << endl;
      delay(1000);
      while(1){} //freeze the main loop
    }

Then condensing the *cursor positioning* lines, gives:

    #include <Streaming.h>

    //setup
    void setup() {
     Serial.begin(9600);  //The faster the better
    }   //Close the setup

    //main loop
    void loop() {
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(1) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(2) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(3) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(4) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(5) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(6) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(7) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(8) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(9) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(10) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(11) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(12) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(13) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(14) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(15) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(16) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(17) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(18) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(19) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
      Serial << "\t\t\t\t\t" << _DEC(20) << endl;
      delay(1000);
      while(1){} //freeze the main loop
    }

Then joining the two *cursor positioning* lines, gives:

    #include <Streaming.h>

    //setup
    void setup() {
     Serial.begin(9600);  //The faster the better
    }   //Close the setup

    //main loop
    void loop() {
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(1) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(2) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(3) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(4) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(5) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(6) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(7) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(8) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(9) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(10) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(11) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(12) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(13) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(14) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(15) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(16) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(17) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(18) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(19) << endl;
      delay(1000);
      Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(20) << endl;
      delay(1000);
      while(1){} //freeze the main loop
    }

Then putting each repeated line in a `for` loop, and adding a *Maximum Count* `const` variable, gives:

    #include <Streaming.h>

    const int MaxCount = 20;

    //setup
    void setup() {
     Serial.begin(9600);  //The faster the better
    }   //Close the setup

    //main loop
    void loop() {
      for (int n = 1; n < 20; n++) {
        Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
        Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(n) << endl;
        delay(1000);
      }

      while(1){} //freeze the main loop
    }

However, [jwpat7's answer][1] is much better, and [Nick's answer][2] is the shortest.

  [1]: https://arduino.stackexchange.com/questions/16122/how-i-can-make-serial-output-print-short#answer-16123
  [2]: https://arduino.stackexchange.com/questions/16122/how-i-can-make-serial-output-print-short#answer-16124


sender: user

message:
Unexpected behaviour of blinking LED code

I'm new to Arduino so this may be a really silly doubt but I'm not finding an explanation for it anywhere online. I first uploaded this code (to blink 5 LEDs) on my Arduino Uno :

     void setup(){
     pinMode(12, OUTPUT);
     pinMode(11, OUTPUT);
     pinMode(10, OUTPUT);
     pinMode(9, OUTPUT);
     pinMode(8, OUTPUT);
    }

    void loop(){
    digitalWrite(12, HIGH);
    delay(1000);
    digitalWrite(12, LOW);
    delay(1000);
    digitalWrite(11, HIGH);
    delay(1000);
    digitalWrite(11, LOW);
    delay(1000);
    digitalWrite(10, HIGH);
    delay(1000);
    digitalWrite(10, LOW);
    delay(1000);
    digitalWrite(9, HIGH);
    delay(1000);
    digitalWrite(9, LOW);
    delay(1000);
    digitalWrite(8, HIGH);
    delay(1000);
    digitalWrite(8, LOW);
    delay(1000);
    }

The 5 LEDs glowed brightly. But when I uploaded the following code (using an if statement to reduce the size of the previous one), the LEDs glowed dimly.

    int LEDpin = 13;
    void setup(){
    pinMode(LEDpin, OUTPUT);
    }

    void loop(){
    digitalWrite(LEDpin, HIGH);
    delay(1000);
    digitalWrite(LEDpin,LOW);
    delay(1000);
    if(LEDpin >= 8){
    LEDpin--;
    } else {
      LEDpin = 8;
      }
    }
Also, when I just typed the `if` statement without the `else` part, nothing happened after the LED at pin 8 had glowed on and off. Can someone please tell me why the LEDs glowed dimly in the second one and why nothing glowed after LED 8 when I skipped the `else` part?

sender: assistant

body:
The problem with your code is that:

**you have not initialised all the LED pins as output**. Only pin 13 is initialised as output.

So, initialise all the pins to output. A correct code would look like this:

    int LEDpin = 13;
    void setup(){
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    }

    void loop(){
    digitalWrite(LEDpin, HIGH);
    delay(1000);
    digitalWrite(LEDpin,LOW);
    delay(1000);
    if(LEDpin >= 8){
    LEDpin--;
    } else {
      LEDpin = 12;
      }
    }


body:
As Abhishek Jain explained, the pin's need to be initialised for OUTPUT.

However there is another error.

The code in `loop()` counts down to 8, once, flashing the LEDs, **but** then only lights an LED on pin 8 because it always goes through the `else` which maintains LEDpin's value as 8. LEDpin needs to be reset to 12, after it passes 8.

Better code might be

    int LEDpin = 12;
    void setup(){
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(12, OUTPUT);
    }

    void loop(){
      digitalWrite(LEDpin, HIGH);
      delay(1000);
      digitalWrite(LEDpin,LOW);
      delay(1000);
      if(LEDpin >= 8){
        LEDpin--;
      } else {
        LEDpin = 12;   // <---- start with the first LED again
      }
    }

For what its worth, I wouldn't do the code this way. I would write something using for loops, like:

    const int firstLED = 8;
    const int lastLED = 12;
    int LEDpin;

    void setup() {
      for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
         pinMode(LEDpin, OUTPUT);
      }
    }

    void loop() {
      for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
        digitalWrite(LEDpin, HIGH);
        delay(1000);
        digitalWrite(LEDpin,LOW);
        delay(1000);
      }
    }


body:
As Abhishek mentioned in his answer is correct, but the better way is to use for loops while dealing with many led's.

Let's say you have led's connected from pin 2 to 8.

    int pin = 2;
    void setup()
    {
       for (Pin = 2; Pin < 8; Pin++)
       {
         pinMode(Pin, OUTPUT);
       }
    }
    void loop()
    {
       for (int Pin = 2; Pin < 8; Pin++)
       {
         digitalWrite(Pin, HIGH);
         delay(1000);
         digitalWrite(Pin, LOW);
         delay(1000);
        }
    }


message:
How do nested for loops work?

In the following code from an Arduino sketch will it run the first "for" statement before enacting the second "for" statement. Also how does it know go run the first stamens again? Will it continue to run till both statements are true?

    for(int r = 0; r < 8; r++){
        for(int c = 0; c < 8; c++){
            lc.setLed(0, r, c, HIGH);
        }
    }

body:
What you have there is a nested loop. The first `for` statement runs 8 times, incrementing `r` from 0 to 7. For *each* of those 8 iterations the second `for` statement runs, incrementing `c` from 0 to 7. Thus the `setLed` statement is executed 64 times.

> Will it continue to run till both statements are true?

Yes. Unless you have a `break` or `return` statement somewhere in the part of the code you haven't shown.

Strictly-speaking, a *statement* does not become true. They will run while the test inside the `for` remains true (both tests).

This is standard C++ or C programming. You may wish to consult a C tutorial if you find this sort of thing puzzling.


body:
A `for` statement repeats everything between `{` and `}`, (or just the next line if there is no `{` and `}` a certain number of times.  It's not as simple as you might at first think, but it makes more sense if you write it out as a `while` loop explicitly.

For instance, `for (a; b; c) { ... }` could be re-written as:

    a;
    while (b) {
        c;
    }

So if you had:

    for (int i = 0; i < 100; i++) {
        Serial.println(i);
    }

it could be re-written as:

    int i = 0;
    while (i < 100) {
        Serial.println(i);
        i++;
    }

The two mean exactly the same thing.  A `for` has the three elements - initializer, comparison and iterator.  The initializer is run before the loop starts, the comparison is used to work out when the loop should finish, and the iterator is used to move through each iteration of the loop.

To re-write your specific example:

    for(int r = 0; r < 8; r++){
        for(int c = 0; c < 8; c++){
            lc.setLed(0, r, c, HIGH);
        }
    }

You would end up with:

    int r = 0;
    while (r < 8) {
        int c = 0;
        while (c < 8) {
            lc.setLed(0, r, c, HIGH);
            c++;
        }
        r++;
    }

Now, if we were to do away with the loops altogether and write it all out longhand, what would it look like?  Well, let's start with the inner `c` loop.  That loops from 0 to 7 (while less than 8), so replacing that loop with 8 discrete calls to the function replacing `c` each time would end up with:

    int r = 0;
    while (r < 8) {
        lc.setLed(0, r, 0, HIGH);
        lc.setLed(0, r, 1, HIGH);
        lc.setLed(0, r, 2, HIGH);
        lc.setLed(0, r, 3, HIGH);
        lc.setLed(0, r, 4, HIGH);
        lc.setLed(0, r, 5, HIGH);
        lc.setLed(0, r, 6, HIGH);
        lc.setLed(0, r, 7, HIGH);
        r++;
    }

We could take it a step further and *unroll* the outer `r` loop.  A subset of what you would end up with would be like this (note, I have skipped a lot of the middle ones):

    lc.setLed(0, 0, 0, HIGH);
    lc.setLed(0, 0, 1, HIGH);
    lc.setLed(0, 0, 2, HIGH);
    lc.setLed(0, 0, 3, HIGH);
    lc.setLed(0, 0, 4, HIGH);
    lc.setLed(0, 0, 5, HIGH);
    lc.setLed(0, 0, 6, HIGH);
    lc.setLed(0, 0, 7, HIGH);
    lc.setLed(0, 1, 0, HIGH);
    lc.setLed(0, 1, 1, HIGH);
    ... skipped a lot ...
    lc.setLed(0, 6, 6, HIGH);
    lc.setLed(0, 6, 7, HIGH);
    lc.setLed(0, 7, 0, HIGH);
    lc.setLed(0, 7, 1, HIGH);
    lc.setLed(0, 7, 2, HIGH);
    lc.setLed(0, 7, 3, HIGH);
    lc.setLed(0, 7, 4, HIGH);
    lc.setLed(0, 7, 5, HIGH);
    lc.setLed(0, 7, 6, HIGH);
    lc.setLed(0, 7, 7, HIGH);

There would, of course, be 8 × 8 = 64 entries in there.

`for` loops can be used in lots of other fun ways too.  It's not just a simple "run this X number of times".  For instance, you can loop through a C string until you reach the NULL character at the end of the string:

    for (char *p = str; *p != 0; p++) {
        ... do something with *p
    }

You can iterate through the entries in a linked list:

    for (struct mylist *scan = myListHead; scan; scan = scan->next) {
        ... do something to scan->whatever ...
    }

You can even embed functions in there:

    for (char c = 0; c != '\n'; c = Serial.read()) {
        ... Do something with character `c` until `c` is a line feed ...
    }

As you can see `for` is an incredibly powerful and flexible tool that is often overlooked in favour of the more explicit `while`.


message:
serial communication between several arduinos to pc

Is possible the communication between several Arduinos to one serial port in the PC ?

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

If I have ARD_A, ARD_B,... ARD_Z running with some code like this

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

    void loop()
    {
        while (Serial.available() > 0)
        {
           String stringID = Serial.read()
           int nFound = stringID.indexOf("@ARD_01");
                        // ---> Id is unique for each arduino
           if ( nFound > 0 )
              Serial.print("this is @ARD_01 responding sending some data");
         }
    }

And in the pc there is an exe sending a string:

    "@ARD_01 I want your data"
       process the data
    "@ARD_02 I want your data"
       process the data
    "@ARD_03 I want your data"
       process the data

body:
Not directly, no.  A PC's serial port - either a "real" one or a USB one, can only communicate with one device.

The Arduino, though, is a USB device, so you can just plug them all into a USB hub or a bunch of hubs - each one will get its own COM port.  Managing all those COM ports can be kind of tricky though, especially when you have a lot of devices.

Another option, one that is more widely used when you want to communicate with a lot of *slave* devices from one *master* device is to use a *multidrop* network.  RS-485 is the most popular of these.  It allows you to connect many slave devices to one set of serial wires and the master sends instructions to a slave, and the slave may respond with data and information on request.

RS-485 requires special hardware to interface normal TTL level RS-232 (UART) ports to the bus.

You can read more about RS-485 here: https://en.wikipedia.org/wiki/RS-485


message:
NRF24 Mixing with/without antenna

Is it possible to have the NRF24 module on an Arduino Mini transmitting to an NRF24 with SMA antenna on a Mega?  In that case, would the antenna on the Mega help pickup the signal of the transmitting Arduino Mini?

body:
Yes, and yes.

A module without an antenna is exactly the same as a module with an antenna, it's just that the antenna is part of the PCB. Yes, the module with the antenna will have more sensitivity (able to receive fainter signals) as well as more transmitting power.

The same is true of the modules with the power amplifier.  They again have even more sensitivity and transmitting power.

It is quite common to have a single powerful transceiver with power amplifier and antenna as a base station and then smaller modules as the remote slave devices.  Especially if you couple the base station with a suitable parabolic or uni-directional high gain antenna to point directly at where the slave devices are.


message:
HC-06 data receiving

I've written a script in Python which sends data through the PC's Bluetooth to HC-06 on Arduino.

`state` is an integer from 0 to 1000 (it is controlled through the potentiometer).

<!-- language: c -->

    ...
    gaugeSocket.send(str(state))
    ...

I can't get the right character-to-integer conversion on Arduino (from HC-06 serial).

Arduino code:

<!-- language: c -->

    SoftwareSerial mySerial(10, 11); // RX, TX
    char buf[2];
    int i=0;
    int data;
    int ledPin = 9;

    void setup() {
      pinMode(ledPin, OUTPUT);
      Serial.begin(57600);
      mySerial.begin(9600);
    }

    void loop() {
      if (mySerial.available()) {
        for(;i<2;){
          buf = mySerial.read();
          i++;
        }
        i = 0;
        Serial.print(buf);
        data = atoi(buf);
      }
        analogWrite(ledPin, data/10); //To see how code behaves on LED
    }

Serial print gives me this (if I turn potentiometer from 0 to 1000):

> 0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(60(1ÿ(00(16(0ÿ(23(0ÿ(30(0ÿ(3ÿ(60(43(0ÿ(49(0ÿ(53(0ÿ(5ÿ(90(69(0ÿ(88(0ÿ(10(00(10(00(10(

What am I missing? Is it because I'm sending it as a string? Or is my buffer not the correct size?

body:
Use `itoa` instead of `str`.

`str` just converts the byte to an ASCII character. So `48` will become `'0'`, `195` will become `'ÿ'`, and `191` will become `'('`.


body:
Here is your main problem:

    if (mySerial.available()) {
        for(;i < 2;){
            buf = mySerial.read();
            i++;
        }
    ....

There you are saying "If there is at least one character available in the buffer then read lots of characters from the buffer".

*You can't read characters that aren't there yet.*

So your stream of data is interspersed with the integer `-1` which means "I don't have any data to read!"

I explain it all here: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

By the way - character -1 looks like this: ÿ

You are sending your data as text.  That means, to send the value 348 you are first sending the byte representation of the ASCII character "3", which is the decimal byte value 51.  Then you send the byte representation of the ASCII character "4", which is the decimal value 52, and finally you send the byte representation of the ASCII character "8", which is the decimal value 56.

You look to see if there is one byte available (if(mySerial.available())) and then read that byte into "buf" and increment "i" (by the way, "i" is never reset to 0 - your whole loop strategy is completely wrong, but that's a completely different issue).  You then read a second character and assign that to buf instead.

So if you have the character "3" in the serial buffer you then place that in "buf".  You then read whatever is next in the buffer, which 9 times out of 10 will be nothing, so `read()` returns -1.  So you just assign that to "buf" instead, replacing the "3" that was in there before.

But "buf" is a character array, and you are assigning a character to the whole array, which makes absolutely no sense (does the code even compile as you have shown it?).

Basically your whole reading routine is completely wrong and can never work no matter how much tweaking and advising we do.

The link I provided above describes not only how you should do the reading on the Arduino, but also how you should do the sending from the other end.  It is vitally important that you send something that says "This is the end of the number I am sending" so that the Arduino knows where one number ends and the next starts.  Normally that is done, when sending a textual representation of the number like this, by adding a line feed and/or carriage return at the end of your number.  So instead of sending "348" you send "248\n".

The Arduino then checks to see if there is one character available, and then it adds *just that one* character to the end of the buffer.  If, and only  if, that character is the *delimiting* character then you can take the buffer and translate it into an actual number and reset your buffer to be empty ready to receive the next number.

The link above has good example code showing you exactly how to do that.


body: I think you should check your baud rates. A mismatch in baud rates usually makes that symbol get printed on the screen.


message:
Human circuit trigger

The main idea is to create trigger which can be switched on by touching 2 plates on opposite walls. And these should be performed by few peoples holding each other hands.

Obviously human body has big resistance so I couldn't just connect these plates to ground and to one of Arduino pins.

There is a toy that do almost what I what ([see it there][1]). But I haven't found any information about how to create it by myself.
Do you have any ideas how to create it?

  [1]: http://www.stevespanglerscience.com/energy-stick.html

body:
I just tried it (using my own method), and I got it working with very good sensitivity (should be fine for two people) using a TIP102 Darlington transistor and some resistors. Here is what I did:
[![enter image description here][1]][1]

R1, the 1M pulldown resistor on the first pin of the Darlington is necessary to keep the light off when nobody is touching the wires. Without this, the light will turn on and off frantically.

R2, the 1k resistor keeps the Arduino from draining too much current (since that would be bad for the pin) in the case that your A0 is in OUTPUT mode and set to LOW.

R3 keeps the LED (or in my case, an AC relay connected to an actual light) from draining too much current from the Arduino. Note: The LED leads may be backward (reverse polarity) in the provided diagram.

Here is the code:

    // I release this code under the standard MIT licence;
    // (in addition to whatever StackExchange implies);

    const short triggerThreshold = 10;// Lower is more sensitive;

    void setup() {
      pinMode(A0, INPUT);
      pinMode(A5, OUTPUT);
      digitalWrite(A5, LOW);
      delay(1);
    }

    void loop() {
      short value = analogRead(A0);
      digitalWrite(A5, (value > triggerThreshold) ? HIGH : LOW);
      delayMicroseconds(10000);// 10ms;
    }

Note the `triggerThreshold` setting in the code. If you want more sensitivity, try changing the 10 to a 5. I just tried it, and it becomes *extremely* sensitive, yet it still appears to reliably stay off when I don't touch it. Naturally if you use large plates for touching, electrostatic in the air could set it off, so you may need to change this number to be higher to make it less sensitive, depending on your setup.

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


message:
Atmega168 Watchdog timer

I'm trying to use the watchdog timer to prevent the atmel from being stuck in a loop.

Right now, I have the watchdog timer in System Reset Mode, with a 8sec timer. I reset the timer in every loop while the system is active. But when it goes to sleep, it cannot clear the timer and the whole system resets. Essentially, the system sleeps > System Reset every 8 sec > goes back to sleep.

While this works, I initialize a lot of other hardware with the atmel, and doing it every 8 second seems like a waste of resources.

I want to use the watchdog interrupt somehow only to wake the system up briefly and stop the full system reset. Only if it's truly stuck, it will do a full system reboot. But i'm not sure how the ISR will work or how to reset the timer or toggle.

Here a basic rundown of what I was thinking about.

    ISR(wdt_timer)
    {
        how to stop the full system reboot?
        how to make the interrupt start again?
    }
    ISR(button_press)
    {
          gotoSleep=0;
    }

    void watchdog_init()
    {
     /* Reset the wdt. */
      wdt_reset(); //from wdt.h

      /* In order to change WDE or the prescaler, we need to
       * set WDCE (This will allow updates for 4 clock cycles).
       */
      WDTCSR |= (1<<WDCE) | (1<<WDE);

      /* set new watchdog timeout prescaler value */
      WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */

      /* Enable the WD interrupt (note both interrupt and reset). */
      WDTCSR |= (1<<WDIE) | (1<<WDE);
    }

    void main ()
    {
        watchdog_init();
        //and initialize all the other hardware and power supply

        while (true) //no need to step out of this loop
        {
            reset_watchdog();

            //
            //main program
            //

            if(go_to_sleep=1)  //command received through serial
            gotoSleep();

            //wake up here

        }

    }

body:
Each time the watchdog interrupt triggers, WDIE is reset. You will need to set it again in the loop if you want to continue capturing the interrupt rather than resetting the system.

Also, consider using `<avr/wdt.h>` and `<avr/sleep.h>` to handle (most of) the watchdog and sleep functionality.

    EMPTY_INTERRUPT(WDT_vect);

    void main ()
    {
        watchdog_init();
        set_sleep_mode(SLEEP_MODE_STANDBY);
        //and initialize all the other hardware and power supply

        while (true) //no need to step out of this loop
        {
            wdt_reset()

            //
            //main program
            //

            if(go_to_sleep=1)  //command received through serial
            {
                sleep_enable();
                sleep_cpu();
                sleep_disable();
                WDTCSR |= _BV(WDIE);
            }
        }
    }


message:
Integrating two Arduino Ethernet libraries in one sketch

I am trying to integrate two different Arduino Ethernet libraries, EtherShield and UIPEthernet in one sketch.

EtherShield library is used to control LEDs via Android mobile application. While UIPEthernet is used to control the same LEDs via Web Server.

Both codes run perfectly when they're uploaded individually. But I need them to run in a single sketch. So I combined them in one sketch. That's where my problem is. They're not running smoothly anymore. My mobile app can only turn one LED off then the app will crash. Accessing my Arduino's web server gives me error as well (but before it is really, really working T.T)

Help me, please.
This is my code

    // ========== UIPEthernet library
    #include <Dhcp.h>
    #include <Dns.h>
    #include <ethernet_comp.h>
    #include <UIPClient.h>
    #include <UIPEthernet.h>
    #include <UIPServer.h>
    #include <UIPUdp.h>

    // ========== EtherShield library
    #include "EtherShield.h"
    #include "ETHER_28J60.h"

    // ========== MOBILE
    //static uint8_t mac[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    //static uint8_t ip[4] = {192, 168, 15, 97};
    static uint16_t port = 80;

    ETHER_28J60 e;

    // ========== WEB
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = { 192, 168, 15, 97 };
    byte gateway[] = { 192, 168, 15, 1 };
    byte subnet[] = { 255, 255, 255, 0 };

    String inString = String(35);

    int i;  // Used for looping
    String Room;

    int pin[] = { 0, 2, 3, 4, 5 }; // Lock pin num 0 in array is not used
    int numOfRooms = 4; // Number of rooms
    String value[] = { "OPEN", "OPEN", "OPEN", "OPEN", "OPEN" }; // Startup all rooms are closed

    EthernetServer server(port);
    String data;

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

      // ========== MOBILE
      e.setup(mac, ip, port);

      // ========== WEB
      Ethernet.begin(mac, ip, gateway, subnet);
      server.begin();

      // Set pin mode
      for (int j = 1; j < (numOfRooms + 1); j++)
      {
        pinMode(pin[j], OUTPUT);
      }

      Serial.println("\n[ WEB + MOBILE ]\n");
      Serial.println("Serial READY");
      Serial.println("Ethernet READY");
      Serial.println("Server READY\n");
    }

    void loop()
    {
      webModule();
      mobileAppModule();
    }

    void mobileAppModule()
    {
    char* params;
    if (params = e.serviceRequest())
    {

      //ROOM 311
      if (strcmp(params, "?cmd=1") == 0)
      {
            digitalWrite(pin[1], HIGH);
            Serial.println("ROOM311 is OPEN\n");
      }
      if (strcmp(params, "?cmd=2") == 0)
      {
            digitalWrite(pin[1], LOW);
            Serial.println("ROOM311 is CLOSE\n");
      }

      //ROOM 312
      if (strcmp(params, "?cmd=3") == 0)
      {
            digitalWrite(pin[2], HIGH);
            Serial.println("ROOM312 is OPEN\n");
      }
      if (strcmp(params, "?cmd=4") == 0)
      {
            digitalWrite(pin[2], LOW);
            Serial.println("ROOM312 is CLOSE\n");
      }

      //ROOM 313
      if (strcmp(params, "?cmd=5") == 0)
      {
            digitalWrite(pin[3], HIGH);
            Serial.println("ROOM313 is OPEN\n");
      }
      if (strcmp(params, "?cmd=6") == 0)
      {
            digitalWrite(pin[3], LOW);
            Serial.println("ROOM313 is CLOSE\n");
      }

      //ROOM 314
      if (strcmp(params, "?cmd=7") == 0)
      {
            digitalWrite(pin[4], HIGH);
            Serial.println("ROOM314 is OPEN\n");
      }
      if (strcmp(params, "?cmd=8") == 0)
      {
            digitalWrite(pin[4], LOW);
            Serial.println("ROOM314 is CLOSE\n");
      }

      //
      if (strcmp(params, "?cmd=9") == 0)
      {
            digitalWrite(pin[1], LOW);
            digitalWrite(pin[2], LOW);
            digitalWrite(pin[3], LOW);
            digitalWrite(pin[4], LOW);
            Serial.println("All rooms are now CLOSED\n");
      }

      e.respond();
      }
    }

    void webModule()
    {
         EthernetClient client = server.available();

     if (client)
     {
     // An HTTP request ends with a blank line
     boolean current_line_is_blank = true;

     while (client.connected())
     {
      if (client.available())
      {
        char c = client.read();
        // If users have gotten to the end of the line (received a newline
        // character) and the line is blank, the HTTP request has ended,
        // so users can send a reply

        if (inString.length() < 35)
        {
          inString.concat(c);
        }

        if (c == '\n' && current_line_is_blank)
        {

          // Send a standard HTTP response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          client.println("");

          client.println("<title>CONTROL PANEL</title>");

          client.println("");

          client.println("
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
COMPUTER ENGINEERING LABORATORY
");
          client.println("

");
          client.println("

");
          client.println("
");
          client.println("

CONTROL PANEL

");

          client.println("<form method=get>");

          for (i = 1; i < (numOfRooms + 1) ; i++)
          {
            Room = String("ROOM") + (i + 310);

            if (inString.indexOf(Room + "=OPEN") > 0 || inString.indexOf("All=OPEN") > 0)
            {
              Serial.println("\n" + Room + " is OPEN");
              digitalWrite(pin[i], HIGH);
              value[i] = "CLOSE";
            }
            else if (inString.indexOf(Room + "=CLOSE") > 0 || inString.indexOf("All=CLOSE") > 0)
            {
              Serial.println("\n" + Room + " is CLOSE");
              digitalWrite(pin[i], LOW);
              value[i] = "OPEN";
            }

            client.println("
" + Room + "     <input type='submit' name=" + Room + " value=" + value[i] + " style='height: 50px; width:100px;' />

");
          }

          client.println("

All <input type='submit' name='All' value='OPEN' style='height: 50px; width:100px;' />    <input type='submit' name='All' value='CLOSE' style='height: 50px; width:100px;' />");
          client.println("</form>");

          for (i = 1; i < (numOfRooms + 1); i++)
          {
            if (value[i] == "ON")
            {
              i = i + 310;
              client.println("

Room " + String(i + 310) + " is OPEN
");
            }
            else if (value[i] == "OFF")
            {
              client.println("

Room " + String(i + 310) + " is CLOSE");
            }
          }
          client.println("
");
          client.println("
");
          client.println("");
          break;
        }

        if (c == '\n')
        {
          // we're starting a new line
          current_line_is_blank = true;
        }
        else if (c != '\r')
        {
          // we've gotten a character on the current line
          current_line_is_blank = false;
        }
      }
    }

        // give the web browser time to receive the data
        delay(1);
        inString = "";
        client.stop();
        }
    }

MOBILE means code for Arduino-Android
WEB means the code for Web Server

body:
You can't.

 1. The code has both libraries trying to run on the same port which is not allowed (in fact you couldn't even do that on a computer). You could try setting one to one port and the other to another port, but that might not work because...
 2. These libraries most likely are both expecting to be the only code accessing the hardware and they will step over each other and cause problems. Sharing hardware between different pieces of code is an advanced programming topic not suited for beginners and would involve rewriting significant portions of these libraries.

The best course of action is to either re-implement your app functionality to use the UIPEthernet Library, or re-implement the webpage using the EtherShield library. You should be able to do this because your app interface is supplying parameters (e.g the "?cmd=" part) and the webpage is not. You should be able to set it up so that if it has "?cmd=" in the request, it should perform the command, otherwise it should return the webpage.


message:
Why are some of my GSM modules not taking commands?

I posted a couple weeks ago about having a GSM error. I moved past it and the code seemed to be working on my GSM module (I think a SIMCOM). But then I needed to create some more systems and out of a total of 8 GSM modules, my code and setup only work on two of them - despite the fact that they should be identical and from the same supplier.

The following code (thanks to [this genius post][1]) works without error to send and receive SMS on two of the boards:

    #include <SoftwareSerial.h>
    char inchar; // Will hold the incoming character from the GSM shield
    SoftwareSerial SIM900 = SoftwareSerial(2,3);

    void setup() {
      Serial.begin(19200);
      initializeGSM();
    }

    void initializeGSM() {
      SIM900.begin(19200);
      Serial.println("Turned on");
      SIM900.print("ATEO\r");
      Response();
      SIM900.print("AT\r");
      delay(1000);
      Response();
      SIM900.println("AT+CMGF=1\r");  // set SMS mode to text
      Response();
      delay(1000);
      SIM900.println("AT+CNMI=1,2,0,0,0\r");
      delay(100);
      Response();
      delay(5000);  // give time to log on to network.
      Serial.println("Ready...");
    }

    void Response() {
      int count = 0;
      delay(1000);
      Serial.println(SIM900.available());
      while(1) {
        if(SIM900.available()) {
          char data =SIM900.read();
          if(data == 'K'){Serial.println("OK");break;}
          if(data == 'R'){Serial.println("GSM Not Working");break;}
        }
        count++;
        if(count == 100){Serial.println("GSM not Found");break;}
      }
    }

    void loop() {
      RecSMS();
      delay(2000);
    }

    void RecSMS(){...}

So again, the above code works to set up the module on 2 modules. On the other 6, it simply hangs during the `Response()` call. `SIM900.available()` returns 0 and then says "GSM Not Found." So I tried to initialize the TX pin during setup as:

    digitalWrite(2, LOW);

Which then gives me a promising `SIM900.available()` value of about 63, which corresponds to what a confirmation would be. However, when I print the "data" variable containing the byte read off the GSM module/SIM card, I get a couple bits of garbage like the following output:

[![Garbage output from printing the data char during the Response function][2]][2]

Has anyone experienced this problem and knows a way to properly initialize the GSM module?

  [1]: http://www.theengineeringprojects.com/2015/02/receive-sms-commands-using-sim900-arduino.html
  [2]: https://i.stack.imgur.com/iWlsl.png

body:
I am owner of this blog whose link you shared, so first of all, I am felling happy that you got something out of it. Now secondly, this code you got from my post is incomplete.

You need to buy that one in order to get the complete code. The code I designed is using AT commands but the above code which you have mixed with your own code is using the Arduino library that's why it's not giving the correct results.

So, either use the complete code from my website or use the Arduino library code only because it has the commands for checking the response, you don't need to use my code to get the response.


message:
Passing the input from one pin to another as output without polling?

I am trying to pass the input from one pin to another pin as output. Effectively I want to create a blind passthrough. The end goal is to connect two Arduinos and a series of test points together like the diagram below. I want Arduino B to shuffle which test points are connected to which pins on Arduino A on startup.

    +-----------+       +-----------+     +-------------+
    |           |       |           |     |             |
    | Arduino A <-------> Arduino B <-----> Test Points |
    |           |       |           |     |             |
    +-----------+       +-----------+     +-------------+

I figure one way to do this is to poll the input pins in the loop() and then change the output pins accordingly but I would prefer if the voltage changes just passed right through without it affecting timing.

**Update:**
For some clarification:

 - All signaling is digital
 - I'm looking to "route" around 10-12 test points to Arduino A ideally but 6 at a minimum

body: No Arduino is capable of doing this. You need to be looking at a crossbar/crosspoint/matrix switch IC instead.


body:
You could use an analog multiplexer such as the 74HC4051 (8 channels) or the 74HC4067 (16 channels) like this:

[![74HC4051 multiplexer][1]][1]

Arduino B could alter the multiplex selector (A/B/C) pins to route the signal from the test points to a specific pin on Arduino A. If you are wanting to see the result of the signal on a different pin then a second multiplexer would be required (ie. one to send data to a pin, the second to see the result on a different pin).

I have a post about the [74HC4051 multiplexer / demultiplexer](http://www.gammon.com.au/forum/?id=11976) which gives more details about using it.

When I tested it I found only about a 5 ns delay in timing:

[![Multiplexer timing][2]][2]

Ignacio's answer about a crossbar switch sounds like a more elaborate form of multiplexer. Personally I haven't used one of them.

  [1]: https://i.stack.imgur.com/FmwtJ.png
  [2]: https://i.stack.imgur.com/CShlX.png


body:
You can reduce latency by using interrupts to detect input changes instead of polling in loop(), if you're dead set on using an Arduino instead of adding switching hardware (as suggested in other answers).

See [attachInterrupt()](http://www.arduino.cc/en/Reference/AttachInterrupt) for details, and beware that different Arduino models differ greatly in how many pins support interrupts.

Alternately, you can speed up the polling approach by using [direct port access](http://www.arduino.cc/en/Reference/PortManipulation) (e.g., PORTB and PORTD registers) instead of the simpler Arduino read and write functions.  This will bypass some wrapper code and also let you manipulate multiple pins in parallel.


body: Because this is digital I would like to add a third option in addition to Ignacio's and Nick's great suggestions. Use a logic device such as an FPGA or CPLD. This will require some extra knowledge and set up to get it working, but it is well suited for the functionality you are looking for.


message:
Why does my LCD display random characters?

I've been struggling with my LCD for hours, and after solving more different issues than I can remember, I'm out of ideas for this one.

My LCD is showing random characters, see the picture below (the last character blinks, some characters change and over time there are slowly more and more characters). I'm starting to wonder if the LCD I chose has a driver compatible with the LiquidCrystal library, what do you think? If so what can I do to avoid buying another one?

[![enter image description here][1]][1]

Here is the code:

<!-- language: c -->

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    //RS EN D4 D5 D6 D7
    LiquidCrystal lcd(2, 3, 4, 5, A2, A3);
    //RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer

    void setup() {
      Serial.begin(9600);
      Serial.println("Starting");
      lcd.begin(16, 2);
    }

    void loop() {
      lcd.setCursor(0, 1);
      lcd.print(millis() / 1000);
      Serial.println("Printing");
      delay(1000);
    }

I'm using this [Arduino][2] and this [LCD][3]. Note that I'm using pins 10,11,12,13 for a SD (which works) and 6 7 8 for a MAX232 (which is disabled).

Any ideas?

  [1]: https://i.stack.imgur.com/DYED4.jpg
  [2]: http://hobbycomponents.com/boards/140-arduino-compatible-5v-pro-mini-?search_query=pro mini&results=53
  [3]: http://uk.farnell.com/midas/mc21605h6w-sptly/lcd-2x16-stn-led-b-l-blk-on-y/dp/2342641

body:
It could be because "millis()/1000" generates a "number", and not the "string" (or "char"). Try to add ",DEC" in your lcd.print(), something like "millis()/1000,DEC" to convert it to "decimal". Generally, it depends on the library, how they implement this function.

Good luck,

Mike


message:
Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest)

I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128.  When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward.

I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.

Here's some explanations for implementing PID in Arduino.
[http://playground.arduino.cc/Code/PIDLibraryConstructor][1]

For instance the joystick readings go from 140, 137, 131, [128], 128, 128, 133, 139, 131, [128], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, [] in the example above.

If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.

    void loop()
    {

      int pwmSpeed;

      int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

      Input = encoder0Pos;

      if (Y_axis == 128)
      {

        Setpoint = encoder0Pos;
        myPID.Compute();
        analogWrite(pwm, Output);

      }

      else if (Y_axis > 128)
      {
        pwmSpeed = Y_axis;
        digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
        analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
      }
      else
      {
        pwmSpeed = abs(Y_axis-255);
        digitalWrite(dir, LOW);
        analogWrite(pwm, pwmSpeed);

      }

    }

Thanks.

//New edited code is shown below:

What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.

If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint.

However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.

    global g_detect128 = false;

    void setup()
        {
    //any code here
        }

    void loop()
    {

      int pwmSpeed;
      int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

      Input = encoder0Pos;

     if (!g_detect128 && Y_axis == 128)
        {
        Setpoint = encoder0Pos;
        g_detect128 = true;
        }

      if (Y_axis == 128)
      {

        myPID.Compute();
        analogWrite(pwm, Output);

      }

      else if (Y_axis > 128)
      {
        pwmSpeed = Y_axis;
        digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
        analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
      }
      else
      {
        pwmSpeed = abs(Y_axis-255);
        digitalWrite(dir, LOW);
        analogWrite(pwm, pwmSpeed);

      }

     if(Y_axis != 128)
        {
        g_detect128 = false;
        }

    }

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

body:
If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:

    boolean g_bSeen128 = false;

    void setup()
    {
        // ... whatever
    }

    void loop()
    {
        // ... your existing code

        // catch first time we see 128
        if (!g_bSeen128 && Y_axis == 128)
        {
            // ... do whatever you need here. e.g.
            Setpoint = encoder0Pos;
            myPID.Compute();
            analogWrite(pwm, Output);

            // stop the event being caught next time
            g_bSeen128 = true;
        }

        // from comments below - to just ignore consecutive 128's, add this:
        if (Y_axis != 128) g_bSeen128 = false;

        // ... your existing code

    }

If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:

    int g_nLastInput = -1;

    void setup()
    {
        // ... whatever
    }

    void loop()
    {
        // get input
        int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

        // if input has changed ...
        if (Y_axis != g_nLastInput)
        {
            // ... save latest input
            g_nLastInput = Y_axis;

            // now process the change, e.g.
            if (Y_axis == 128)
            {
                // ... do something special for 128
            }
            else
            {
                // ... do something else for other inputs
            }
        }
    }

I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.

If that's correct, an alternative way of coding your original logic might be like this:

    void loop()
    {
        // get input
        int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

        Input = encoder0Pos;

        // if input has changed ...
        if (Y_axis != g_nLastInput)
        {
            // ... save latest input
            g_nLastInput = Y_axis;

            // now process the change
            int nDelta = Y_axis - 128;

            if (nDelta == 0)
            {
                // i.e. Y_axis is 128
                Setpoint = encoder0Pos;
                myPID.Compute();
                analogWrite(pwm, Output);
            }
            else
            {
                // choose direction
                digitalWrite(dir, (nDelta > 0) ? HIGH : LOW);

                // set PWM speed scaled to 0..255
                analogWrite(pwm, abs(nDelta) * 2);
            }
        }
    }


message:
Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.”

I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."

Please check and correct me if I am wrong anywhere.

I am using below code and and wiring diagram is

[![enter image description here][1]][1]

My Code:

    //#include <SoftwareSerial.h>
       //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
       #define SSID "SopraSteria"
       #define PASS "1234567890"
       #define DST_IP "220.181.111.85" //baidu.com
       //SoftwareSerial dbgSerial(10, 11); // RX, TX
       void setup()
       {
         // Open serial communications and wait for port to open:
         //serial 2 is to esp8266
         Serial2.begin(115200);//9600 (mine), 57600, 115200
         Serial2.setTimeout(2000);

         //serial 0 is to usb
         Serial.begin(115200);

         while(!Serial);
         while(!Serial2);

         //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
         //dbgSerial.println("ESP8266 Demo");
         Serial.println("ESP8266 Demo on Mega2560");

        while(Serial2.available()>0)
        Serial2.read();

         delay(1000);
           //test if the module is ready
         Serial2.println("AT+RST");
         //delay(1000);
         //delay(1000);
         Serial.println("Resetting module");
         Serial2.flush();
         //Serial.println(Serial2.read());
         //if(Serial2.find("ready"))
         if(Serial2.find("Ready")||Serial2.find("ready"))
         {
           //dbgSerial.println("Module is ready");
           Serial.println("Module is ready");
         }
         else
         {
           //dbgSerial.println("Module have no response.");
           Serial.println("Module have no response.");
           //while(1);
         }
         delay(1000);
         //connect to the wifi
         boolean connected=false;
         for(int i=0;i<5;i++)
         {
           if(connectWiFi())
           {
             connected = true;
             break;
           }
         }
         if (!connected){
          //while(1);
          Serial.println("Not Connected.");
         }
         delay(1000);
         //print the ip addr

       Serial2.println("AT+CIFSR");
         Serial.println("ip address:");
         while (Serial2.available())
         Serial.write(Serial2.read());

         //set the single connection mode
         Serial2.println("AT+CIPMUX=0");
       }
       void loop()
       {
        //connectWiFi();
         String cmd = "AT+CIPSTART=\"TCP\",\"";
         cmd += DST_IP;
         cmd += "\",80";
         Serial2.println(cmd);
         Serial.println(cmd);
         Serial.println(cmd);
         if(Serial2.find("Error")) return;
         cmd = "GET / HTTP/1.0\r\n\r\n";
         Serial2.print("AT+CIPSEND=");
         Serial2.println(cmd.length());
         if(Serial2.find(">"))
         {
           //dbgSerial.print(">");
           Serial.print(">");
           }else
           {
             Serial2.println("AT+CIPCLOSE");
             //dbgSerial.println("connect timeout");
             Serial.println("connect timeout");
             delay(1000);
             return;
           }
           Serial2.print(cmd);
           delay(2000);
           //Serial.find("+IPD");
           while (Serial2.available())
           {
             char c = Serial2.read();
             //dbgSerial.write(c);
             Serial.write(c);
             //if(c=='\r') dbgSerial.print('\n');
             if(c=='\r') Serial.print('\n');
           }
           //dbgSerial.println("====");
           Serial.println("====");
           delay(1000);
         }
         boolean connectWiFi()
         {
           Serial2.println("AT+CWMODE=1");
           String cmd="AT+CWJAP=\"";
           cmd+=SSID;
           cmd+="\",\"";
           cmd+=PASS;
           cmd+="\"";
           //dbgSerial.println(cmd);
           Serial2.println(cmd);
           Serial.println(cmd);
           delay(2000);
           if(Serial2.find("OK"))
           {
             //dbgSerial.println("OK, Connected to WiFi.");
             Serial.println("OK, Connected to WiFi.");
             return true;
             }else
             {
               //dbgSerial.println("Can not connect to the WiFi.");
               Serial.println("Can not connect to the WiFi.");
               return false;
             }
           }

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

body:
I took your code as a starting point and got it to work with some small modifications. I am providing my version below for your review. I had to add a bunch of delays. I am also communicating with the ESP8266 at 19200 baud.

I have not optimized the timing yet but I was able to run this code for 24 hours straight with no issues. I am using Pins 6 and 7 on the Arduino for COMM to the ESP8266.

    #include <SoftwareSerial.h>
    #define SSID "YOURSSID"
    #define PASS "YOURPW"
    #define DST_IP "220.181.111.85"

    SoftwareSerial Serial2(6, 7); // RX, TX

    void setup() {

    // Open serial communications w ESP8266
    Serial2.begin(19200);
    Serial2.setTimeout(5000);

    // serial 0 is to usb
    Serial.begin(115200);
    while(!Serial);
    while(!Serial2);

    Serial.println("ESP8266 Demo on Mega2560");

    while (Serial2.available() > 0)
    Serial2.read();
    delay(1000);
    while (Serial2.available() > 0)
    Serial2.read();

    //test if the module is ready
    Serial.println("RESETTING ESP8266 WIFI CHIP");
    Serial2.write("AT+RST\r\n");
    delay(2500);
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());

    delay(2500);
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());
    Serial.println("");

    //  connect to the wifi
    boolean connected=false;
    for(int i=0;i<5;i++) {
    if(connectWiFi())
    {
    connected = true;
    break;
    }
    }

    if (!connected){
    Serial.println("Not Connected.");
    }

    Serial2.println("AT+CIFSR");
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());

    //  set the single connection mode
    Serial2.println("AT+CIPMUX=0");
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());
    }

    void loop() {

    String cmd = "AT+CIPSTART=\"TCP\",\"";
    cmd += DST_IP;
    cmd += "\",80";
    Serial2.println(cmd);
    Serial.println(cmd);
    delay(5000);

    if(Serial2.find("Error")) return;

    cmd="GET / HTTP/1.0\r\n\r\n";
    Serial2.print("AT+CIPSEND=");
    Serial2.println(cmd.length());
    delay(2000);

    if(Serial2.find(">"))      {
    Serial.print(">");
    }
    else {
    Serial2.println("AT+CIPCLOSE");
    Serial.println("connect timeout");
    delay(2000);
    return;
    }
    Serial2.print(cmd);
    delay(2500);

    while (Serial2.available()) {
    char c = Serial2.read();
    Serial.write(c);;
    if(c=='\r') Serial.print('\n');
    delay(5);
    }

    Serial.println("");
    Serial.println("====");
    delay(2000);
    }

    boolean connectWiFi() {

    String cmd;
    int iIP;

    iIP = 0;
    Serial2.println("AT+CWMODE=1");
    delay(5000);
    while (Serial2.available())
    Serial.write(Serial2.read());

    cmd="AT+CWJAP=\"";
    cmd+=SSID;
    cmd+="\",\"";
    cmd+=PASS;
    cmd+="\"";

    Serial2.println(cmd);

    delay(2000);
    Serial.println("Line 1");
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());

    delay(2000);
    Serial.println("Line 2");
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());
    if (Serial2.find("OK")) {
    Serial.println("WIFI OK was received!");
    iIP = 1;
    }

    if( iIP == 1 ) {
    Serial.println("OK, Connected to WiFi.");
    return true;
    }
    else  {
    Serial.println("Can not connect to the WiFi.");
    return false;
    }

    }


body:
Your transmitter and receiver pins need to be crossed, rx->tx and tx->rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH_PD. I use one 10K pullup for both.

Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.

*Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).*

You can confirm your connections and baud rate with:

`EspSerial.println("AT");`

You should receive `OK' in reply.


message:
How to count the time until the next day of the week?

I wants to do in Arduino countdown that shows how many days, hours and minutes remaining to Friday 12:00.
In my program I used a function in php `strtotime('next friday')` which thus could calculate differential timestamp and show how much time is left until Friday 12:00.

Is there a function `strtotime('next friday')` in Arduino?
I have RTC which gives me just the current date and time, but does not show the current day of the week.

**EDIT:
I have a solution**

We have day of week. We multiplied by 86400.

We have an hour. We multiply by 3600.

We have a minute. We multiplied by 60.

Add everything.

Subtract this from 604800.

`nextFriday  = 604800-((dayofweek * 86400)+(now.hour()*3600)+(now.minute()*60)+now.second());`

Important, Friday is the number of the week "0". Friday = 0; Saturday = 1; etc...

body:
The key to working with time is to have a known "base" time to calculate everything relative to.  This is called the *epoch*.  Different systems use different epochs, and each has advantages and disadvantages.

I generally use the UNIX epoch in my programming (chiefly because I am a UNIX nut), which is the first of January, 1970 (01/01/1970).  This is year, month, day, hour, minute and second 0.

From that you can then calculate the number of seconds between the epoch and any other time you choose as long as it is later than the epoch.

To calculate the day of the week for any given date you first need to know the day of the week for the epoch (for UNIX that's a Thursday) then work out how many days there are between the epoch and the target time.

Calculating real times in terms of seconds can be somewhat tricky due to leap years and daylight savings, but there are plenty of algorithms in the public domain, and many RTC libraries include functions to convert to/from epoch times.

For instance, the [Arduino Time Library](http://playground.arduino.cc/code/time) has functions to calculate weekdays, and to convert to "time_t" format (seconds since epoch) which can be used to work out differences in times.  For instance, if you know that it's Tuesday and you want next Friday then you know that Friday is 3 days in the future - so you can get the current time in seconds from the epoch then add to that 3 days' worth of seconds (3 × 60 × 60 × 24) to that time to get the same time of day next Friday.


body:
<!-- language-all: lang-C++ -->
There are generic examples, e.g. [Determination of the day of the week - Wikipedia](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week).

> In the C language expressions below, **y**, **m** and **d** are, respectively, integer variables representing the year (e.g., 1988), month (1-12) and day of the month (1-31).

            (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7

Also see [StackOverflow - C Program to find day of week given date](https://stackoverflow.com/questions/6054016/c-program-to-find-day-of-week-given-date).


message:
ACS712 inacurrate reading. Wild jumping

I'm trying to use my 30A ACS712 on my OSD (it has ATMEGA16L).

But it is very unstable, 0 amps goes from 450 to 445, but that isn't that bad, but when I put 10A of current through it jumps from 440 to 380.

I already searched on google and tried to add filter cap between acc and gnd, but it didn't help and acs712 and osd have different power supply than the load.

Any help is welcome.

body:
This is not a simple chip to use.  These parts of the data sheet may help you understand what is happening.  It is internally an analog device and needs clean power.  I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you.  Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.

"Quiescent output voltage (VIOUT(Q)). The output of the device
when the primary current is zero. For a unipolar supply voltage,
it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into
VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the
resolution of the Allegro linear IC quiescent voltage trim and
thermal drift.

Electrical offset voltage (VOE). The deviation of the device output
from its ideal quiescent value of VCC / 2 due to nonmagnetic
causes. To convert this voltage to amperes, divide by the device
sensitivity, Sens.

Accuracy (ETOT). The accuracy represents the maximum deviation
of the actual output from its ideal value. This is also known
as the total output error. The accuracy is illustrated graphically in
the output voltage versus current chart at right."

I realize this does not answer your question but it does give you a good starting point to resolve your problem.  Hopefully you or a buddy has some analog experience, that will help a lot.  Oh Yes clean power supplies are imperative for this to work.


message:
Encoding an entire Byte for File Reading

I'm using an Arduino Yun to read from a data file, which will then populate a data structure. The `file.read()` function "*returns: The next byte (or character), or -1 if none is available.*"

This functionality is identical to the `SD.read()` function in the SD card library.

The data file will never have any value that exceeds 1 byte with all numbers in the range 0-255. If I print these numbers as a long string in the data file, each character is read as a byte. So I need to call `file.read()` 3 times to read in a single 0-255 value. And then do some additional processing to construct the final 8-bit value for storing.

I could reduce this to 2 calls by printing the Hex code in the data file, but this isn't much of an improvement.

**Is there a way to encode a full byte in a single character?**

**Effectively , is there a particular way I can format my data file so that I can read in an `8-bit unsigned` value in a single call to `file.read()`?**

body:
This is a fragment (untested) of how you can do it:

    char datafile[512];
    int ch;
    int index = 0;

    while ((ch = file.read()) != -1) {
      datafile[i] = (char)ch;
      if (++i == 512)
        break;
    }


body:
There's two parts to what you want to do, writing the file in the right form, and reading that format file.

The format of file is known as *raw binary*. Every byte in the file can store a separate value between 0 and 255, or between -128 and 127, dependin on how you interpret the data.  At the end of the day, every byte in a file is just a collection of 8 bits yielding 2^8 = 256 combinations. What those combinations actually mean is more of a human thing than a machine thing.

We, as humans, have decided upon three main representations of those bytes: *unsigned* numbers from 0 to 255, *signed* numbers from -128 to 127 (lookup two's complement) and finally ASCII characters.

ASCII characters are more of a lookup table placed over one of the other two representations. Some systems use unsigned bytes and some signed bytes for the basis of that lookup tabe.

Writing text into the file results in looking up the corresponding byte values for each character in that text and placing those values in the file. When you read the file the reverse is done - the byte values are read and you look them up in the ASCII table to find the corresponding letters.

To store just numbers between 0 and 255 it is far more efficient to bypass that ASCII table and store the values directly as bytes. How you do that is entirely dependent on what language you are writing your software in. Since you haven't mentioned what that language is I can't advise you on that front' only give some examples in languages I know.

Such as in C you would store your data in an array of *unsigned char* or *uint8_t*. You then use the `write()` function to write raw data to the file.

In Perl you might use the `pack()` function to store your values as bytes in a string then write that string to a file.

When reading the data you are presented with a raw value. That may be given to you as a signed or an unsigned value depending on the underlying system. I don't know what the yun is off hand. Converting from whatever is handed to you by thr `file.read()` function to what you expect it to be though is a very simple matter, and is called *casting*.

    int in = file.read();
    uint8_t bval = (uint8_t)in;

The bit in brackets is the *cast* which converts the value in the integer *in* into a uint8_t (Unsigned INTeger 8-bit Type) which corresponds to whatever you wrote as an unsigned char or uint8_t at the other end.


message:
Uno as a composite USB HID keyboard

I'm looking to create a USB device that would  be basically a HID keyboard. I am able to do that with Uno. I flash new firmware with a HID keyboard descriptor and on the arduino side I loop and check for button presses. Based on butotn presses I send the report.

What I would like to add to this is option to send some data from a PC and based on that data do something (like turn an LED on.)

Here is an example:

    loop() {
      check_and_send_buttons();
      uint8_t inputByte = get_input(); //new
      handle_input(inputByte); //new
    }

I'm on Linux and I tried sending some data via hidrawX but that did not work out.
Any ideas?

I'm willing to also write new device driver for Linux if needed.

body:
On UNO R3 the HID protocol is handled by the secondary AVR present on the board. Which is the one talking to the PC. So what you should modify is the code implementing the USB protocol on the secondary AVR.

The main (328p) AVR interacts with it through the serial port.

You do not need to alter the Linux driver, since it already supports the driving of the usual LEDs (CAPS, Num Lock, Scroll Lock), if these are enough for you.

So, to recap:

 1) enhance the HID implementation to understand LED status commands coming from the PC

 2) report such changes over serial

 3) on the primary AVR, monitor for such messages coming over serial port from the secondary AVR and use them to drive the LEDs.


message:
Verify RGB Led Cube equipment

I'm preparing this kit on eBay to create the following instructable - http://www.instructables.com/id/4x4x4-RGB-LED-Cube/
But I have doubts about 0.1uF and 22pF capacitors since the once on eBay are 50v. Also MOSFETs - instructable uses IRF9531 but the ones I found on eBay are IRF9540N.
Is the equipment I added on eBay compatible with instructable?

body:
Capacitor ratings don't really matter in your case, as you are using only 5 volt. Only their values (F) do.

Though the crystal you selected has an indication it needs 20pF load capacitors, not 22pF. 22pF is probably still fine. (Also note the ±20% accuracy, so between 17.6 and 26.4pF)

The IRF9531 and IRF9540N have the same pinout. They are also pretty similar in specs. The IRF9540N is slightly better even.

Note that the ATMega328p doesn't have the bootloader pre-installed. It's not that hard to do yourself though.

The EEPROM you selected is an SMD version. Kind of hard to work with if you are still a beginner. Better use a [DIP version](http://www.ebay.com/itm/2PCS-AT24C256-10PU-2-7-DIP-8-24C256-PU27-2-Wire-Serial-EEPROM-GOOD-QUALIITY-/311362511891?hash=item487ea6e413) instead (that one is a bit more expensive, but 4 times the size)

I'd suggest you add an [USB to Serials Adapter](http://www.ebay.com/itm/FT232RL-FTDI-Serials-Adapter-Module-Mini-Port-f-Arduino-USB-TTL-3-3V-5-5V-/311406775045?hash=item48814a4b05) to the list, so you don't need the Arduino Uno every time you want to reprogram it, and use the Uno for something more useful.


body:
For a crystal with 20pF load capacitance you need 40pF capacitors.

The formula used is:

* Cx1 = Cx2 = 2(CL - Cpara)

CL is 20pF and Cpara is the parasitic capacitance of the circuitry involved. Under most amateur circumstances that can be ignored.


message:
Can both the 3.3V and 5V pins on the Arduino be used at once for power?

I'm supplying power to Arduino via PC USB.

body:
Yes.

Here's a block diagram of how the Arduino power is arranged:

[![enter image description here][1]][1]

As you can see the USB power is fed through a FET (P-channel MOSFET) to isolate it when there is external power applied (as decided by the comparator *COMP*).  External power is fed through a 5V regulator and is fed to the same point as the USB power.  Thus you get the same 5V at the same point regardless of if you have USB or Barrel Jack power.  From there the 5V (wherever it comes from) is fed into a 3.3V regulator.  The 5V pin on the Arduino is connected directly to the 5V point where the USB and the 5V regulated input are connected. The 3.3V pin is connected directly to the output of the 3.3V regulator.

So no matter what input power arrangement you use - barrel jack, USB power, battery connected to the V IN pin (not shown, but connects to the barrel jack), or regulated 5V into the 5V pin, you get access to the same 5V and 3.3V power on the 5V and 3.3V power pins.

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


message:
ESP8266 failure to connect to router

I'm trying to get a ESP8266 board with 2x4 pins to work. I'm connecting it to an Olimexino 32u4 (Leonardo-compatible), configured to use 3.3V. This simple snippet I use to transfer everything to the PC (CH_PD is connected to D8, /RST to D9):

    void setup() {
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
      delay(2000);
      // initialize both serial ports:
      Serial.begin(9600);
      Serial1.begin(115200);
      delay(10000);
      digitalWrite(9, HIGH);
      digitalWrite(8, HIGH);
    }

    void loop() {
      // read from port 1, send to port 0:
      if (Serial1.available()) {
        int inByte = Serial1.read();
        Serial.write(inByte);
      }

      // read from port 0, send to port 1:
      if (Serial.available()) {
        int inByte = Serial.read();
        Serial1.write(inByte);
      }
    }

When launching, I see following output:

    <"random" bytes>
    Ai-Thinker Technology Co. Ltd.

    invalid

Performing a reset shows more:

    AT+RST

    OK

     ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x40100000, len 1396, room 16
    tail 4
    chksum 0x89
    load 0x3ffe8000, len 776, room 4
    tail 4
    chksum 0xe8
    load 0x3ffe8308, len 540, room 4
    tail 8
    chksum 0xc0
    csum 0xc0

    2nd boot version : 1.4(b1)
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size & Map: 8Mbit(512KB+512KB)
    jump to run user1 @ 1000

    ŒÂÕ�MEM CHECK FAIL!!!
    äsl�‚rô
    Ai-Thinker Technology Co. Ltd.

    invalid

The mode is set to station:

    AT+CWMODE?

    +CWMODE:1

    OK

Listing the access points works fine:

    AT+CWLAP

    +CWLAP:(3,"ap-1",-91,"01:23:45:67:89:ab",1)
    +CWLAP:(3,"ap-2",-88,"cd:ef:01:23:45:67",2)
    +CWLAP:(3,"ap-3",-74,"89:ab:cd:ef:01:23",11)

    OK

But logging in to my Fritzbox router fails (WPA2):

    AT+CWJAP="ap-2","mypassword"
    WIFI CONNECTED
    +CWJAP:1

    FAIL
    WIFI DISCONNECT

First I thought the reason is the low signal, but even moving directly beside the Fritzbox shows the same result (though with higher signal value in `AT+CWLAP`).

I've tried nearly everything, e.g. `AT+CWMODE=3`, `AT+RST`, `AT+RESTORE`). Nothing changes. When using a wrong password, I'm getting no "WIFI CONNECTED" messages at all.

Could it be a power problem (that the Olimexino can't provide up to 200mA at the 3.3V line?

Connecting from my smartphone to the ESP8266 in one of its access point modes (2 or 3) works fine. If there were power problems, wouldn't then the access point mode fails as well?

body:
It looks like the ESP8266 could not obtain the IP address over DHCP (it was enabled in the ESP8266, but the Fritzbox was configured for a limited range only .200 - .209). When setting the IP explicitly:

    AT+CIPSTA="192.168.92.82","192.168.92.254","255.255.255.0"

    OK
and then trying to connect, it worked:

    AT+CWJAP="ap-2","mypassword"
    WIFI CONNECTED
    WIFI GOT IP

    OK
Pinging also works now: :)

    AT+PING="arduino.stackexchange.com"

    +39

    OK


body:
In my case when I try to connect to my router, I get the following output:

    AT+CWJAP="myssid","mypassword"
    WIFI CONNECTED
    +CWJAP:1

    FAIL
    WIFI DISCONNECT

The reason is that the ESP8266 I have is setup with DHCP disabled by default. To enable it you can try the following:

    AT+CWDHCP=1,1

If that works, you will get this message:

    OK
    WIFI GOT IP


body: I had many headaches related with this CWJAP:1 error and few others like Ok in return for change IP number command but actually the IP number still the same as before !!! The solution: The AT+RESTORE command to bring the ESP8266 back to the factory defaults... When not logical things happens for unknow reason probably is due to some internal register has dirty values inside and only a AT+RESTORE can normalize them...


body:
I had this same problem and spent an embarrassing number of hours trying to fix it before coming across this post.

I did a `AT+RESTORE` followed by `AT+UART_DEF=9600,8,1,0,0` since, as expected, my module expected communication on 115200 after the restore.

Then... as if by magic, everything works now...

    AT+CWJAP="ssis","pwd"
    WIFI CONNECTED
    WIFI GOT IP

    !

I really don't know what was wrong that the `RESTORE` fixed... I must have screwed up the module by experimenting with various commands somehow.


message:
Connect my arduino with ethernet shield to new router

I just changed the router for my webserver and I'm having trouble to connect my arduino with the LAN.
I'm using a router which uses Zhone technology, and I've been working with NetGear for a while without problems.
The procedure I've done so far is:

 1. Connect the arduino with the ethernet and run the DhcpAdressPrinter example
 2. Once I got the adress, in my case 192.168.1.125 I run the WebServer example, using the IP assigned by the DHCP.
 3. In the serial monitor, I see it has started the program with the correct IP.

Problem: WHEN PUTTING THE IP INTO A BROWSER, NOTHING CHARGES

More info:

 - In my router page (192.168.1.1) I can see that each ethernet port has
   assigned a MAC adress, I don't really understand why.
 - I also can see that the arduino has been successfully added to the DHCP with the IP assigned and the MAC adress that I wrote on the code
 - Finally, add that I've read in another website that sometimes the problem is due to the fact that the router just let the access to some specific MAC adress, but i'm not sure.

Any help will be apreciated! Thanks!

body:
Finally, I was capable to solve it by just creating a port forwarding with the IP that was assigned by the DCHP.
It looks like my router for security reasons don't let you comunicate with other devices within the lan, so it's necessary to open a port and access the device through it!


message:
safety for power electronics

I'm quite new to Arduino. I have build a number of projects successfully, like potentiometers, serial communication, DAC, sensors, motors etc.

I use a laptop to power my Arduino project and Atmel Studio to program and upload to the Arduino. I have created a project with 2 motors and I have successfully used a separate power supply (a transformer) to power the motors.

Now I want to continue my experiments but I'm afraid of the possibility to cause any problem to my laptop.

When I made the circuit with the 2 power sources (laptop for the Arduino, transformer for the motors) I had to connect the 2 grounds together.

So my question is that:

*Can someone explain me or point me to some information about power electronics so to be absolutely sure that I won't cause any problem to the laptop?*

Should I use optocouplers, or diodes etc? Is there a way to avoid the 2 grounds connection? What is the reason to connect both grounds (of the 2 power supplies) in the first place?

body:
Connecting the grounds together is required since without that there would be no circuit for the current to flow through.  Take this simple block diagram for instance:

[![enter image description here][1]][1]

In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power).  The communication between the Arduino and the Device can't happen because there is no circuit (red).

In the bottom diagram the red circuit has been completed by joining the grounds together.  That means that the current has some way to get back to where it came from (which current always *has* to do) so the signals you send can actually get through.

To avoid having to connect the grounds together you need something called *Galvanic Isolation*.  This involves using some method that is not electricity to connect the two circuits together.  That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay.  In that situation you have an arrangement like this:

[![enter image description here][2]][2]

The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.

Galvanic isolation is highly desirable when:

* You are controlling a different *type* of current (e.g., using DC to switch AC)
* You are working with voltages considerably higher than your drive voltage (e.g., switching mains)
* You have different ground potentials (e.g., you have a long distance connection)

  [1]: https://i.stack.imgur.com/0uyFv.png
  [2]: https://i.stack.imgur.com/G9hvY.png


message:
Connect Arduino to MySQL database online problem

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

I'm trying to connect Arduino with MySQL database on my online server.

I manage my project to work on WampServer locally on localhost, but when I try to move everything online I have problem... on the serial monitor I get the message that the server is connected and my sensor readings, but I can't put them in to my database on my online sever.

Here is my code:

---

**dbconnect.php**

    <?php
    $MyUsername = "*******";  // enter your username for mysql
    $MyPassword = "*******%";  // enter your password for mysql
    $MyHostname = "*************";      // this is usually "localhost" unless your database resides on a different server

    $dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
    $selected = mysql_select_db("tanjamayaarduino",$dbh);
    ?>

---

**add_data.php**

    <?php
        // Connect to MySQL
        include("dbconnect.php");

        // Prepare the SQL statement
        $SQL = "INSERT INTO tanjamayaarduino.temperature (sensor ,celsius, light, moisture1, moisture2) VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."','".$_GET["light"]."','".$_GET["moisture1"]."','".$_GET["moisture2"]."')";

        // Execute SQL statement
        mysql_query($SQL);

        // Go to the review_data.php (optional)
        header("Location: review_data.php");
    ?>

---

**Arduino code**

    #include<Ethernet.h>
    #include<SPI.h>
    const int temperaturePin = A3;    //LM35 Temperature sensor
    const int lightPin = A2;          //LDR photoresistor sensor
    const int moisture1Pin = A4;          //Moisture1 sensor
    const int moisture2Pin = A5;          //Moisture2 sensor

    // **** ETHERNET SETTING ****
    // Arduino Uno pins: 10 = CS, 11 = MOSI, 12 = MISO, 13 = SCK
    // Ethernet MAC address - must be unique on your network - MAC Reads T4A001 in hex (unique in your network)
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x3A, 0xDC };
    // For the rest we use DHCP (IP address and such)
    IPAddress ip(192, 168, 2, 121);
    EthernetClient client;
    //IPAddress server(192, 168, 2, 100); // IP Adres (or name) of server to dump data to
    // IP Adres (or name) of server to dump data to  (godaddy baza server 37.148.204.140) (User: tanjamayaarduino@188.121.42.33) (goddady glavna adresa na hostingot 188.121.46.1)
    //IPAddress server(188, 121, 46, 1);
    char server[] = "188.121.46.1";

    int  interval = 5000; // Wait between dumps

    void setup() {

      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }

      Serial.println("Tweaking4All.com - Temperature Drone - v2.0");
      Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
      Serial.print("IP Address        : ");
      Serial.println(Ethernet.localIP());
      Serial.print("Subnet Mask       : ");
      Serial.println(Ethernet.subnetMask());
      Serial.print("Default Gateway IP: ");
      Serial.println(Ethernet.gatewayIP());
      Serial.print("DNS Server IP     : ");
      Serial.println(Ethernet.dnsServerIP());
    }

    void loop() {
      // if you get a connection, report back via serial:
      if (client.connect(server, 80)==1) {
        float tem = getTemp();
        Serial.println( tem );
        float lig = getLight();
        Serial.println( lig );
        float mois1 = getMoisture1();
        Serial.println( mois1 );
        float mois2 = getMoisture2();
        Serial.println( mois2 );

        Serial.println("-> Connected");
        if (client.connected()) {
          // Make a HTTP request:
          client.print( "GET /advertacs/test/arproekt/add_data.php?");
          Serial.println("-> add_data");
          client.print("serial=");
          client.print( "TempSensor" );
          client.print("&&");
          client.print("temperature=");
          client.print( tem);
          Serial.println("-> add_temp");
          client.print("&&");
          client.print("light=");
          client.print( lig);
          Serial.println("-> add_light");
          client.print("&&");
          client.print("moisture1=");
          client.print( mois1);
          Serial.println("-> add_mois1");
          client.print("&&");
          client.print("moisture2=");
          client.print( mois2);
          Serial.println("-> add_moi2");

          client.println( " HTTP/1.1");
          client.println( "Host:" );
          client.println(server);
          client.println( "Connection: close" );
          client.println();
          client.println();
          client.stop();
        }
      }
      else {
        // you didn't get a connection to the server:
        Serial.println("--> connection failed/n");
      }

      delay(interval);
    }
    float getTemp() {
      float temperatureC = (5.0 * analogRead(temperaturePin) * 100.0) / 1024; //converting from a 0 to 1023 digital range to 0 to 5 volts (each 1 reading equals ~ 5 millivolts
      return temperatureC;
    }
    float getLight() {
      float light;
      light = analogRead(lightPin) ;
      return light;
    }

    float getMoisture1() {
      float moisture1;
      moisture1 = analogRead(moisture1Pin) ;
      return moisture1;
    }
    float getMoisture2() {
      float moisture2;
      moisture2 = analogRead(moisture2Pin) ;
      return moisture2;
    }

body:
There are two basic things wrong with your code.  First is the formatting of your headers - you have mistakenly used `client.println` for sending the first part of the Host: header, so it becomes split onto two lines:

    client.println( "Host:" );
    client.println(server);

Secondly you are using the server's IP address instead of the actual host name in the Host: header. That means the server can't work out which website you are wanting to talk to and just rejects your request.

You need to have something more like:

    client.print("Host: ");
    client.println(servername);

where `servername` is the *name* of the server (`www.website.com`) *not* the IP address.  You can put it all in one line if you don't ever want to change the website name, since it makes it slightly harder to find and edit:

    client.println("Host: www.mywebsite.com");


body:
First of all, are you now connected to SQL? If so, and it still doesn't work... Have you tried to escape your `"`, so instead of:

<!-- language-all: lang-php -->

    $SQL = "... VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."',...')";

doing something like:

    $SQL = "... VALUES ('\".$_GET[\"serial\"].\"', '\".$_GET[\"temperature\"].\"',...')";

If it still doesn't work, once you send to SQL with your code, print on screen what you are effectively sending, copy it with your mouse, paste it in your phpadmin-sql console and execute it. There you should see any helpful tips on what is really happening.
Hope this helps!


message:
How to loop over objects or pass object to function?

I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea.

I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array.

However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try.

I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination.

I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with & or * to explain what I want:

    SomeClass classA();
    SomeClass classB();

    // error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested
    SomeClass things[2] = {classA, classB};

    int init(class SomeClass thing) {
     std::cout << "Setting up thing ";
     thing.setFoo(100);
    }

    int main() {

     for (int i=0; i < 2; i++) {
      things[i].setFoo(100);
     }

     // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’
     init(classA);

       return 0;
    }

And just for completeness my class files which are simplified versions of the AccelStepper class:

SomeClass.h:

    #include <stdlib.h>

    class SomeClass
    {
    public:
        SomeClass();

        void    setFoo(float foo);
    };

SomeClass.cpp:

    #include <stdlib.h>
    #include <string>
    #include <iostream>
    #include "SomeClass.h"

    SomeClass::SomeClass()
    {
    }

    void SomeClass::setFoo(float foo)
    {
     std::cout << "foo ";
    }

I hope someone doesn't mind explaining what is probably really simple and obvious! :)

body:
There's a couple of fundamental errors in your sketch.  Mainly your construction of your class instances:

    SomeClass classA();
    SomeClass classB();

Those are taken as functions that return a SomeClass object, not SomeClass constructors.  Instead they should just read:

    SomeClass classA;
    SomeClass classB;

As for the rest, you are much better off using pointers to the classes - it makes passing them around so much easier.  For instance, your array would look like this:

    SomeClass *things[2] = {&classA, &classB};

That is an array of pointers to the objects.  It just stores the addresses that they are at, rather than duplicating the objects into new objects within the array.

Your loop would then run like this:

    for (int i=0; i < 2; i++) {
        things[i]->setFoo(100);
    }

Note the use of `->` instead of `.` because you are using a pointer to the object.

Similarly your `init()` function would be like this:

    int init(SomeClass *thing) {
        Serial.println("Setting up thing");
        thing->setFoo(100);
    }

    init(&classA);

However, if you're never going to use the contents of your array with it you could use a reference instead of a pointer:

    int init(SomeClass &thing) {
        Serial.println("Setting up thing");
        thing.setFoo(100);
    }

    init(classA);

That performs the same job as a pointer but leaves you with what looks like a real object rather than a pointer to the object - in fact it's just aliased the object name to a new one at the same address so you can still access it the same using `.`