message:
Break loop/restart program at any time

maybe my problem is just that my thinking is wrong. I hope you can help me.
First of all I will point out what I think in general, then I show you some code to work with.

In general my problem is to wrap me head around a push-button (or any other input) that stops (or better restarts) a running program at **any** time.
If i use the digitalRead(pin-whatsoever)-statement don't I have to tackle the exact mili/microsecond my MC is working on that specific line of code?
I don't want to use an interrupt either, i want to restart the program, not to interrupt it.

My project is some kind of turn-indicators for a bicycle.
The lights shall "run" from right to left on left-turns and vice versa.
But i want to stop the sequence at any point (or at least after one loop-run) if I push the corresponding button again.
After that the MC shall wait for another button-push to run the indicator either till the for-loop is finished or i press the same button earlier.

Another (general) question: Is there a way to get rid of delay-statements and achieve similar results?

Thank You so far.

       // Var-Setup
      const int mtime = 120; // Time between lights lighting up
      const int ftime = 100; // Time between lights turning out

    void setup() {
      // put your setup code here, to run once:
      // Pin-Setup
        // LED-Pins
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);

      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(11, OUTPUT);

        // Button-Pins
      pinMode(12, INPUT);
      pinMode(13, INPUT);

    }

    void right(){
      for(int i=0; i<5; i++){
          // Indicator right with running light (like a "half-knight-rider" ;) )
          // Rise
          digitalWrite(11, HIGH);
          delay(mtime);
          digitalWrite(10, HIGH);
          delay(mtime);
          digitalWrite(9, HIGH);
          delay(mtime);
          digitalWrite(8, HIGH);
          delay(mtime);
          digitalWrite(7, HIGH);
          delay(mtime);
          delay(mtime);

          // Fade
          digitalWrite(11, LOW);
          delay(ftime);
          digitalWrite(10, LOW);
          delay(ftime);
          digitalWrite(9, LOW);
          delay(ftime);
          digitalWrite(8, LOW);
          delay(ftime);
          digitalWrite(7, LOW);
          delay(250);
        }
    }

    void left (){
      for(int i=0; i<5; i++){
        // Indicator left with running light
        // Rise
        digitalWrite(2, HIGH);
        delay(mtime);
        digitalWrite(3, HIGH);
        delay(mtime);
        digitalWrite(4, HIGH);
        delay(mtime);
        digitalWrite(5, HIGH);
        delay(mtime);
        digitalWrite(6, HIGH);
        delay(mtime);
        delay(mtime);

        // Fade
        digitalWrite(2, LOW);
        delay(ftime);
        digitalWrite(3, LOW);
        delay(ftime);
        digitalWrite(4, LOW);
        delay(ftime);
        digitalWrite(5, LOW);
        delay(ftime);
        digitalWrite(6, LOW);
        delay(250);
      }
    }

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorL = digitalRead(12);
      int sensorR = digitalRead(13);
      if(sensorL == HIGH){
        left();
      }else if(sensorR == HIGH){
        right();
      }
    }

body:
replace each delay chain with a switch statement where each delay is replaced by saving the current millis counter, a increment of the state, a case label for the new state and a `if(millis()-timestamp  < timeout) return;`

    switch(state){
    case 0;
          // Indicator right with running light (like a "half-knight-rider" ;) )
          // Rise
          digitalWrite(11, HIGH);
      timestamp = millis();
      state++;
    case 1:
       if(millis()-timestamp  < mtime) return;

          digitalWrite(10, HIGH);
      timestamp = millis();
      state++;
    case 2:
          digitalWrite(9, HIGH);
    //etc.

The for loop around the entire thing will need to be replaced. Make `i` global and incrementing it in the last state and resetting it as needed. When i has been incremented to beyond 5 you always return.

This means that the `left` and `right` functions only do a few things: set the led, check a timestamp against the current time, and increment a state before returning.

This means that they will take very little time to execute and that you can check the button in the main loop() body and if pressed initiate the statemachine or end it (and putting out the LED when needed).


sender: user

message:
Two data outputs to be displayed on one 16x1 lcd display

Before pursuing this very far, I would like to know if I can get two different data outputs (one on the left 8 and the other data on the right 8).  And if so, are there any requirements on the display or any other thing that might be needed.  I'm thinking that as far as the proper Arduino platform being the Mega 2560.  My idea is to put together an FSX navigation radio for my flight simulator.

sender: assistant

body:
You can use

    lcd.setCursor(x, y);

To set the cursor.

Than you can output text with

    lcd.print("Text");

Make sure you add spaces in case there is already text written to overwrite older text.

You can also use

    lcd.clear();

to clear the display, but this might result in flickering if you do it too often.

Another possibility is to create a 16 character string

    char lcdText[16];

and write characters in this string and set it at once with:

    lcd.setCursor(0, 0);
    lcd.print(lcdText);


message:
USB or external power

I have an arduino mega that i am using as a clock. I would like it to detect if it is connected to a USB or external power supply (e.g. a battery). I then want to set a variable to different values depending on the result, so i can display it on an OLED.

body:
Use a simple transistor where the Vin (external power) is connected to the base, which switches the transistor. Than connect the collector to +5V, and the emitter to a GPIO input pin and read the status with the Arduino. If it receives a HIGH you know external power (via Vin) is used.

See the useful 'good' answer as comment of Majenko below ... I will leave the answer above as is, to keep his remarks clear.


message:
Blink a LED between servo pulses

Apparently using delay() commands locks the Arduino during the delay period and there are better ways to control a servo that free the Arduino to do other things at the same time as running the servo.

At this point my code consists of a servo going forwards and backwards like this:

    void setup()
    {
      pinMode(1, OUTPUT); // makes pin 1 an output
    }
    void loop()
    {
    for(int i = 0; i<31; ++i) { //keeps in this position for about 400ms
      digitalWrite(1, HIGH); //turns the servo pin to HIGH
      delayMicroseconds(1000); //sets the servo to move clockwise
      digitalWrite(1, LOW); //turns the servo pin to LOW
      delay(19);
    }

    for(int i = 0; i<31; ++i) { // keeps in this position for about 400ms
      digitalWrite(1, HIGH); // turns the servo pin to HIGH
      delayMicroseconds(2000); //sets the servo to move anti-clockwise
      digitalWrite(1, LOW); //turns the servo pin to LOW
      delay(19);
    }}

Where and how will I add some code that will allow the arduino to carry out another task for example blinking an led light during the approximately 20ms between servo pulses.

NOTE: The arduino is using the ATtiny 85 Processor.

body:
Before and after the delay of 19 ms?

In setup add:

    pinMode(2, OUTPUT); // LED pin output

Than changen in both cases:

      delay(19);

into

      digitalWrite(2, HIGH); // LED on
      delay(19);
      digitalWrite(2, LOW); // LED off


body:
*I'm not sure exactly what you mean with "between servo pulses" but I am assuming it means you want to blink the led while the servo is turning.*

Use the Arduino Timer library: https://playground.arduino.cc/Code/Timer

Add this at top of the sketch:

    #include "Timer.h"

    Timer t;
    #define BLINK_TIME 20

in setup, add:

    t.oscillate(LED_PIN, BLINK_TIME, HIGH);

inside the two for-loops, add:

    t.update();

This will make the led on LED_PIN turn on and off every 20 milliseconds.


body:
Short answer: don't use `delay()` if you want to do anything other than waiting, so rewrite your code without that call.

Long answer follows.

Instead of asking the Arduino to go to _sleep_ (1) until a certain amount of time has passed, you should write your code to run continuously and do certain things whenever enough time has passed since the last time they have been executed.
If the previous statement makes sense to you, then the following piece of code translates to C language what I just stated in English:

<!-- language: lang-cpp -->

    unsigned long time; // stores the time when the last motor movement happened, in ms
    boolean clockwise; // stores the wanted direction: true CW, false CCW
    unsigned byte counter; // stores how many time the wanted movement has occurred so far

    unsigned long ledTimer; // stores the last time we changed the LED state
    boolean ledIsOn; // stores the current LED state
    void setup() {
      pinMode(1, OUTPUT); // makes pin 1 an output
      pinMode(13, OUTPUT); // makes pin 13 (onboard LED pin) an output
    }

    void loop() {
      if (time - millis() >= 19) { // has enough time passed since the last time we executed a step motor movement?
        time = millis(); // reset the timer for next pass
        if (counter < 31) { // have we moved in the same direction enough?
          if (clockwise) {
            moveCW();
          } else {
            moveCCW();
          }
          counter++;
        } else { // we moved enough times in the same direction: reset the counter and switch direction
          counter = 0;
          clockwise = !clockwise;
        }
      }
      // do anything else, but don't use delay()!!!
      // the following does the same as above, but on the LED
      // blinking at 1Hz (500 ms on, 500ms off)
      if (millis() - ledTimer >= 500) {
        if (ledIsOn) {
          digitalWrite(13, LOW);
        } else {
          digitalWrite(13, HIGH);
        }
        ledIsOn = !ledIsOn;
        ledTimer = millis();
      }

      // need to do something more? go ahead and try
      // but remember not to use delay() and not to waste too much time
      // in complex calcs or the loop will take too long to wrap
    }

    void moveCW() {
      digitalWrite(1, HIGH); //turns the servo pin to HIGH
      delayMicroseconds(1000); //sets the servo to move clockwise
      digitalWrite(1, LOW); //turns the servo pin to LOW
    }

    void moveCCW() {
      digitalWrite(1, HIGH); // turns the servo pin to HIGH
      delayMicroseconds(2000); //sets the servo to move anti-clockwise
      digitalWrite(1, LOW); //turns the servo pin to LOW
    }

There is a beautiful library called `elapsedMillis` ([reference][1]) which can reduce a bit the boilerplate code regarding subtracting `millis()` and all that stuff, but the code above is practically the same and, probably, more straightforward to begin with.

<sub>
(1) The term _sleep_ it's incorrect as it implies some sort of power reduction. Instead `sleep()` is just wasting time at full power.
</sub>

  [1]: https://playground.arduino.cc/Code/ElapsedMillis


message:
Having a problem where the previous letter flashes after a space

im currently working on a stranger things letter board with an arduino and ws2811 leds and im having an issue where ever there is a space, the previous letter will be displayed. Ive tried going in and finding where it makes this duplicate, but i am rather inexperienced. Heres my code:

    #include <FastLED.h>

    #include <HashMap.h>

    #define DATA_PIN 6 //this is the data pin connected to the LED strip. If using WS2801 you also need a clock pin

    #define NUM_LEDS 50 //change this for the number of LEDs in the strip

    #define COLOR_ORDER RGB

    CRGB leds[NUM_LEDS];

    CRGB colors[5];

    int myleds[25];

    int last_letter = 0;

    CRGB white = CRGB(255, 255, 255);

    CRGB red = CRGB (255, 0, 0);

    CRGB green = CRGB (0, 255, 0);

    CRGB blue = CRGB(0, 0, 255);

    CRGB off = CRGB(0, 0, 0);

    const byte HASH_SIZE = 28;

    HashType<char, int> hashRawArray[HASH_SIZE];

    HashMap<char, int> charToLed = HashMap<char, int>( hashRawArray , HASH_SIZE );

    void setup() {

      FastLED.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); //setting up the FastLED

      randomSeed(analogRead(0)); //seeding my random numbers to make it more random.

      myleds[0] = 47;//A

      charToLed[0]('a', 47);

      myleds[1] = 45;//B

      charToLed[1]('b', 45);

      myleds[2] = 43;//C

      charToLed[2]('c', 43);

      myleds[3] = 42;//D

      charToLed[3]('d', 42);

      myleds[4] = 40;//E

      charToLed[4]('e', 40);

      myleds[5] = 38;//F

      charToLed[5]('f', 38);

      myleds[6] = 37;//G

      charToLed[6]('g', 37);

      myleds[7] = 34;//H

      charToLed[7]('h', 34);

      myleds[8] = 32;//I

      charToLed[8]('i', 32);

      myleds[9] = 16;//J

      charToLed[9]('j', 16);

      myleds[10] = 18;//K

      charToLed[10]('k', 18);

      myleds[11] = 20;//L

      charToLed[11]('l', 20);

      myleds[12] = 22;//M

      charToLed[12]('m', 22);

      myleds[13] = 24;//N

      charToLed[13]('n', 24);

      myleds[14] = 26;//O

      charToLed[14]('o', 26);

      myleds[15] = 28;//P

      charToLed[15]('p', 28);

      myleds[16] = 29;//Q

      charToLed[16]('q', 29);

      myleds[17] = 31;//R

      charToLed[17]('r', 31);

      myleds[18] = 15;//S

      charToLed[18]('s', 15);

      myleds[19] = 13;//T

      charToLed[19]('t', 13);

      myleds[20] = 11;//U

      charToLed[20]('u', 11);

      myleds[21] = 9;//V

      charToLed[21]('v', 9);

      myleds[22] = 7;//W

      charToLed[22]('w', 7);

      myleds[23] = 4;//X

      charToLed[23]('x', 4);

      myleds[24] = 2;//Y

      charToLed[24]('y', 2);

      myleds[25] = 0;//Z

      charToLed[25]('z', 0);

      colors[0] = white;

      colors[1] = red;

      colors[2] = green;

      colors[3] = blue;

      colors[4] = off;

      reset();

      abcs();

    }

    void loop() {

      type("My world would be upsidedown if i went to homecoming without you");
      delay(3000);
      type("andificant");
      delay(100);
      jog();

    }

    void beforejog() {
      FastLED.clear();
      leds[0] = CRGB (0, 255, 255); //aqua
      leds[10] = CRGB (0, 255, 255); //aqua
      leds[20] = CRGB (0, 255, 255); //aqua
      leds[30] = CRGB (0, 255, 255); //aqua
      leds[40] = CRGB (0, 255, 255); //aqua
      leds[1] = CRGB (153, 50, 204); //dark orchid
      leds[11] = CRGB (153, 50, 204); //dark orchid
      leds[21] = CRGB (153, 50, 204); //dark orchid
      leds[31] = CRGB (153, 50, 204); //dark orchid
      leds[41] = CRGB (153, 50, 204); //dark orchid
      leds[2] = CRGB (255, 255, 0); //yellow
      leds[12] = CRGB (255, 255, 0); //yellow
      leds[22] = CRGB (255, 255, 0); //yellow
      leds[32] = CRGB (255, 255, 0); //yellow
      leds[42] = CRGB (255, 255, 0); //yellow
      leds[3] = CRGB (0, 255, 127); //spring green
      leds[13] = CRGB (0, 255, 127); //spring green
      leds[23] = CRGB (0, 255, 127); //spring green
      leds[33] = CRGB (0, 255, 127); //spring green
      leds[43] = CRGB (0, 255, 127); //spring green
      leds[4] = CRGB (255, 165, 0); //orange
      leds[14] = CRGB (255, 165, 0); //orange
      leds[24] = CRGB (255, 165, 0); //orange
      leds[34] = CRGB (255, 165, 0); //orange
      leds[44] = CRGB (255, 165, 0); //orange
      leds[5] = CRGB (65, 105, 255); //royal blue
      leds[15] = CRGB (65, 105, 255); //royal blue
      leds[25] = CRGB (65, 105, 255); //royal blue
      leds[35] = CRGB (65, 105, 255); //royal blue
      leds[45] = CRGB (65, 105, 255); //royal blue
      leds[6] = CRGB (76, 0, 153); //dark purple
      leds[16] = CRGB (76, 0, 153); //dark purple
      leds[26] = CRGB (76, 0, 153); //dark purple
      leds[36] = CRGB (76, 0, 153); //dark purple
      leds[46] = CRGB (76, 0, 153); //dark purple
      leds[7] = CRGB (255, 105, 180); //hot pink
      leds[17] = CRGB (255, 105, 180); //hot pink
      leds[27] = CRGB (255, 105, 180); //hot pink
      leds[37] = CRGB (255, 105, 180); //hot pink
      leds[47] = CRGB (255, 105, 180); //hot pink
      leds[8] = CRGB (0, 128, 0); //dark green
      leds[18] = CRGB (0, 128, 0); //dark green
      leds[28] = CRGB (0, 128, 0); //dark green
      leds[38] = CRGB (0, 128, 0); //dark green
      leds[48] = CRGB (0, 128, 0); //dark green
      leds[9] = CRGB (255, 0, 0); //red
      leds[19] = CRGB (255, 0, 0); //red
      leds[29] = CRGB (255, 0, 0); //red
      leds[39] = CRGB (255, 0, 0); //red
      leds[49] = CRGB (255, 0, 0); //red
      FastLED.show();
      delay(50);
      FastLED.clear();
    }

    void jog() {
      beforejog();
      delay(100);
      BLACKOUT();
      beforejog();
      delay(100);
      BLACKOUT();
      beforejog();
      delay(100);
      BLACKOUT();
      beforejog();
      delay(100);
      BLACKOUT();
      beforejog();
      delay(100);
      BLACKOUT();
      beforejog();
      delay(100);
      BLACKOUT();
      beforejog();
      delay(100);
      BLACKOUT();
      beforejog();
      delay(100);
      BLACKOUT();
      leds[31] = CRGB (255, 0, 0);
      FastLED.show();
      delay(2000);
      FastLED.clear();
      leds[11] = CRGB (255, 0, 0);
      FastLED.show();
      delay(2000);
      FastLED.clear();
      leds[24] = CRGB (255, 0, 0);
      FastLED.show();
      delay(2000);
      FastLED.clear();
    }

    void abcs() {

      for (int i = 0; i < 25; i++) {

        int t = myleds[i];

        leds[t] = white;

        FastLED.show();

        delay(250);

      }

      delay(10);

    }

    CRGB randomColor() {

      int t = random(4);

      return colors[t];

    }

    void reset() {

      for (int x = 0; x < NUM_LEDS; x++) {

        leds[x] = off;

      }

      FastLED.show();

      last_letter = 0;

    }

    void displayLetter(char letter) {

      if (isWhitespace(letter)) {

        last_letter = 0;

        delay(2000);

      }

      int lednum = charToLed.getValueOf(letter);

      if (lednum >= 0 && lednum <= 50) {

        if (last_letter == lednum) {

          delay(2000);
        }

        leds[lednum] = white;

        FastLED.show();

        last_letter = lednum;

        delay(2000);

        leds[lednum] = off;

        FastLED.show();

      }

    }

    void type(String message) {

      reset();

      message.toLowerCase();

      for (int i = 0; i < message.length(); i++) {

        displayLetter(message[i]);

      }

      reset();

    }
    void BLACKOUT() {
      int r = 0;
      int b = 0;
      int g = 0;

      for (int x = 0; x < NUM_LEDS; x++) {
        leds[x] = CRGB(r, g, b);
      }

      FastLED.show();
      delay(100);

    }
Any help is appreciated. thanks.

body:
This will not fix your problem!

You said you were inexperienced, so I have taken you code and with no knowledge of what it does (that mean I may have made mistakes) I have refactored it slightly.

    #include <FastLED.h>

    #define DATA_PIN (6) //this is the data pin connected to the LED strip. If using WS2801 you also need a clock pin
    #define NUM_LEDS (50) //change this for the number of LEDs in the strip
    #define COLOR_ORDER RGB
    #define HASH_SIZE (28)

    CRGB Leds[NUM_LEDS];

    int last_letter = 0;

    enum ColourNames {White, Red, Green, Blue, Off};
    const CRGB Colours[] = { CRGB(255, 255, 255), CRGB(255, 0, 0), CRGB(0, 255, 0), CRGB(0, 0, 255), CRGB(0, 0, 0) };

    struct LED
    {
     int myled;
     int led;
     char letter;
     LED(const int& m = 0, const int& l = 0, const char& let = 0)
      : myled(m)
      , led(l)
      , letter(let)
     {}
    };
    LED LedData[HASH_SIZE];

    void setup()
    {
     FastLED.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(Leds, NUM_LEDS); //setting up the FastLED
     randomSeed(analogRead(0)); //seeding my random numbers to make it more random.

     LedData[ 0] = LED(47, 47, 'a');
     LedData[ 1] = LED(45, 45, 'b');
     LedData[ 2] = LED(43, 43, 'c');
     LedData[ 3] = LED(42, 42, 'd');
     LedData[ 4] = LED(40, 40, 'e');
     LedData[ 5] = LED(38, 38, 'f');
     LedData[ 6] = LED(37, 37, 'g');
     LedData[ 7] = LED(34, 34, 'h');
     LedData[ 8] = LED(32, 32, 'i');
     LedData[ 9] = LED(16, 16, 'j');
     LedData[10] = LED(18, 18, 'k');
     LedData[11] = LED(20, 20, 'l');
     LedData[12] = LED(22, 22, 'm');
     LedData[13] = LED(24, 24, 'n');
     LedData[14] = LED(26, 26, 'o');
     LedData[15] = LED(28, 28, 'p');
     LedData[16] = LED(29, 29, 'q');
     LedData[17] = LED(31, 31, 'r');
     LedData[18] = LED(15, 15, 's');
     LedData[19] = LED(13, 13, 't');
     LedData[20] = LED(11, 11, 'u');
     LedData[21] = LED( 9,  9, 'v');
     LedData[22] = LED( 7,  7, 'w');
     LedData[23] = LED( 4,  4, 'x');
     LedData[24] = LED( 2,  2, 'y');
     LedData[25] = LED( 0,  0, 'z');
     LedData[26] = LED();
     LedData[25] = LED();

     reset();
     abcs();
    }

    void loop()
    {
     type("My world would be upsidedown if i went to homecoming without you");
     delay(3000);
     type("andificant");
     delay(100);
     jog();
    }

    void beforejog()
    {
     static const int MaxColours = 10;
     const CRGB colours[MaxColours] =
     {
        CRGB(0, 255, 255)   //aqua
      , CRGB(153, 50, 204)  //dark orchid
      , CRGB(255, 255, 0)   //yellow
      , CRGB(0, 255, 127)   //spring green
      , CRGB(255, 165, 0)   //orange
      , CRGB(65, 105, 255)  //royal blue
      , CRGB(76, 0, 153)   //dark purple
      , CRGB(255, 105, 180)  //hot pink
      , CRGB(0, 128, 0)   //dark green
      , CRGB(255, 0, 0)   //red
     };

     FastLED.clear();
     for (int col = 0; col < MaxColours; ++col)
     {
      for (int r = col; r < NUM_LEDS; r += MaxColours)
      {
       Leds[r] = colours[col];
      }
     }

     FastLED.show();
     delay(50);
     FastLED.clear();
    }

    void jog()
    {
     for (int l = 0; l < 7; ++l)
     {
      beforejog();
      delay(100);
      Blackout();
      delay(100);
     }

     static const MaxLights = 3;
     const int lights[MaxLights] = { 31, 11, 24 };
     for (int l = 0; l < MaxLights; ++l)
     {
      Leds[lights[l]] = Colours[Red];
      FastLED.show();
      delay(2000);
      FastLED.clear();
     }
    }

    void abcs()
    {
     for (int i = 0; i < 25; i++)
     {
      Leds[LedData[i].myled] = Colours[White];
      FastLED.show();
      delay(250);
     }
     delay(10);
    }

    CRGB randomColor()
    {
     const int t = random(4);
     return Colours[t];
    }

    void reset()
    {
     Blackout();
     last_letter = 0;
    }

    void displayLetter(char letter)
    {
     if (isWhitespace(letter))
     {
      last_letter = 0;
      delay(2000);
     }
     const int lednum = charToLed.getValueOf(letter);
     if (lednum >= 0 && lednum <= 50)
     {
      if (last_letter == lednum)
      {
       delay(2000);
      }
      Leds[lednum] = Colours[White];
      FastLED.show();
      last_letter = lednum;
      delay(2000);
      Leds[lednum] = Colours[Off];
      FastLED.show();
     }
    }

    void type(String message)
    {
     reset();
     message.toLowerCase();
     for (int i = 0; i < message.length(); i++)
     {
      displayLetter(message[i]);
     }
     reset();
    }

    void Blackout()
    {
     for (int x = 0; x < NUM_LEDS; x++)
     {
      Leds[x] = Colours[Off];
     }
     FastLED.show();
    }

What I have tried to do is group similar variables into arrays (`Colour`).  I have also created a structure to hold your LED data, it makes it easier to read if it all appears on a single line.  I have added loops to some of the functions to reduce the line count.  And if you aren't changing a variable make it const, it will make no difference to the compiler, but its easier to read and understand.

I haven't compiled this, so there is probably a howler in there, but hopefully it will give you a different perspective on your code and a different (not better) way of doing things.  Oh and it should still have the problem you are asking about, which I think is you need to add an else into that function.


message:
LCD library and timer2 CTC interrupt not working together

I want to set up real time counter along with lcd functions from LiquidCrystal library. But they don't work together. However, they work fine separately.
The code is working by itself, but by implementing counter function, LCD just freezes with other functionality.
Part of code:

        #include <LiquidCrystal.h>

    LiquidCrystal lcd(2, 3, 4, 5, 6, 7, 8, 9, 13, 12, 10);

    volatile boolean timerFlag = false;
    volatile unsigned long int tmr2Count = 0;

    void setup(){

        timer2Init();
    }
    void loop(){
        checkState();

    }
    //everything works by commenting out ISR and timer2Init
    //===================================================
    ISR (TIMER2_COMPA_vect){
      if (timerFlag)
        tmr2Count++;
    }
    void timerStart(void){
      if ( !timerFlag )
        timerFlag = true;
    }
    void timerReset(void){
      timerFlag = false;
      tmr2Count = 0;
    }
    void timer2Init(void){
        //Timer 2 interrupt service routine CTC settings, 1 uS:

        TCCR2A = 0;
        TCCR2B = 0;

        //set CTC mode
        TCCR2A |= (1 << WGM21);
        //prescaler 1 for timer2
        TCCR2B |= (1 << CS20);

        // prescaler for 1 uS.
        OCR2A = 15;
        //set compare match for register OCRA
        TIMSK2 |= ( 1 << OCIE2A);
    }
    //========================================================

    // menu
    void checkState(void)
    {
      // if button is pressed without menu being displayed
      if (userSettings.currentState == STATE_IDLE && encButton == true){
        userSettings.currentState = MENU_CHOICE;
        lcd.clear();
        lcd.setCursor(3,1);
        lcd.print("<Settings>");
        encButton = false;
      }

      int menuState = userSettings.currentState;

      switch(menuState)
      {
        case STATE_IDLE:
          timeDisplay();
          dateDisplay();
          break;

        case MENU_CHOICE:
          menuSettingDisplay();
          break;

        case MENU_CONTRAST:
          contrastSetting();
          break;

        case MENU_TIME:
          timeSetting();
          break;

        case MENU_DATE:
          setDate();
          break;

        case TIME_DISPLAY:
          timeDisplayOnOff();
          break;

        case DATE_DISPLAY:
          dateDisplay();
          break;

        default:
          break;
      }
    }

I digged in LiquidCrystal.cpp and found that there is DelayMicroseconds function, I'm thinking that it could be the cause. If it's not, what can be done otherwise ?

body:
You're getting interrupt every 16th CPU clock cycle. The `ISR` handler might be even longer than that and your code and lower priority ISRs suffers by "starvation" as MCU can't do anything else than processing ISR.

If you use prescaler value 8, then you have `1/2us` resolution of `TCNT2` and overflow interrupt (in normal mode) occurs every `128us`, so there will be enough time to do something else. However, if you want atomic value of `TCNT2` and counted value from `ISR` handler, you'll have to stop Timer2 for a while.


message:
How to jump outside the loop? in below Programme how to use goto or any other Jump related Programme

const int analogPin1 = A1;
    const int analogPin2 = A2;
    const int analogPin3 = A3;
    const int ledPin = 13;
    const int ledPin2 = 7;
    const int thresold = 400;
    unsigned int x1, x2, x3, fault = 0;
    void setup()
    {
        pinMode(ledPin, OUTPUT);
        Serial.begin(9600);
    }
    void Config()
    {
        delay(1000);
        Serial.print("ATE0r");
        Response();
        Serial.print("ATr");
        Response();
        Serial.print("AT+CMGF=1r");
        Response();
        Serial.print("AT+CNMI=1,2,0,0,0r");
        Response();
    }
    void Response()
    {
        int count = 0;
        Serial.println();
        while (1) {
            if (Serial.available()) {
                char data = Serial.read();
                if (data == 'K') {
                    Serial.println("OK");
                    break;
                }
                if (data == 'R') {
                    Serial.println("GSM Not Working");
                    break;
                }
            }
            count++;
            delay(10);
            if (count == 1000) {
                Serial.println("GSM not Found");
                break;
            }
        }
    }
    void loop()
    {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);

        if (analogValue1 < thresold) {
            x1 = 1;
            fault = x1;
        }
        if (analogValue2 < thresold) {
            x2 = x1 + 3;
            fault = x2;
        }
        if (analogValue3 < thresold) {
            x3 = x1 + x2 + 5;
            fault = x3;
        }

        switch (fault) {
        case 1:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919\"\r");
            delay(1000);
            Serial.print("PHASE 1 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            goto nsr;
            break;

        case 3:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919\"\r");
            delay(1000);
            Serial.print("2 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            goto nsr;
            break;

        case 4:
            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919\"\r");
            delay(1000);
            Serial.print("1 AND 2 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            goto nsr;
            break;

        case 5:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919\"\r");
            delay(1000);
            Serial.print("3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            Serial.print("AT+CNMI=2,2,0,0,0");
            goto nsr;
            break;

        case 6:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919\"\r");
            delay(1000);
            Serial.print("1 AND 3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            goto nsr;
            break;

        case 8:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919\"\r");
            delay(1000);
            Serial.print("2 AND 3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            goto nsr;
            break;

        case 10:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919\"\r");
            delay(1000);
            Serial.print("ALL 3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            goto nsr;
            break;

        default:
            x1, x2, x3, fault = 0;
            digitalWrite(ledPin, LOW);
            break;
        }

        x1, x2, x3, fault = 0;
        digitalWrite(ledPin, LOW);
        do {
            int analogValue1 = analogRead(analogPin1);
            int analogValue2 = analogRead(analogPin2);
            int analogValue3 = analogRead(analogPin3);
        } while (analogValue1 < thresold || analogValue2 < thresold || analogValue3 < thresold);
    }

    do {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    } while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
    }

    nsr : if ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
    {

        digitalWrite(ledPin, HIGH);
        Serial.begin(9600);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("ALL 3 Phase Restored");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("ALL 3 Phase Restored");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);

        do {
            int analogValue1 = analogRead(analogPin1);
            int analogValue2 = analogRead(analogPin2);
            int analogValue3 = analogRead(analogPin3);
        } while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
    }

body:
Instead of using

    goto nsr

Use a boolean to skip parts you do not want to execute. It is (almost) never a good idea to use goto.

Due to the misalignment of { and } I do not know what you exactly want to execute.


body:
You want to create separate function `nsr` and use it instead of goto.

    void nsr(void){
      if ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
      {

        digitalWrite(ledPin, HIGH);
        Serial.begin(9600);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("ALL 3 Phase Restored");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("ALL 3 Phase Restored");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);

        do {
            int analogValue1 = analogRead(analogPin1);
            int analogValue2 = analogRead(analogPin2);
            int analogValue3 = analogRead(analogPin3);
        } while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
      }
    }


message:
DHT.h Library not being imported

I am trying to read the humidity and temperature using a DHT11 temperature sensor for an Arduino UNO using the `DHT.h` library. I have my code below:

    #include <DHT.h>
    #define dataPin 4
    dht DHT;

    void setup() {
      Serial.begin(9600)

    }

    void loop() {
      int readData = DHT.read11(dataPin);
      float t = DHT.temperature;
      float h = DHT.humidity;
      Serial.println("Temperature: ")
      Serial.print(t)
      Serial.print(" ºC")
      Serial.println("Humidity: ")
      Serial.print(h)
      Serial.print(" % ")
      delay(2000)
    }

When compiling the program, it gives me an error:

    fatal error: DHT.h: No such file or directory

I have also tried with lower case letters, but it will not work. Is there any reason why? Do I have to install it? I have tried to search for the library in the Arduino app **Sketch - Include Library - Manage Libraries**, but the library is not there.

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

1. Download https://github.com/RobTillaart/Arduino/archive/master.zip
1. Copy the `Arduino-master/libraries/DHTstable` subfolder of the downloaded file to the `libraries` subfolder of your sketchbook folder. You can find the location of your sketchbook folder at **File > Preferences > Sketchbook location** in the Arduino IDE.
1. Change the first line of your sketch from:

        #include <DHT.h>
 to:

        #include <dht.h>

Now when you try to compile the sketch you will still encounter many errors. However, these are caused by a paucity of semicolons, not by the DHT library, and thus off-topic for this question.


body:
I have had problems using some `DHT` library versions.  I suggest that you try using a different version of `dht.h`

This version works for me (there are [newer versions][1], but I recommend starting with this oldie but goldie):

dht.h (606B 6/12/2012)

 //
 //    FILE: dht.h
 // VERSION: 0.1.00
 // PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
 //
 //     URL: http://arduino.cc/playground/Main/DHTLib
 //
 // HISTORY:
 // see dht.cpp file
 //

 #ifndef dht_h
 #define dht_h

 #if ARDUINO >= 100
  #include "Arduino.h"
 #else
  #include "WProgram.h"
 #endif

 #define DHT_LIB_VERSION "0.1.00"

 class dht
 {
 public:
  int read11(uint8_t pin);
     int read22(uint8_t pin);
  double humidity;
  double temperature;

 private:
  uint8_t bits[5];  // buffer to receive data
  int read(uint8_t pin);
 };
 #endif
 //
 // END OF FILE
 //

  [1]: http://arduino.cc/playground/Main/DHTLib


body:
try to download this library in this link and insert it to your ide, it works for me.

https://github.com/adafruit/DHT-sensor-library


message:
Reading pressure sensor using Arduino analog

I'm using a Arduino Uno to read pressure and I want to know if I have wired/coded the sensor correctly. I'm not sure I'm getting the correct readings (it could be the right readings - I just want to check I have done everything right). The sensor I am using is an OsiSense™ XMLP pressure sensor that reads between 0 and 100 bars and gives out a 0v (zero bars) to 10v (100 bars) charge. Due to the Arduino Uno only being capable of reading up to 5 volts, I've used a voltage divider to reduce the maximum voltage the Arduino receives to 5v.

I've attached a hand-written diagram. Let me know if you need any more information. I've attached the wiring and also the code.

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

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

    /*
      ReadAnalogVoltage from a OsiSense XMLP presure sensor

      Reads an analog input on pin 0, converts it to voltage and then bar pressure, and prints the result to the Serial Monitor and also MQTT.
      Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).

      Todo
      Static ip. set it to request IP from network
      Work out best way to average readings

    */

    #include <SPI.h>  //Serial Peripheral Interface (SPI)
    #include <Ethernet.h>  //  These libraries are designed to work with the Arduino Ethernet Shield (Ethernet.h)
    #include <PubSubClient.h>  // This library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT

    // sets the MAC address and IP address for the network
    byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
    IPAddress ip(192,34,98,221);  // IP Address of the client
    IPAddress server(192,34,98,201); // The IP address of the MQTT server

    void callback(char* topic, byte* payload, unsigned int length) {
      // handle message arrived
    }

    EthernetClient ethClient;
    PubSubClient client(server, 1883, callback, ethClient);

    void setup() {
      Serial.println("Begin setup");
      Ethernet.begin(mac, ip);
      // Note - the default maximum packet size is 128 bytes. If the
      // combined length of clientId, username and password exceed this,
      // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
      // PubSubClient.h

      // connects to MQTT and says hello world.  Probably change this later on to something more appropriate
      if (client.connect("ArdRigTest")) {
        client.publish("outTopic","Ard Rig Test");
        client.subscribe("inTopic");
      }
      // start serial port
      Serial.begin(9600);
    }

    void loop() {
      // Note - the default maximum packet size is 128 bytes. If the
      // combined length of clientId, username and password exceed this,
      // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
      // PubSubClient.h

      // read the input on analog pin 0:
      int sensorValue1 = analogRead(A0);
      delay(2); // read twice with small delay to get accurate reading.
      int sensorValue2 = analogRead(A0);

      Serial.println(sensorValue2);
      //Test code. using map function
      int MapBarPressure;
      MapBarPressure = map(sensorValue2, 0, 1023, 0, 100);
      if (client.connect("ArdRigTest" )) {
        client.publish("MapBarPressure",String(MapBarPressure).c_str());  //logs the pressure of the RigTest
        client.subscribe("MapBarPressure");
      }
      delay(100); // Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)
      client.loop();
    }

Thanks in advance.

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

body:
You can use `map`, ref. : https://www.arduino.cc/en/Reference/Map

> Re-maps a number from one range to another. That is, a value of
> fromLow would get mapped to toLow, a value of fromHigh to toHigh,
> values in-between to values in-between, etc.


body:
If you need to use fractional pressure values, then the formula is

    float MapBarPressure;
    MapBarPressure = sensorValue2 / 10.24;

This was obtained by seeing that the maximum reading from `AnalogRead(A0)` is `1024`, which corresponds to 5V on A0 (and which also means 10V output from the sensor.) If you read `1024` from A0, it means you are measuring 100bar, so

    bar = (A0 / 1024) * 100

Alternatively, you could maintain 1 decimal place of accuracy in bar if you keep with `int` values:

    int MapDeciBarPressure;
    MapDeciBarPressure = map(sensorValue2, 0, 1023, 0, 1000);

Then your variable is holding "tenths of bar" (deciBar) and you only convert it to bar by dividing by 10.0 (not 10, which is an int, but 10.0, which is a float and does floating point math and returns a float response.)

One other note: you write:

    // read the input on analog pin 0:
    int sensorValue1 = analogRead(A0);
    delay(2); // read twice with small delay to get accurate reading.
    int sensorValue2 = analogRead(A0);

Just reading twice doesn't gain accuracy -- you have to average the values:

    int sensorValAvg = (sensorValue1 + sensorValue2) / 2;

Then, use sensorValAvg for your less noisy value.

**Edit:**
Also, make sure you connect all ground lines together, both from the sensor and the Arduino!


body:
**About accuracy.**

I assume you have read @edgar-bonet about connecting the GND's.
I assume you understand the other answer to calculate the pressure. I would write it like this:

    // This is for the DEFAULT 5V analog reference.
    // v = the voltage at the pin in Volts.
    // p = the pressure in bar.
    // Note that 'bar' is the pressure relative to the
    // normal atmospheric pressure at that moment.
    float v = (float) analogRead(A0) / 1024.0 * 5.0;
    float p = v / 5.0 * 100.0;

The [`analogRead`][1] uses default the 5V as reference.

That means that if the project is powered by a USB cable, the 5V could vary between 4.5 and 5.0 V. That 10% difference will be seen in the resulting calculated pressure. In that case you can not measure more accurate than 10%.

If the project is powered with a power supply to the power barrel jack, then the resulting accuracy depends on the accuracy of the voltage regulator on the Arduino board.

The analog reference can be set with [`analogReference`][2].
The internal voltage reference of the Arduino Uno is 1.1V. That is reasonably stable, but it depends a little on the voltage of VCC and the temperature. The main problem is that it is different for each Arduino Uno, and it can be between 1.0 and 1.2 V. Therefor you have to measure it, and use the measured value in the calculation in the sketch.

The input range is between 0V and the analog reference. Therefor you have to adjust the voltage divider to get 0..10V down to 0..1.1V. You could try: R1 = 100k and R2 = 10k.

    const int pressureSignalPin = A0;

    void setup()
    {
      analogReference( INTERNAL);
    }

    void loop()
    {
      // v = the voltage at the pin in Volts.
      // p = the pressure in bar.
      // Note that 'bar' is the pressure relative to the
      // normal atmospheric pressure at that moment.
      // The "(100.0 + 10.0) / 10.0" is the factor by the voltage divider
      // with 100k and 10k.
      // Measure the AREF pin, and fill the value in for "1.10".
      float v = (float) analogRead(A0) / 1024.0 * 1.10;
      float p = v * ((100.0 + 10.0) / 10.0);
    }

  [1]: https://www.arduino.cc/en/Reference/AnalogRead
  [2]: https://www.arduino.cc/en/Reference/AnalogReference


body:
Everything is just fine.

All you have to do is to provide the common ground (0 potential) to your Arduino and your Sensor.

The problem here is that they might be on a different potential.

So just connect the ground of your 5 volts and 24 volts together and everything will work perfectly.


message:
Arduino Mega Wifi Shield Timeout Error

I got an Arduino Mega(not original) and also a Wifi shield, when ever I try to upload my code to it, I get this error:

    Sketch uses 5504 bytes (2%) of program storage space. Maximum is 253952 bytes.
    Global variables use 704 bytes (8%) of dynamic memory, leaving 7488 bytes for local variables. Maximum is 8192 bytes.
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer
    An error occurred while uploading the sketch
Without the shield on it works perfectly, but as soon as I plug it in it stops working, I tried uploading the code without shield and placing the shield but this way the serial port didn't work.

The shield I bought is:<br>
**ESP8266 ESP-12E UART WIFI Module Wireless Shield Converter For Arduino UNO Mega**
[![enter image description here][1]][1]

**Edit:**
If there is anything connected to the arduino it wont upload, it is not just the shield, I can't get my OLED to work either. Also tried using the shield on my UNO and I get the same result.

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

body:
via Google I found this helpful site which has an answer that might help.  It is not the same question as yours, but it explains what the dip switches are for

https://arduino.stackexchange.com/questions/24919/how-to-connect-wi-fi-shield-esp-12e-esp8266-uart-wifi-wireless-shield-with-ardui

It seems that _IF_ you have what is pictured a 'shield' version of the board, as opposed to a 'shaild' version, then when you plug it in to an uno it will stop the uno working, because of the serial connection from the ESP on shield pins 0 and 1.  I don't know where these pins are going on your mega, but it might be the same issue.  This page recommends bending the pins out the way and wiring them to other pins - Which is at your risk.  You could trial it by wiring the whole shield to the mega and seeing if it worked.

https://claus.bloggt.es/2017/02/26/arduino-esp8266-wifi-shield-elecshop-ml-by-wangtongze-comparison/


message:
Powering a Nano with a 5v mini USB adaptor

I have made a [simple temp sensing circuit that lights an LED][1] when it reaches a certain point. It works perfectly when powered by a USB plugged in to the laptop but when I connect it to a 5V supply with a mini-USB connection nothing happens.

Is this correct and do I need to send power directly to the board on the 5V pin?

Many thanks,
Jack

  [1]: http://hackscience.io/project/temperature-alert/

body:
Thanks all. I found a different power source with a mini-usb connector and it works fine. I think when plugging it in to the PC the Nano makes some faint clicking noises but when direct to  5v plug it does not? I'm not sure so I'll re-test. It was the lack of clicking that lead me to believe it wasn't working as I can't see the on board LEDs using my enclosure.

I don't know about the accuracy but it seems to work for my situation - it is to be placed in a fridge that recently turned itself in to a freezer but has since fixed itself. This project is an early warning system in case it decides to do it again.

Thanks again.
Jack


message:
ESP8266 Blink sketch - does not blink / or stays constant

I uploaded the Blink sketch (from the ESP8266 examples, in the Arduino IDE) successfully.

Depending on which wire configuration I am using two different things happen:

`wiring 1`:

    CH_PD -> 3.3V
    VCC -> 3.3V
    RST -> GND
    GPI02 -> LED
    GND -> GND

`wiring 2`:

    VCC -> 3.3V
    RST -> GND
    GPI02 -> LED
    GND -> GND

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

There are TX/RX lines in the picture from when I was flashing - they aren't being used for running the sketch.

With `wiring 1` the LED stays on (doesn't blink) - I was wondering if this was because I still had the VCC -> 3.3V connected. So I disconnected that, which gives way to `wiring 2`.

With `wiring 2` the LED doesn't come on at all, it is the same as `wiring 1` except without VCC -> 3.3V.

Why is it constant when 3.3V is going to VCC, and constantly off when I disconnect it? Why doesn't it blink using `wiring 2`?

**UPDATE**

A diagram as requested, sorry it was my first time doing this:

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

Code:

    /*
     ESP8266 Blink by Simon Peter
     Blink the blue LED on the ESP-01 module
     This example code is in the public domain

     The blue LED on the ESP-01 module is connected to GPIO1
     (which is also the TXD pin; so we cannot use Serial.print() at the same time)

     Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
    */

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                        // but actually the LED is on; this is because
                                        // it is acive low on the ESP-01)
      delay(1000);                      // Wait for a second
      digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
      delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
    }

  [1]: https://i.stack.imgur.com/hCIcx.jpg
  [2]: https://i.stack.imgur.com/Z0OgR.png

body:
You should connect Vcc to 3.3V, because that's how the ESP8266 is powered.
RST is active-low reset and should be pulled to 3.3V


body:
I can't comment as my karma is too low so if I am wrong please just someone let me know and I'll simply delete.

I thought that the RST pin being pulled to ground resets the chip, if this is the case surely in your setup you are constantly reseting your chip, so it won't do anything. My understanding is that you should have the reset pin pulled up to 3.3V with a 10K resistor.


message:
serial data transfer on gps shield duinopeak

I'm using an arduino uno r3 with a [gps shield duinopeak][1].

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

The shield is configured using RX pin 3 and Tx pin 2, as image below:

[![enter image description here][3]][3]

I'm using the TinyGPSPlus library to read NMEA data. This is my code:

    /******************************************************************************
      This example uses SoftwareSerial to communicate with the GPS module on
      pins 8 and 9, then communicates over SPI to log that data to a uSD card.

      It uses the TinyGPS++ library to parse the NMEA strings sent by the GPS module,
      and prints interesting GPS information - comma separated - to a newly created
      file on the SD card.

      Resources:
      TinyGPS++ Library  - https://github.com/mikalhart/TinyGPSPlus/releases
      SD Library (Built-in)
      SoftwareSerial Library (Built-in)

      Development/hardware environment specifics:
      Arduino IDE 1.6.7
      GPS Logger Shield v2.0 - Make sure the UART switch is set to SW-UART
      Arduino Uno, RedBoard, Pro, Mega, etc.
    ******************************************************************************/

    #include <SPI.h>
    #include <SD.h>
    #include <TinyGPS++.h>

    #define ARDUINO_USD_CS 8 // uSD card CS pin (pin 8 on Duinopeak GPS Logger Shield)

    /////////////////////////
    // Log File Defintions //
    /////////////////////////
    // Keep in mind, the SD library has max file name lengths of 8.3 - 8 char prefix,
    // and a 3 char suffix.
    // Our log files are called "gpslogXX.csv, so "gpslog99.csv" is our max file.
    #define LOG_FILE_PREFIX "gpslog" // Name of the log file.
    #define MAX_LOG_FILES 100 // Number of log files that can be made
    #define LOG_FILE_SUFFIX "csv" // Suffix of the log file
    char logFileName[13]; // Char string to store the log file name
    // Data to be logged:
    #define LOG_COLUMN_COUNT 8
    char * log_col_names[LOG_COLUMN_COUNT] = {
      "longitude", "latitude", "altitude", "speed", "course", "date", "time", "satellites"
    }; // log_col_names is printed at the top of the file.

    //////////////////////
    // Log Rate Control //
    //////////////////////
    #define LOG_RATE 5000 // Log every 5 seconds
    unsigned long lastLog = 0; // Global var to keep of last time we logged

    /////////////////////////
    // TinyGPS Definitions //
    /////////////////////////
    TinyGPSPlus tinyGPS; // tinyGPSPlus object to be used throughout
    #define GPS_BAUD 9600 // GPS module's default baud rate

    ////////////////////////////////////////////////
    // Arduino GPS Shield Serial Port Definitions //
    ////////////////////////////////////////////////
    // If you're using an Arduino Uno, Mega, RedBoard, or any board that uses the
    // 0/1 UART for programming/Serial monitor-ing, use SoftwareSerial:
    #include <SoftwareSerial.h>
    #define ARDUINO_GPS_RX 3 // GPS TX, Arduino RX pin
    #define ARDUINO_GPS_TX 2 // GPS RX, Arduino TX pin
    SoftwareSerial ssGPS(ARDUINO_GPS_TX, ARDUINO_GPS_RX); // Create a SoftwareSerial

    // Set gpsPort to either ssGPS if using SoftwareSerial or Serial1 if using an
    // Arduino with a dedicated hardware serial port
    #define gpsPort ssGPS  // Alternatively, use Serial1 on the Leonardo

    // Define the serial monitor port. On the Uno, Mega, and Leonardo this is 'Serial'
    //  on other boards this may be 'SerialUSB'
    #define SerialMonitor Serial

    void setup()
    {
      SerialMonitor.begin(9600);
      gpsPort.begin(GPS_BAUD);

      SerialMonitor.println("Setting up SD card.");
      // see if the card is present and can be initialized:
      if (!SD.begin(ARDUINO_USD_CS))
      {
        SerialMonitor.println("Error initializing SD card.");
      }
      updateFileName(); // Each time we start, create a new file, increment the number
      printHeader(); // Print a header at the top of the new file
    }

    void loop()
    {
      if ((lastLog + LOG_RATE) <= millis())
      { // If it's been LOG_RATE milliseconds since the last log:
        if (tinyGPS.location.isUpdated()) // If the GPS data is vaild
        {
          if (logGPSData()) // Log the GPS data
          {
            SerialMonitor.println("GPS logged."); // Print a debug message
            lastLog = millis(); // Update the lastLog variable
          }
          else // If we failed to log GPS
          { // Print an error, don't update lastLog
            SerialMonitor.println("Failed to log new GPS data.");
          }
        }
        else // If GPS data isn't valid
        {
          // Print a debug message. Maybe we don't have enough satellites yet.
          SerialMonitor.print("No GPS data. Sats: ");
          SerialMonitor.println(tinyGPS.satellites.value());
        }
      }

      // If we're not logging, continue to "feed" the tinyGPS object:
      while (gpsPort.available())
        tinyGPS.encode(gpsPort.read());
    }

    byte logGPSData()
    {
      File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file

      if (logFile)
      { // Print longitude, latitude, altitude (in feet), speed (in mph), course
        // in (degrees), date, time, and number of satellites.
        logFile.print(tinyGPS.location.lng(), 6);
        logFile.print(',');
        logFile.print(tinyGPS.location.lat(), 6);
        logFile.print(',');
        logFile.print(tinyGPS.altitude.feet(), 1);
        logFile.print(',');
        logFile.print(tinyGPS.speed.mph(), 1);
        logFile.print(',');
        logFile.print(tinyGPS.course.deg(), 1);
        logFile.print(',');
        logFile.print(tinyGPS.date.value());
        logFile.print(',');
        logFile.print(tinyGPS.time.value());
        logFile.print(',');
        logFile.print(tinyGPS.satellites.value());
        logFile.println();
        logFile.close();

        return 1; // Return success
      }

      return 0; // If we failed to open the file, return fail
    }

    // printHeader() - prints our eight column names to the top of our log file
    void printHeader()
    {
      File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file

      if (logFile) // If the log file opened, print our column names to the file
      {
        int i = 0;
        for (; i < LOG_COLUMN_COUNT; i++)
        {
          logFile.print(log_col_names[i]);
          if (i < LOG_COLUMN_COUNT - 1) // If it's anything but the last column
            logFile.print(','); // print a comma
          else // If it's the last column
            logFile.println(); // print a new line
        }
        logFile.close(); // close the file
      }
    }

    // updateFileName() - Looks through the log files already present on a card,
    // and creates a new file with an incremented file index.
    void updateFileName()
    {
      int i = 0;
      for (; i < MAX_LOG_FILES; i++)
      {
        memset(logFileName, 0, strlen(logFileName)); // Clear logFileName string
        // Set logFileName to "gpslogXX.csv":
        sprintf(logFileName, "%s%d.%s", LOG_FILE_PREFIX, i, LOG_FILE_SUFFIX);
        if (!SD.exists(logFileName)) // If a file doesn't exist
        {
          break; // Break out of this loop. We found our index
        }
        else // Otherwise:
        {
          SerialMonitor.print(logFileName);
          SerialMonitor.println(" exists"); // Print a debug statement
        }
      }
      SerialMonitor.print("File name: ");
      SerialMonitor.println(logFileName); // Debug print the file name
    }

Basically the code get the values os lat, long, alt, etc and log into csv file on sdcard. Unfortunately I'm always get no gps data. What's wrong with my code?

**Update:**

Test serial connection with this code:

    #include <AltSoftSerial.h>

    // AltSoftSerial always uses these pins:
    //
    // Board          Transmit  Receive   PWM Unusable
    // -----          --------  -------   ------------
    // Teensy 3.0 & 3.1  21        20         22
    // Teensy 2.0         9        10       (none)
    // Teensy++ 2.0      25         4       26, 27
    // Arduino Uno        9         8         10
    // Arduino Leonardo   5        13       (none)
    // Arduino Mega      46        48       44, 45
    // Wiring-S           5         6          4
    // Sanguino          13        14         12

    AltSoftSerial altSerial;

    void setup() {
      Serial.begin(9600);
      while (!Serial) ; // wait for Arduino Serial Monitor to open
      Serial.println("AltSoftSerial Test Begin");
      altSerial.begin(9600);
      altSerial.println("Hello World");
    }

    void loop() {
      char c;

      if (Serial.available()) {
        c = Serial.read();
        altSerial.print(c);
      }
      if (altSerial.available()) {
        c = altSerial.read();
        Serial.print(c);
      }
    }

I just receive the menssage "AltSoftSerial Test Begin", so the problem may be the serial port?

  [1]: http://duinopeak.com/index.php?route=product/product&product_id=101
  [2]: https://i.stack.imgur.com/qOFPC.png
  [3]: https://i.stack.imgur.com/sxjT8.png

body:
The comments in the AltSoftSerial Test say that you have to connect the GPS to pins 8 (RX for GPS TX) and 9 (TX for GPS RX).  Your shield does not have jumpers for those pins, but you could use a jumper wire to connect any of the TX pins (0-7) to Arduino pin 8 (on the edge of the shield).

I would also recommend looking at my [NeoGPS](https://github.com/SlashDevin/NeoGPS) library.  It's smaller, faster, more accurate and more reliable than all other GPS libraries.  Even if you don't use it, there are lots of tips on the Troubleshooting page.

Be sure to read about [choosing a serial port](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Installing.md#2-choose-a-serial-port) for the GPS device.  That's especially important.  In your case, you could use pins 0 and 1.  `SoftwareSerial` is the worst choice and is NOT recommended.

There is also an NMEASDlog example.  Unlike examples from other libraries, the NeoGPS examples will reliably work at high update rates and with slow SD cards.

NeoGPS is also available from the Arduino IDE Library Manager, under the menu **Sketch -> Include Library -> Manage Libraries**.


message:
Conncet Bluetoth module HC-05 to Arduino Uno Using UART Usb to enter in AT command

I have connected Arduino Rx(pin 0) to Bluetooth module Rx pin. Tx od Arduino to Tx of Bluetooth . I am able to send command to Bluetooth module using Serial Monitor of Arduino on my PC.

I have uploaded the empty code in Arduino.

I want to know why we connected Tx to Tx and Rx to Rx i.e one to one connection?

If I send command "AT" from my PC using serial Monitor of Arduino , How is it flowing to Bluetooth module.

Why not we connect Rx to Tx pin in AT Mode of Bluetooth module?

Pls explain using diagram.

body:
By using SoftSerial you can connect the HC-05 module to another pin than D0 and D1. Example connect HC-05 to D2 and D3 and define SoftSerial to use D2 and D3.

    ---------                        -----------                        ------
    | HC-05 +---(SoftSerial)---(D2/3)+ Arduino +(D0/1)---(Serial USB)---+ PC |
    ---------                        -----------                        ------


message:
LED matrix question light up H or 4

Just a basic query;

On my understanding of LED Matrix's, The following would light up 4 LEDs.

But what if I only wanted to light up just 3 of those LEDs? The circuit still needs the same inputs, since power will continue across all columns/rows

Thanks

Tom

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

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

body:
Multiplexing is the answer.

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

If you want to, as an example, light up only LEDS 1, 3 and 4, you will:

  * activate line A
  * activate line X
  * de-activate line X
  * de-activate lines A and B (yes, B was not active)
  * activate line A and B
  * activate line Y
  * de-activate line Y
  * de-activate lines A and B
  * start again from top

Do this so that the loop takes less than 10 milliseconds and you are actually refreshing the entire matrix at 100Hz, fast enough to trick the eyes of any human being as if the LEDs 1,3 and 4 are lighted up at the same time: [_persistence of vision_][2] is your friend.

  [1]: https://i.stack.imgur.com/wHWwJ.png
  [2]: https://en.wikipedia.org/wiki/Persistence_of_vision


body:
This is very simple. You can turn on each LED one at a time and repeat this over and over again. The easiest way of achieving this is to put this code in the loop section.

> Persistence of vision is defined as "the retention of a visual image for a short period of time after the removal of the stimulus that produced it" - [dictionary.com][1]

Even though the LED is on for only 1/3 of the time, it is fast enough that the human eye will not be able to tell that each LED turns off. Hence the viewer sees 3 LEDs on at the same time.

This allows any combination of LED patterns in your LED matrix.

7-segment displays also use this technique. You probably have some in a microwave or DVD player that you never realized that they were cycling through each digit, using persistence of vision.

**Resources:**
http://www.circuitstoday.com/interfacing-8x8-led-matrix-with-arduino (recommended)
http://tronixstuff.com/2013/10/11/tutorial-arduino-max7219-led-display-driver-ic/
https://playground.arduino.cc/Main/LEDMatrix
http://forum.hobbycomponents.com/viewtopic.php?f=43&t=1489

  [1]: http://www.dictionary.com/browse/persistence-of-vision


message:
What happens if I don't use a relay for 5V pump

I am trying to build an automatic watering system by following some examples. However, I don't have all the components for the entire system, therefore I have built it in Fritzing using only the components that I have (see scheme below):

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

I didn't build the physical version yet, because I am not sure that such a system would work without burning anything. In many examples, people connect the pump to a [Relay Module][2], but since I don't have it yet, I would like to build it like this until I set up the watering system.

Can anyone help me understand why a relay would make it better or worse?

P.S. I have a JPC-3F relay, but I can see that the Relay Module contains multiple components. Is it possible to add the JPC relay to the pump without having the entire Relay Module? Would I need extra components for that?

Thank you!

EDIT: Thanks to the answer from ratchet freak, I have added resistances and a transistor. It works fine, but the same question stands. Do I still need a relay in this case?
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/tyo8p.png
  [2]: http://www.etechpk.net/shop/relays-interface-module/4038/
  [3]: https://i.stack.imgur.com/eFAvF.jpg

body:
You should put a resistor in series with the led to limit the current.

The IO pins cannot source enough current to run the pump without damaging themselves. That's why you need a buffer of some kind.

The extra components in the relay module are a transistor to do the actual switching and a reverse-biased flyback schottky diode in parallel with the relay coil. The flyback diode is required to absorb the voltage spike generated by the coil getting switched off and acting like an inductor.

You can use a transistor to switch the motor directly assuming you can find one that can handle the current draw. If you do then you absolutely will need a flyback diode on the motor to avoid damage to the transistor.


body:
The relay have a coil resistance of 70 ohm for the 5 Volt version.

Ohms law, U = I x R

I = U/R = 0.071 Ampere, and now you have to find out, can an Arduino I/O pin drive a load of 71 mA? If not you have to add a driver aka most commonly a transistor.

And now you should ask yourself, can I drive the motor directly with a transistor driver and skip the relay? So do you have any data on the pump?

And if you look at the datasheet for IRF520, fig 3 and fig 4 have the data for planning if it will work or not.

Ref.: https://www.infineon.com/dgdl/irf520npbf.pdf?fileId=5546d462533600a4015355e340711985


body:
this is not an answer to the question you asked, but you need to understand this:

generic DC relay advice. Use commutating diodes. this is not a special kind of diode, it is a particular use of a generic diode. you want 2:

one across the coil, reversed biased - cathode to +VDC. The coil throws a huge spike of negative DC when power to the coil is cut and the magnetic field collapses. this diode eats that spike

second one from the load to ground, reverse biased. this eats any spike from the load to ground - the fat blue arc you see when you disconnect a load by yanking the wire

https://www.allaboutcircuits.com/textbo ... -circuits/
https://www.allaboutcircuits.com/textbo ... ing-diode/
https://en.wikipedia.org/wiki/Flyback_diode
G


message:
How important is the INT pin of the MPU6050 (GY-521)?

I want to wire multiple MPU6050 (at least 16 of them) to an arduino UNO for development (then nano for production). So I first started wiring one MPU6050 to an arduino like shown on the diyhacking website or in the picture below:
[![MPU6050 wired to Arduino Uno ][2]][2]
as you can see in the picture above the INT pin is used.
I then wearched for a way to wire multiple MPU6050 to an arduino using a multiplexer and I found a way on horizonlab's website or see the picture below:
[![enter image description here][4]][4]
As you can see in the second picture the INT isn't used at all. I'd like to know how important it is and what I'm missing out by not using it.

  [2]: https://i.stack.imgur.com/BBBmU.png
  [4]: https://i.stack.imgur.com/YUO7b.png

body:
The `INT` is the interrupt signal, usually open-drain output and you can connect many of them to the single `MCU` interrupt line (but you have to check all devices which ones are ready). The `LOW` level from `MPU` device signalize that data are ready (conversion was finished). So you don't have to periodically read status register to find it out (no polling is necessary).

In short, using `INT` is optional.


message:
Referencing Serial output

I'm confused with what I'm reading.

I have Serial communicating with my PC (USB) and SoftwareSerial over RS485 to a remote PC. I don't want to duplicate all of my print statements to be able to send output to either (or both) terminals. What I want to do is have a single set of print statements (think of a list of error messages) and then be able to output a message to either Serial or SSerial depending on which needs it. Does this make sense?

body:
Almost all of those things you do which involve functions like print, println, and write all derive from the Print class.  You could have an array of Print objects and print to whichever you like.

    Print* outs[] = {&Serial, &Serial1, &mySoftSerial};

    //  Later somewhere in code:

    outs[0]->println("This prints to Serial");
    outs[1]->println("This prints to Serial1");
    outs[2]->println("This prints to mySoftSerial");

    for(int i = 0; i < 3; i++){
      outs[i]->println("This prints to all 3.  You could even make this bit a function");
    }


message:
ESP8266 blink sketch not blinking LED

After flashing the blink sketch to the ESP8266, I removed all the unnecessary wires from flashing - and my setup to try and run the sketch looks like this:

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

Something to note about flashing - it would take anywhere from 10-50 tries before it would flash successfully, the other times it just failed to upload and spit out the `espcomm` failure to connect message, or it got halfway through the upload and quit. This is the only clue to me that maybe my board is just bad, and it won't be able to run any sketch - I ordered another ESP8266, but I'm still wondering if I could be doing something wrong, it seems fairly straight forward, and I have done a lot of research about this up until this point. This is my first arduino project, other than the starter projects.

Also not represented in the diagram are the female to male jumper cables I am using to connect to the ESP8266. Those connect to the breadboard, and then I plug another wire into the breadboard on the same row to attach it to what it needs to be attached to. I figure none of this stuff matters - as long as it is powered (red LED) it should be working.

Any ideas why the onboard LED isn't blinking? Or is the sketch not running at all? Does the upload problem matter...could it be producing a false positive result? The only other idea I have where something could be different is an output capacitor for the voltage regulator, I have been told that a 10mF capacitor is what I would use (but I have also been told it doesn't matter...and neither does the filter capacitor, I just put it in anyway).

CODE (straight from Arduino IDE / ESP8266 examples):

    /*
     ESP8266 Blink by Simon Peter
     Blink the blue LED on the ESP-01 module
     This example code is in the public domain

     The blue LED on the ESP-01 module is connected to GPIO1
     (which is also the TXD pin; so we cannot use Serial.print() at the same time)

     Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
    */

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                        // but actually the LED is on; this is because
                                        // it is acive low on the ESP-01)
      delay(1000);                      // Wait for a second
      digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
      delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
    }

Mike pointed out my regulator matters (because of dropout voltage) - I am using this one:

http://www.nteinc.com/specs/1900to1999/pdf/nte1904.pdf

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

body: The ESP8266 is power hungry, the Arduino may not have enough output current to power it.  Also, which voltage regulator you're using matters, as some have higher dropout than others.


body:
Here's how you test your voltage regulator setup:

1. Disconnect the ESP8266.
2. Connect a 10 ohm 1 W (or higher) resistor across the output of the v-reg.  One end goes to the output, the other goes to ground.
3. Measure the voltage across the resistor.  If it stays regulated close to the expected 3.3V, then you're fine.  If not, then this setup can't supply enough current for the ESP8266.


body: Some ESP8266 - V01 boards won't blink integrated led (only works with GPIO2), so connect it to a resistor (~150 ohms), in series with an external led to ground. I don't know why... is just the way that it is...


message:
Temperature Controlled fan using arduino project regarding - LCD not displaying anything

I have connected the circuit as per the diagram below and I have got the LCD to display boxes and nothing else. What could be wrong here? Please help!

Circuit diagram below -

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

Code as follows -

<!-- language: lang-cpp -->

    #include<DHT11.h>
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
    #define dht11pin 12
    dht11 DHT11;
    #define pwm 9
    byte degree[8] =
    {
      0b00011,
      0b00011,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000
    };
    void setup()
    {
      lcd.begin(16, 2);
      lcd.createChar(1, degree);
      lcd.clear();
      lcd.print("   Fan Speed  ");
      lcd.setCursor(0, 1);
      lcd.print("  Controlling ");
      delay(2000);
      analogWrite(pwm, 255);
      lcd.clear();
      lcd.print("Our Project ");
      delay(2000);
    }

    void loop()
    {
      DHT11.read(dht11pin);
      int temp = DHT11.temperature;
      lcd.setCursor(0, 0);
      lcd.print("Temperature:");
      lcd.print(temp);
      lcd.write(1);
      lcd.print("C");
      lcd.setCursor(0, 1);
      if (temp < 26 )
      {
        analogWrite(9, 0);
        lcd.print("Fan OFF  ");
        delay(100);
      }
      else if (temp == 26)
      {
        analogWrite(pwm, 51);
        lcd.print("Fan Speed: 20%   ");
        delay(100);
      }
      else if (temp == 27)
      {
        analogWrite(pwm, 102);
        lcd.print("Fan Speed: 40%   ");
        delay(100);
      }
      else if (temp == 28)
      {
        analogWrite(pwm, 153);
        lcd.print("Fan Speed: 60%   ");
        delay(100);
      }
      else if (temp == 29)
      {
        analogWrite(pwm, 204);
        lcd.print("Fan Speed: 80%    ");
        delay(100);
      }
      else if (temp > 29)
      {
        analogWrite(pwm, 255);
        lcd.print("Fan Speed: 100%   ");
        delay(100);
      }
      delay(3000);
    }

I used the default LiquidCrystal.h library for this project. Is that wrong?

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

body:
Your constructor doesn't match your wiring:

    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

You have:

    RS = 7
    E = 6
    D4 = 5
    D5 = 4
    D6 = 3
    D7 = 2

Yet your wiring has:

    RS = 2
    E = 3
    D4 = 4
    D5 = 5
    D6 = 6
    D7 = 7

I.e., completely backwards.

The constructor prototype is:

    LiquidCrystal(rs, enable, d4, d5, d6, d7)

Yet you seem to have chosen to ignore (or misunderstand) that.

Instead you need to specify your pins *correctly*:

    LiquidCrystal(2, 3, 4, 5, 6, 7);

Also, as a side note, you don't have a ground connection to that little 9V circuit off to one side - so you will never be able to control it.  [Read this.](https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/)


message:
SIM900A showing Starting modem test...ERROR, no modem answer. Checking IMEI...Modem's IMEI: 0

___
**Edit:**

Solution can be found [**HERE**](https://arduino.stackexchange.com/a/44981/26037)
___
I am trying to interface Simcom **SIM900A** GSM *(SIM900a Mini DEV Board v3.9.2)* and I tryed interfacing it with **Arduino UNO**. I have connected as:

**Pins:**

    SIM900A - Arduino
    =================
    VCC     - VDC (+5V)
    GND     - GND
    5VR     - Connect to Arduino TX (Pin 1)
    5VT     - Connect to Arduino RX (Pin 0)

**Power Supply (External):**

    5V 2A

**Problem**
When I upload sketch of:

    Example > GSM > TestModem:

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

**Other info:**

- By supplying `5V, 2A` the `SIM900A` `Power LED` `ON` continuesly and `Signal LED` `blink with certain period of time` which mean I am okay with signal.

- I connected SIM900A and Arduino with `Male to Male` + `Female to Female` as I don't have `Male to Female` wires. I tested the wires with Multimeter and it's prefectly working.

- I tested uploading other sketches of sending sms but not successful. Note that, I have load + free sms on SIM.

- Power supply is actually Adapter *(no transformer but circuit)* with output of `5.1 Volts`

My previous post can be checked [**HERE**](https://arduino.stackexchange.com/questions/44599/sim900a-mini-modem-imei-0-help-with-tx-rx-pins)

**PS:**

Yesterday just for a minute I noted: Both LEDs *(Power + Signal)*  of SIM900A were `blinking at same time`. But then by restarting it gets Okay again.

Please help. I am likely to die becuase of tension.

body:
___

**Note:**

Detailed Solution can be found [**Here**](https://arduino.stackexchange.com/a/44981/26037)
___

**Excerpt:**

My Pins connections were wrong, it should not be: `0` and `1` it should be `2` & `3`

Also `SoftwareSerial.h` is not working with `SIM900A`

**Pins:**

All connections should be like this:

    SIM900A - Arduino
    =================
    VCC     - VDC (+5V)
    GND     - GND
    5VR     - Connect to Arduino TX (Pin 3)
    5VT     - Connect to Arduino RX (Pin 2)

Details [**Here**](https://arduino.stackexchange.com/a/44981/26037)


message:
Arduino port grayed out for Fake Board with CH340

I have downloaded and used Arduino IDE v1.8.4 from official site (needs no install) for windows10, and connected my random board with a ch340, but it's LED is only blinking and I can't select the port (ie. it's grayed).

I did test all USB ports and restarted my laptop but that didn't work!

I tried to install 1.6.9 IDE that I had before, but again the port option is unselectable!

This is my board:
http://uupload.ir/files/xgv_uno.jpg

body:
Simplest possible thing would be that you do not have CH340g driver installed and you should try installing it first; These boards use CH340 for usb to serial and they need the driver to be installed; Please give it a try by getting the driver from the following link http://www.wch.cn/download/CH341SER_EXE.html or any other reliable source if there is any problem with the link;

If the board is not recognized even after that, it could be a bad USB port or a bad USB cable or even a board with the CH340 chip dead;


message:
How to connect a simple wall switch to arduino GPIO

I am trying to create a smart doorbell, but my problem is that doorbell makes ring any time when nobody touch the button.

I think that the problem is caused for the incorrect way to connect the analog wall button to arduino GPIO.

Basically my wiring diagram is:

Analog Input (A0) to 1 pin of the button.
Ground of the Arduino (GND) to the other pin of the button.

When the button is pressed, the circuit is closed, and doorbell makes ring!

But surely this is not the way to connect a button on the wall because the doorbell sounds on its own.

I leave a picture of the button
[![nk][1]][1]

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

body:
You need to have a pull-up resistor, see circuit below.

You do not need to connect it to an Analog pin, but a digital pin. Without a pull-up or pull-down resistor, the voltage on the input pin "floats" anywhere, and can give false triggers. This circuit *forces* the pin to either be 5V or 0V.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/Rotuk.png)

<!-- End schematic -->


body:
jose can u c is absolutely right, you need a pullup. No need to change your wiring however: the Arduino has built-in pullups on all the inputs. You just have to activate them:

    const uint8_t buttonPin = A0;  // or any other pin for that matter

    void setup()
    {
        pinMode(buttonPin, INPUT_PULLUP);
    }


message:
Avrdude Verification Error while flashing Arduino Mega code

I'm working with an Arduino Mega 2560 and am getting the following error at compile time:

> avrdude: verification error, first mismatch in byte 0x0000 0x14! =
> 0x25 avrdude: verification error; content mismatch

I've already changed the COM port and also restarted an IDE.

body:
I have made Jot's comment into an answer in the hope that it helps someone.

----------

First mismatch in byte 0x0000. [This is] the first byte that goes wrong. That means that not even a single byte passes the verification.

Perhaps the cause is one of these:

1. A cheap clone with a bad bootloader.
2. An old bootloader.
3. A bug, perhaps a bug with the size of the code or ram, for example the code at the border of 32k or 64k.
4. Maybe the voltage of the Arduino board is too low. Measure it. It must be above 4.5V.
5. Maybe a bad USB cable.
6. Wrong USB driver.
7. Board is too cheap and is missing decoupling capacitors.


message:
Not sure why eeprom isn't reading back correctly

I'm new to saving data on eeprom and I'm obviously doing something wrong but I'm not sure what.  I have one program which both writes to and reads the internal eeprom on a attiny85 and this seems to work.  However when I try to use this program to write and then remove the power from the attiny, then reprogram it with another program to read the eeprom it gives values of -1 for time and NAN for temperature.

My program which works is as follows, the program to read the eeprom only is the same however I deleted all the sections which write.  If you want me to add that program let me know.

I am using at attinyavr programmer from sparkfun and I have connected pins 3 & 4 on the attiny to an arduino uno which is connected to the serial monitor so that I can see the output (described here:  http://www.instructables.com/id/Easy-ATTiny-Serial-Communication-with-Tiny-AVR-Pro/#CP78RMAJ76GI6JQ)

Feel free to direct me to another answer if someone else has had the same problem, at the moment I think I will figure this out eventually but I suspect it will take me a few days so thought I would ask hopefully it's obvious to someone else.

(I'm aware that the time won't be correct since it should be unsigned long not an int, was just changing it round to test if that was the problem which it seems not to be).

Any help is really appreciated!!! Thanks :)
    /*

    ATTINY85 pin 3 -> Arduino Uno pin 0
    ATTINY85 pin 4 -> Arduino Uno pin 1
    Program choose 1MHz clock
     */

    #include <EEPROM.h>
    #include <SoftwareSerial.h>
    // Definitions
    #define rxPin 3     // Make pin 3 on the
    #define txPin 4

    SoftwareSerial mySerial(rxPin, txPin);

    int currentTime;
    int getTime;

    int sensorPin = 7; // This is the 7th pin on the ATtiny85,
                             // it is an analog input when reading as digital
    call it 7? analogpintochannel function
                              // (On the HLT tutorial it is labelled as Pin2: Analog input 1, SCK )
    float temperature = -500.00f;     // Create a new float called temperature and give it the value -500 to start with
    float getTemperature = -500.00f;
    int eepromAddress = 0;       // initialize variable for position in eeprom to store data collected
    int getEepromAddress = 0;

    // the setup routine runs once when you press reset:
    void setup() {
      pinMode(sensorPin, INPUT);    // make pin 7 on the ATTiny an input pin
      mySerial.begin(9600);         // begin software serial at rate of 9600

    }

    // the loop routine runs over and over forever:
    void loop() {

      static int countDataCollected = 0;  // initialize a count variable to count the data collected, static int should set to 0 only first time, second time loop goes round it shouldn't reset to 0

      if (countDataCollected==0) delay(90000); // put delay here so it gives me time to load the read eeprom program if required before it changes the eeprom in case that was the problem.

      if((countDataCollected>=0) and (countDataCollected < 10)) {

        currentTime = millis();
        temperature = analogRead(sensorPin)*5.0/1024.0;  // read value on pin 7, multiply it to find temperature
        temperature = temperature - 0.5;
        temperature = temperature / 0.01;

        mySerial.print("\n\nData number: ");
        mySerial.print(countDataCollected);
        mySerial.print("\tTime: ");
        mySerial.print(currentTime);
        mySerial.print("\tTemperature: ");
        mySerial.print(temperature);
        mySerial.print("\tCurrent eeprom address: ");
        mySerial.print(eepromAddress);
        mySerial.print("\t");
        mySerial.print(getEepromAddress);

        EEPROM.put(eepromAddress, currentTime);
        EEPROM.get(getEepromAddress, getTime);
        mySerial.print("\tGot time: ");
        mySerial.print(getTime);

        eepromAddress = eepromAddress + sizeof(currentTime);
        getEepromAddress = getEepromAddress + sizeof(getTime);
        mySerial.print("\teeprom address: ");
        mySerial.print(eepromAddress);
        mySerial.print("\t");
        mySerial.print(getEepromAddress);

        EEPROM.put(eepromAddress, temperature);
        EEPROM.get(getEepromAddress, getTemperature);

        eepromAddress = eepromAddress + sizeof(temperature); //Move address to the next byte after float 'myfloat'.
        getEepromAddress = getEepromAddress + sizeof(getTemperature);
        mySerial.print("\tGot temperature: ");
        mySerial.print(getTemperature);
        mySerial.print("\teeprom address: ");
        mySerial.print(eepromAddress);
        mySerial.print("\t");
        mySerial.print(getEepromAddress);
        mySerial.println();

        }

      // wait two seconds so as not to send massive amounts of data
      delay(2000);
      countDataCollected=countDataCollected+1;

      mySerial.print("\n\nNext data number =");
      mySerial.print(countDataCollected);
    }

body:
Fixed by resetting the attiny85 fuse to stop the EEPROM being cleared when the attiny was reprogrammed.

As far as I understand (I am a newbie at AVR programming so may be wrong)

The arduino bootloader (in the Arduino IDE) sets the attiny fuses.  One of the fuses that it sets (also the attiny85 default setting) clears the EEPROM when reprogramming.  To see how the bootloader is setting the fuses to you can turn on verbose comments in the Arduino IDE, and run the bootloader. When I ran the bootloader it set the fuses as follows: pattiny85 -cusbtiny -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m

i.e. arduino bootloader settings,
     efuse: 0xff,
     hfuse: 0xdf (need to change to d7),
     lfuse: 0xe2 (affects the clock),

You can use a fuse calculator (http://www.engbedded.com/fusecalc/)
 to determine how to change the fuse settings so the the EEPROM is not cleared.  (In the fuse calculator tick the box for "Preserve EEPROM memory through the chip erase cycle, EESAVE=0").  When the box is ticked the hfuse setting is D7 rather than DF

Also note that the bootloader in Arduino sets the lfuse to 0xe2, this is different from the default (it affects the setting 'Divide clock internally by 8' if 0xe2 is used it's an 8Mhz clock, the default prior to loading the boatloader is 1Mhz). Noting this because I initally reset everything to default and then had clock problems.

The hfuse can be set to d7 by downloading and running the AVR programming software https://sourceforge.net/projects/winavr/ and then setting the fuse using avrdude in a command window.
(more information on AVR setting fuses here http://www.ladyada.net/learn/avr/index.html)

I ran avrdude in a command window with the instruction:
avrdude -c usbtiny -p attiny85 -U hfuse:w:0xd7:m

("-c usbtiny" specifies the programmer used so this may vary, the attiny was connected to my computer USB port using the sparkfun attiny AVR programmer).


message:
Water flow sensor unable to get readings

I connected my "arduino(nano)" to "water flow sensor" and wrote a code which simply prints the readings like 0-1023 and tested it. First i got the readings but now i'm not getting it.

My code looks something like this.

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

    void loop(){
     int vla=analogRead(2);
     Serial.println(vla);
     delay(1500);
    }

and my connection.

> Sensor to Supply module

>Vcc -->  5v

>Gnd -->  Gnd

> Sensor to Arduino(Nano)

> Sig --> D2

body:
>Sensor to Arduino(Nano)
Sig --> D2

Your connections are wrong.

    int vla=analogRead(2);

is reading from analog channel 2, which is pin A2 on your Nano, not D2

D2 is not an analog pin and thus you can't use it with `analogRead()`.


message:
Can I use my Arduino nano to upload sketch in Uno's ATmega328p chip?

I can not upload sketch to my UNO directly. My ATmega16U2 doesn't work.But the Atmega328P processor still work.
 I have an arduino nano lying around. Can I use it to upload sketches to Atmega328P directly.
Thanks in advance

body: Yes. You can. Either as a USB to UART adaptor and use the Uno's bootloader as you would with any bootloader-enabled breadboard Arduino, or as an Arduino ISP to program the chip directly through the ICSP pins as you would when putting the bootloader onto a blank chip.


message:
Communicating to arduino as fast as real-time

I'm trying to control some pneumatic cylinders with arduino. I want to do the calculations on pc and then send the command to arduino to control the air flow to pneumatic cylinders. It's very important that arduino receive these commands super fast (in real time if it's possible) so that I can control air flow in millisecond precision.

What is the fastest way to communicate to arduino (Read and write). I tested serial communication and it's very slow in compare to real-time. Is there any specific settings for serial communications that i need to do to increase it's speed? Should I use LAN connection? Or maybe I should use for example Arduino YUN with an OS?

body:
Going over USB will add about a millisecond of jitter to your data in both the sensing and command directions.  Using a part with direct USB rather than then needing to go through a serial link from USB chip to processor could help limit what is added on top of that, but it will still be there.  If you could get a USB high speed solution that would reduce this as the polling interval is shorter, but there are few such solutions for simple microcontrollers.  Ultimately, USB is meant to move a lot of data in a reasonable amount of time - it is *not* designed to move small messages promptly.

True realtime systems put the processing and the actuation in tightly connected local circuitry. With the increasing isolation of PC processors from external I/O by multiple layers of intermediate architecture on the chip and motherboard, you see very little realtime use of PCs today.  An embedded board with a decent processor and good direct I/O (Beaglebone, maybe the Linux side of a Yun or comparable) would be better, but be aware that multi-tasking operating systems like Linux or Windows are fundamentally in conflict with real-time performance - it takes very complex hacks to make that work, for example running a realtime scheduler directly on the hardware  and having it run an ordinary operating system as a low priority task.

The architecturally cleanest solutions would be to find a way to fit your calculations on a fast single processor - in the realm of Arduino-style solutions perhaps one of the latest in the Teensy series.  Beyond that you are really out of the realm where this could be considered an Arduino question - trying for example to run a realtime scheduler on the Linux half of a Yun is really not related to "Arduino" at all.

One thing that is not clear however is if your system needs to *react* in real time, or merely to *sequence* with precise timing.  Mere sequencing is a far easier problem, as you can send the data a bit in advance of need and hold it in a buffer, so that communication latency doesn't delay operations.  A 3d printer could be an example of this - the really complex  calculations are done on a PC, then commands are drip-fed a bit in advance of need to a simpler executive traditionally running on a repackaged Arduino Mega, and that moves the motors with sub-millisecond pulse precision.  Given that there are no realtime inputs to the calculations, their results can also be stored on an SD card for use months later with no PC connection at all.  If your need does reduce to such pure non-reactive sequencing then things are a lot simpler; if it doesn't, then the rest of the explanation here applies.