message:
What is wrong with my state machines?

My goal is to make an automatic gate and garage door, and it has a servo as the lock mechanism on the gate, and alarm systems that notify when the gate or garage door is open too long, more than the interval (in my case 10 seconds) through a buzzer.

It also uses:

- Bluetooth to send a command (which is `readChar`) to open/close the gate and open/close the garage.
- 4 limit switches (2 switched located at both end of gate and garage to stop its movement).

I want that the gate and garage doors can be opened/closed at the same time, so there are 2 state machines. And the alarm system (if it is activated) will stop when the gate reaches limit switch 1, and the garage reaches limit switch 3.

However with my current code (compiled), I get:

- The first state machine (stateGate) can open and close the gate, but the buzzer does not buzz when it exceeds the limit.
- The second state machine (stateGarage) did not do anything/did not operate.

Can someone point out/correct what is the mistake? Because I can't seem to find what is wrong. Thank you in advance!

Here is my current full code:

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

    #include <Servo.h>

    Servo Servokey;

    // Motor for Gate (MotorA)
    const byte IN1 = 9;
    const byte IN2 = 8;
    const byte EnableMotorA = 6;

    // Motor for Garage Door (MotorB)
    const byte IN3 = 4;
    const byte IN4 = 3;
    const byte EnableMotorB = 5;

    const byte LimitSwitch1 = A1;
    const byte LimitSwitch2 = A2;
    const byte LimitSwitch3 = A3;
    const byte LimitSwitch4 = A4;

    const int piezoPin = 10; // piezo for the alarm system

    int StateGate;
    int StateGarage;
    boolean gateClosed = false;
    boolean garageClosed = false;

    unsigned long GateMillis; //will hold the timer for Gate
    unsigned long GarageMillis; // will hold the timer for Garage
    unsigned long interval = 10000;

    void setup() {
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(EnableMotorA, OUTPUT);

      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);
      pinMode(EnableMotorB, OUTPUT);

      pinMode(LimitSwitch1, INPUT);
      pinMode(LimitSwitch2, INPUT);
      pinMode(LimitSwitch3, INPUT);
      pinMode(LimitSwitch4, INPUT);

      Servokey.attach(11); // lock mechanism for Gate
      Servokey.write(70);

      unsigned long GateMillis = 0; //will hold the timer for Gate
      unsigned long GarageMillis = 0;

      Serial.begin(9600);
    }

    void loop() {
      byte readChar = 0;
      if (Serial.available() > 0)
        readChar = Serial.read();
      stateGate(readChar);
      stateGarage(readChar);
    }

    void stateGate(byte readChar) {
      static enum { StateGate_Idle, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Close, StateGate_Alarm} StateGate;
      switch (StateGate) {
        case StateGate_Idle:
          { // If we received a valid command, start the operation
            if (readChar > 0) {
              switch (readChar) {
                case 'A':
                  StateGate = StateGate_Opening;
                  break;
                case 'B':
                  StateGate = StateGate_Closing;
                  break;
                default:
                  // Here you can notify that there was a bad command
                  break;
              }
            }
          }
          break;
        case StateGate_Opening:
          Servokey.write(140);
          delay(50);
          digitalWrite(IN1, LOW);
          digitalWrite(IN2, HIGH);
          analogWrite(EnableMotorA, 250);
          StateGate = StateGate_Open;
          break;
        case StateGate_Open:
          if (digitalRead(LimitSwitch2)) {
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            GateMillis = millis();
            gateClosed = false;
            StateGate = StateGate_Idle;
          }
          break;
        case StateGate_Closing:
          digitalWrite(IN1, HIGH);
          digitalWrite(IN2, LOW);
          analogWrite(EnableMotorA, 250);
          StateGate = StateGate_Close;
          break;
        case StateGate_Close:
          if (digitalRead(LimitSwitch1)) {
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            Servokey.write(70);
            delay(50);
            gateClosed = true;
            StateGate = StateGate_Idle;
          }
          break;
        case StateGate_Alarm:
          if ((millis() - GateMillis) > interval && gateClosed == false) {
            tone(piezoPin, 5000);
            StateGate = StateGate_Idle;
          } else if (gateClosed == true) {
            StateGate = StateGate_Idle;
          }
          break;
        default:
          StateGate = StateGate_Idle;
          break;
      }
    }

    void stateGarage(byte readChar) {
      static enum { StateGarage_Idle, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Close, StateGarage_Alarm} StateGarage;
      switch (StateGarage) {
        case StateGarage_Idle:
          { // If we received a valid command, start the operation
            if (readChar > 0) {
              switch (readChar) {
                case 'C':
                  StateGarage = StateGarage_Opening;
                  break;
                case 'D':
                  StateGarage = StateGarage_Closing;
                  break;
                default:
                  // Here you can notify that there was a bad command
                  break;
              }
            }
          }
          break;
        case StateGarage_Opening:
          digitalWrite(IN3, LOW);
          digitalWrite(IN4, HIGH);
          analogWrite(EnableMotorA, 250);
          StateGarage = StateGarage_Open;
          break;
        case StateGarage_Open:
          if (digitalRead(LimitSwitch4)) {
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorA, 0);
            GarageMillis = millis();
            garageClosed = false;
            StateGarage = StateGarage_Idle;
          }
          break;
        case StateGarage_Closing:
          digitalWrite(IN3, HIGH);
          digitalWrite(IN4, LOW);
          analogWrite(EnableMotorA, 250);
          StateGarage = StateGarage_Close;
          break;
        case StateGarage_Close:
          if (digitalRead(LimitSwitch3)) {
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            garageClosed = true;
            StateGarage = StateGarage_Idle;
          }
          break;
        case StateGarage_Alarm:
          if ((millis() - GarageMillis) > interval && garageClosed == false) {
            tone(piezoPin, 5500);
            StateGarage = StateGarage_Idle;
          } else if (garageClosed == true)
            StateGarage = StateGarage_Idle;
          break;
        default:
          StateGarage = StateGarage_Idle;
          break;
      }
    }

I made another code like what @CodeGorilla had suggested, however it turned out that both state machines did not operate.... I think I am still missed out something

Here's the other code:

    #include <Servo.h>

    Servo Servokey;

    enum StateGate { StateGate_Idle = 0, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Closed, StateGate_Alarm, StateGate_Last };
    enum StateGarage { StateGarage_Idle = 0, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Closed, StateGarage_Alarm, StateGarage_Last };

    struct Data1
    {
      byte IN1;
      byte IN2;
      bool Enable;
      int NextState;

      Data1(byte in1, byte in2, bool enable, int nextstate)
           :IN1(in1), IN2(in2), Enable(enable), NextState(nextstate)
      {}
    };

    struct Data2
    {
      byte IN3;
      byte IN4;
      bool Enable;
      int NextState;

      Data2(byte in3, byte in4, bool enable, int nextstate)
           :IN3(in3), IN4(in4), Enable(enable), NextState(nextstate)
      {}
    };

    struct MotorData1
    {
      byte IN1;
      byte IN2;
      byte Enable;
      MotorData1(byte i1, byte i2, byte enable)
           : IN1(i1), IN2(i2), Enable(enable)
      {}
      void pinMode() const
      {
        :: pinMode(IN1, OUTPUT);
        :: pinMode (IN2, OUTPUT);
        :: pinMode (Enable, OUTPUT);
      }
      int Set(const Data1& data1) const
      {// Set the motors to the given state
        digitalWrite(IN1, data1.IN1);
        digitalWrite(IN2, data1.IN2);
        analogWrite(Enable, data1.Enable?250:0);
        return data1.NextState;
      }
    };

    struct MotorData2
    {
      byte IN3;
      byte IN4;
      byte Enable;
      MotorData2(byte i3, byte i4, byte enable)
           : IN3(i3), IN4(i4), Enable(enable)
      {}
      void pinMode() const
      {
        :: pinMode(IN3, OUTPUT);
        :: pinMode (IN4, OUTPUT);
        :: pinMode (Enable, OUTPUT);
      }
      int Set(const Data2& data2) const
      {// Set the motors to the given state
        digitalWrite(IN3, data2.IN3);
        digitalWrite(IN4, data2.IN4);
        analogWrite(Enable, data2.Enable?250:0);
        return data2.NextState;
      }
    };
    // Define the motors
    const MotorData1 MotorsA(9, 8, 6);
    const MotorData2 MotorsB(4, 3, 5);

    const byte LimitSwitch1 = A1;
    const byte LimitSwitch2 = A2;
    const byte LimitSwitch3 = A3;
    const byte LimitSwitch4 = A4;

    const int piezoPin = 10; // piezo for the alarm system

    StateGate CurrentGateState = StateGate_Idle;
    StateGarage CurrentGarageState = StateGarage_Idle;
    boolean gateClosed = false;
    boolean garageClosed = false;

    unsigned long GateMillis(0); //will hold the timer for Gate
    unsigned long GarageMillis(0); // will hold the timer for Garage
    unsigned long interval = 10000;

    void setup() {
        MotorsA.pinMode();
        MotorsB.pinMode();

        pinMode(LimitSwitch1, INPUT);
        pinMode(LimitSwitch2, INPUT);
        pinMode(LimitSwitch3, INPUT);
        pinMode(LimitSwitch4, INPUT);

        Servokey.attach(11); // lock mechanism for Gate
        Servokey.write(70);

        Serial.begin(9600);
    }

    void loop()
    {
        byte readChar = 0;
        if (Serial.available() > 0)
            readChar = Serial.read();
        stateGate(readChar);
        stateGarage(readChar);
    }

    void stateGate(byte readChar)
    {// Define the state machine
        static const Data1 stateData1[StateGate_Last] =
        {
              Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Idle
            , Data1(LOW, HIGH, true, StateGate_Open)  // StateGate_Opening
            , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Open
            , Data1(HIGH, LOW, false, StateGate_Closed)  // StateGate_Closing
            , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Closed
            , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Alarm
        };
    switch (CurrentGateState)
        {
            case StateGate_Idle:
            { // If we received a valid command, start the operation
                if (readChar > 0) {
                    switch (readChar) {
                    case 'A':
                        if (CurrentGateState != StateGate_Open)
                        {  // Prevent opening the gate if its already open
                            CurrentGateState = StateGate_Opening;
                        }
                        break;
                    case 'B':
                        if (CurrentGateState != StateGate_Closed)
                        {// Prevent closing the gate if its already closed.
                            CurrentGateState = StateGate_Closing;
                        }
                        break;
                    default:
                        // Here you can notify that there was a bad command
                        break;
                    }
                }
            }
            break;
        case StateGate_Opening:
            Servokey.write(140);
            delay(50);
            CurrentGateState = MotorsA.Set(stateData1[StateGate_Opening]);
            break;
        case StateGate_Open:
            if (digitalRead(LimitSwitch2))
            {
                CurrentGateState = MotorsA.Set(stateData1[StateGate_Open]);
                GateMillis = millis();
                gateClosed = false;
            }
            break;
        case StateGate_Closing:
            CurrentGateState = MotorsA.Set(stateData1[StateGate_Closing]);
            break;
        case StateGate_Closed:
            if (digitalRead(LimitSwitch1))
            {
                CurrentGateState = MotorsA.Set(stateData1[StateGate_Closed]);
                Servokey.write(70);
                delay(50);
                gateClosed = true;
            }
            break;
        case StateGate_Alarm:
            if ((millis() - GateMillis) > interval && gateClosed == false) {
                tone(piezoPin, 5000);
                CurrentGateState = StateGate_Idle;
            }
            else if (gateClosed == true) {
                CurrentGateState = StateGate_Idle;
            }
            break;
        default:
            CurrentGateState = StateGate_Idle;
            break;
        }
    }

    void stateGarage(byte readChar)
    {// Define the state machine
        static const Data2 stateData2[StateGarage_Last] =
        {
              Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Idle
            , Data2(LOW, HIGH, true, StateGarage_Open)  // StateGate_Opening
            , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Open
            , Data2(HIGH, LOW, false, StateGarage_Closed)  // StateGate_Closing
            , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Closed
            , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Alarm
        };
    switch (CurrentGarageState)
        {
            case StateGarage_Idle:
            { // If we received a valid command, start the operation
                if (readChar > 0) {
                    switch (readChar) {
                    case 'A':
                        if (CurrentGarageState != StateGarage_Open)
                        {  // Prevent opening the gate if its already open
                            CurrentGarageState = StateGarage_Opening;
                        }
                        break;
                    case 'B':
                        if (CurrentGarageState != StateGarage_Closed)
                        {// Prevent closing the gate if its already closed.
                            CurrentGarageState = StateGarage_Closing;
                        }
                        break;
                    default:
                        // Here you can notify that there was a bad command
                        break;
                    }
                }
            }
            break;
        case StateGarage_Opening:
            CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Opening]);
            break;
        case StateGarage_Open:
            if (digitalRead(LimitSwitch2))
            {
                CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Open]);
                GarageMillis = millis();
                garageClosed = false;
            }
            break;
        case StateGarage_Closing:
            CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Closing]);
            break;
        case StateGarage_Closed:
            if (digitalRead(LimitSwitch1))
            {
                CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Closed]);
                Servokey.write(70);
                delay(50);
                garageClosed = true;
            }
            break;
        case StateGarage_Alarm:
            if ((millis() - GarageMillis) > interval && garageClosed == false) {
                tone(piezoPin, 5000);
                CurrentGarageState = StateGarage_Idle;
            }
            else if (garageClosed == true) {
                CurrentGarageState = StateGarage_Idle;
            }
            break;
        default:
            CurrentGarageState = StateGarage_Idle;
            break;
        }
    }

body:
There a couple of places where you define variables which hide other variables. eg Line 27 is hidden by 48 for a little bit.  More importantly line 22 is hidden by 63 and this is probably why your state machine doesn't work.

As I said in my comment you could make life easier for yourself by refactoring it.  Most of the states have the same lines of code in, so by using a structure you can reduce the number of lines and hopefully the number of bugs.  I had a play a roughed out this to show what I mean.  (I have not compiled it, let alone run it, but it might be a starting point.

    Servo Servokey;
    // Global to prevent accidental variable declaration.
    static enum StateGate { StateGate_Idle = 0, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Closed, StateGate_Alarm, StateGate_Last };
    // Defines the state machines
    struct Data
    {
     byte IN1;
     byte IN2;
     bool Enable;
     int NextState;

     Data(byte in1, byte in2, bool enable, int nextState)
      : IN1(in1), IN2(in2), Enable(enable), NextState(nextState))
     {}
    };
    // Group the motor data to make things tidier
    struct MotorData
    {
     byte IN1;
     byte IN2;
     byte Enable;
     MotorData(byte i1, byte i2, byte enable)
      :IN1(i1), IN2(i2), Enable(enable)
     {}
     void pinMode() const  // Set the pin mode
     {
      ::pinMode(IN1, OUTPUT);  // Use the global pinMode not this function
      ::pinMode(IN2, OUTPUT);
      ::pinMode(Enable, OUTPUT);
     }
     int Set(const Data& data) const
     { // Set the motors to the given state
      digitalWrite(IN1, data.IN1);
      digitalWrite(IN2, data.IN2);
      analogWrite(Enable, data.Enable?250:0);
      return data.NextState
     }
    };
    // Define the motors
    const MotorData MotorsA(9, 8, 6);
    const MotorData MotorsB(4, 3, 5);

    const byte LimitSwitch1 = A1;
    const byte LimitSwitch2 = A2;
    const byte LimitSwitch3 = A3;
    const byte LimitSwitch4 = A4;

    const int piezoPin = 10; // piezo for the alarm system

    StateGate CurrentGateState = StateGate_Idle;  // It is best to initialise the variables.
    int StateGarage;
    boolean gateClosed = false;
    boolean garageClosed = false;

    unsigned long GateMillis(0); //will hold the timer for Gate
    unsigned long GarageMillis(0); // will hold the timer for Garage
    unsigned long interval = 10000;

    void setup() {
     MotorsA.pinMode();
     MotorsB.pinMode();

     pinMode(LimitSwitch1, INPUT);
     pinMode(LimitSwitch2, INPUT);
     pinMode(LimitSwitch3, INPUT);
     pinMode(LimitSwitch4, INPUT);

     Servokey.attach(11); // lock mechanism for Gate
     Servokey.write(70);

     Serial.begin(9600);
    }

    void loop()
    {
     byte readChar = 0;
     if (Serial.available() > 0)
      readChar = Serial.read();
     stateGate(readChar);
     stateGarage(readChar);
    }

    void stateGate(byte readChar)
    {// Define the state machine
     static const Data stateData[StateGate_Last] =
     {
        Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Idle
      , Data(LOW, HIGH, true, StateGate_Open)  // StateGate_Opening
      , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Open
      , Data(HIGH, LOW, false, StateGate_Closed)  // StateGate_Closing
      , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Closed
      , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Alarm
     };

     switch (CurrentGateState)
     {
      case StateGate_Idle:
      { // If we received a valid command, start the operation
       if (readChar > 0) {
        switch (readChar) {
        case 'A':
         if (CurrentGateState != StateGate_Open)
         {  // Prevent opening the gate if its already open
          CurrentGateState = StateGate_Opening;
         }
         break;
        case 'B':
         if (CurrentGateState != StateGate_Closed)
         {// Prevent closing the gate if its already closed.
          CurrentGateState = StateGate_Closing;
         }
         break;
        default:
         // Here you can notify that there was a bad command
         break;
        }
       }
      }
      break;
     case StateGate_Opening:
      Servokey.write(140);
      delay(50);
      CurrentGateState = MotorsA.Set(stateData[StateGate_Opening]);
      break;
     case StateGate_Open:
      if (digitalRead(LimitSwitch2))
      {
       CurrentGateState = MotorsA.Set(stateData[StateGate_Open]);
       GateMillis = millis();
       gateClosed = false;
      }
      break;
     case StateGate_Closing:
      CurrentGateState = MotorsA.Set(stateData[StateGate_Closing]);
      break;
     case StateGate_Closed:
      if (digitalRead(LimitSwitch1))
      {
       CurrentGateState = MotorsA.Set(stateData[StateGate_Closed]);
       Servokey.write(70);
       delay(50);
       gateClosed = true;
      }
      break;
     case StateGate_Alarm:
      if ((millis() - GateMillis) > interval && gateClosed == false) {
       tone(piezoPin, 5000);
       CurrentGateState = StateGate_Idle;
      }
      else if (gateClosed == true) {
       CurrentGateState = StateGate_Idle;
      }
      break;
     default:
      CurrentGateState = StateGate_Idle;
      break;
     }
    }

    void stateGarage(byte readChar) {
     static enum { StateGarage_Idle, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Close, StateGarage_Alarm } StateGarage;
     switch (StateGarage) {
     case StateGarage_Idle:
     { // If we received a valid command, start the operation
      if (readChar > 0) {
       switch (readChar) {
       case 'C':
        StateGarage = StateGarage_Opening;
        break;
       case 'D':
        StateGarage = StateGarage_Closing;
        break;
       default:
        // Here you can notify that there was a bad command
        break;
       }
      }
     }
     break;
     case StateGarage_Opening:
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      analogWrite(EnableMotorA, 250);
      StateGarage = StateGarage_Open;
      break;
     case StateGarage_Open:
      if (digitalRead(LimitSwitch4)) {
       digitalWrite(IN3, LOW);
       digitalWrite(IN4, LOW);
       analogWrite(EnableMotorA, 0);
       GarageMillis = millis();
       garageClosed = false;
       StateGarage = StateGarage_Idle;
      }
      break;
     case StateGarage_Closing:
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      analogWrite(EnableMotorA, 250);
      StateGarage = StateGarage_Close;
      break;
     case StateGarage_Close:
      if (digitalRead(LimitSwitch3)) {
       digitalWrite(IN3, LOW);
       digitalWrite(IN4, LOW);
       analogWrite(EnableMotorB, 0);
       garageClosed = true;
       StateGarage = StateGarage_Idle;
      }
      break;
     case StateGarage_Alarm:
      if ((millis() - GarageMillis) > interval && garageClosed == false) {
       tone(piezoPin, 5500);
       StateGarage = StateGarage_Idle;
      }
      else if (garageClosed == true)
       StateGarage = StateGarage_Idle;
      break;
     default:
      StateGarage = StateGarage_Idle;
      break;
     }
    }

EDIT ----------------

This code is a complete version of the code refactored to reduce the repetitive statements and try and minimise the number of potential bugs.  I have also removed one of the state functions, since apart form the lock and acting on different motors and switches they seemed to be the same.

    #include "Servo.h"

    Servo Servokey;

    enum State { State_Idle = 0, State_Opening, State_Open, State_Closing, State_Closed, State_Alarm, State_Last };

    struct Data
    {
     byte IN1;
     byte IN2;
     bool Enable;
     State NextState;

     Data(byte in1, byte in2, bool enable, State nextstate)
      :IN1(in1), IN2(in2), Enable(enable), NextState(nextstate)
     {}
    };

    struct MotorData
    {
     byte IN1;
     byte IN2;
     byte Enable;
     MotorData(byte i1, byte i2, byte enable)
      : IN1(i1), IN2(i2), Enable(enable)
     {}
     void pinMode() const
     {
      ::pinMode(IN1, OUTPUT);
      ::pinMode(IN2, OUTPUT);
      ::pinMode(Enable, OUTPUT);
     }
     State Set(const Data& Data) const
     {// Set the motors to the given state
      digitalWrite(IN1, Data.IN1);
      digitalWrite(IN2, Data.IN2);
      analogWrite(Enable, Data.Enable ? 250 : 0);
      return Data.NextState;
     }
    };

    /// Defines all the data for the gate or garage.
    struct Object
    {
     State   CurrentState;    // The current state of the object
     char   OpenCommand;    // The command to open the gate/garage
     char   CloseCommand;
     MotorData&  Motors;      // A reference to the motors object
     byte   LimitSwitchA;
     byte   LimitSwitchB;
     bool   LockObject;     // True if the object should be locked/ unlocked
     unsigned long OpenTime;     // The time the object was last opened.
     bool   IsClosed;     // True when the object is closed.
     Object(char o, char c, MotorData m, byte la, byte lb, bool lock)
      : CurrentState(State_Idle)
      , OpenCommand(o)
      , CloseCommand(c)
      , Motors(m)
      , LimitSwitchA(la)
      , LimitSwitchB(lb)
      , LockObject(lock)
      , OpenTime(0)
      , IsClosed(false)
     {}
    };

    // Define the motors
    const MotorData MotorsA(9, 8, 6);
    const MotorData MotorsB(4, 3, 5);

    const byte LimitSwitch1 = A1;
    const byte LimitSwitch2 = A2;
    const byte LimitSwitch3 = A3;
    const byte LimitSwitch4 = A4;

    const int piezoPin = 10; // piezo for the alarm system

    Object Gate('A', 'B', MotorsA, LimitSwitch1, LimitSwitch2, true);
    Object Garrage('C', 'D', MotorsB, LimitSwitch3, LimitSwitch4, false);

    unsigned long interval = 10000;

    /// Lock or unlock the lock.
    void LockGate(bool lock=true)
    {
     if (lock)
      Servokey.write(70);
     else
      Servokey.write(140);
     delay(50);
    }

    void setup() {
     MotorsA.pinMode();
     MotorsB.pinMode();

     pinMode(LimitSwitch1, INPUT);
     pinMode(LimitSwitch2, INPUT);
     pinMode(LimitSwitch3, INPUT);
     pinMode(LimitSwitch4, INPUT);

     Servokey.attach(11); // lock mechanism for Gate
     Servokey.write(70);

     Serial.begin(9600);
    }

    void loop()
    {
     byte readChar = 0;
     if (Serial.available() > 0)
      readChar = Serial.read();
     StateMachine(readChar, Gate);
     StateMachine(readChar, Garrage);
    }

    void StateMachine(const byte readChar, Object& objectData)
    {// Define the state machine
     static const Data stateData[State_Last] =
     {
      Data(LOW, LOW, false, State_Idle)  // State_Idle
      , Data(LOW, HIGH, true, State_Open)  // State_Opening
      , Data(LOW, LOW, false, State_Idle)  // State_Open
      , Data(HIGH, LOW, true, State_Closed)  // State_Closing
      , Data(LOW, LOW, false, State_Idle)  // State_Closed
      , Data(LOW, LOW, false, State_Idle)  // State_Alarm
     };
     switch (objectData.CurrentState)
     {
     case State_Idle:    // If we received a valid command, start the operation
      if (readChar > 0)
      {
       if (readChar == objectData.OpenCommand)
       {
        objectData.CurrentState = State_Opening;
       }
       else if (readChar == objectData.CloseCommand)
       {
        objectData.CurrentState = State_Closing;
       }
       else
       {
        // Here you can notify that there was a bad command
       }
      }
      break;
     case State_Opening:
      if (objectData.LockObject)
       LockGate(false);
      objectData.CurrentState = objectData.Motors.Set(stateData[State_Opening]);
      break;
     case State_Open:
      if (digitalRead(LimitSwitch2))
      {
       objectData.CurrentState = objectData.Motors.Set(stateData[State_Open]);
       objectData.OpenTime = millis();
       objectData.IsClosed = false;
      }
      break;
     case State_Closing:
      objectData.CurrentState = objectData.Motors.Set(stateData[State_Closing]);
      break;
     case State_Closed:
      if (digitalRead(LimitSwitch1))
      {
       objectData.CurrentState = objectData.Motors.Set(stateData[State_Closed]);
       if (objectData.LockObject)
        LockGate(true);
       objectData.IsClosed = true;
      }
      break;
     case State_Alarm:
      if ((millis() - objectData.OpenTime) > interval && objectData.IsClosed == false) {
       tone(piezoPin, 5000);
       objectData.CurrentState = State_Idle;
      }
      else if (objectData.IsClosed == true) {
       objectData.CurrentState = State_Idle;
      }
      break;
     default:
      objectData.CurrentState = State_Idle;
      break;
     }
    }

As before I can't test it, without righting myself a test harness and "it doesn't work" doesn't really help me know what the fault is.  One thing I did notice is the Alarm won't work.  This is because nothing ever puts it into that state, maybe the check to see if the alarm has been triggered should be in the idle state and if it occurs the state machine should move into the alarm state.

What I have tried to show you is if you are doing the same things repeatedly on different data then define the data outside of the function and reduce the amount of code you write.  You would never write these functions would you?

    int Add2and2 ()
    {return 2+2;}
    int Add2and3 ()
    {return 2+3;}
    int Add2and4 ()
    {return 2+4;}

But its often very difficult to spot that you are doing that in your own code.

If there is still something wrong, please describe what the fault is and I'll see what I can do.


sender: user

message:
Can't fetch data from server using arduino and esp8266

I am trying to fetch some data from my website using esp8266 and Arduino, with the help of WiFiEsp library, I have got data from the website but don't know how to save that data in an array or variable and use it, now I can only see received data on the serial monitor.

     #include "WiFiEsp.h"

    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(6, 7); // RX, TX
    #endif

    char ssid[] = "moto g";            // your network SSID (name)
    char pass[] = "hvats555";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    char server[] = "himalayavats.com";

    unsigned long lastConnectionTime = 0;
    const unsigned long postingInterval = 10000L;

    WiFiEspClient client;

    void setup()
    {
      // initialize serial for debugging
      Serial.begin(115200);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);

      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        while (true);
      }

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      Serial.println("You're connected to the network");

      printWifiStatus();
    }

    void loop()
    {
      // if there's incoming data from the net connection send it out the serial
    port
      // this is for debugging purposes only
      while (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if 10 seconds have passed since your last connection,
      // then connect again and send data
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();
      }
    }

    // this method makes a HTTP connection to the server
    void httpRequest()
    {
      Serial.println();

      // close any connection before send a new request
      // this will free the socket on the WiFi shield
       client.stop();

      // if there's a successful connection
      if (client.connect(server, 80)) {
        Serial.println("Connecting...");

        // send the HTTP PUT request
        client.println(F("GET /to_fetch/system_info.json HTTP/1.1"));
        client.println(F("Host: himalayavats.com"));
        client.println("Connection: close");
        client.println();

        // note the time that the connection was made
        lastConnectionTime = millis();
      }
      else {
        // if you couldn't make a connection
        Serial.println("Connection failed");
      }
    }

    void printWifiStatus()
    {
      // print the SSID of the network you're attached to
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

     // print the received signal strength
      long rssi = WiFi.RSSI();
      Serial.print("Signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

**Response from arduino(in serial monitor):-**

    [WiFiEsp] Initializing ESP module
    [WiFiEsp] Initilization successful - 1.3.0
    Attempting to connect to WPA SSID: moto g
    [WiFiEsp] Connected to moto g
    You're connected to the network
    SSID: moto g
    IP Address: 192.168.43.61
    Signal strength (RSSI):-372 dBm

    [WiFiEsp] Connecting to himalayavats.com
    Connecting...
    HTTP/1.1 200 OK
    Date: Fri, 05 Jan 2018 10:19:46 GMT
    Server: Apache
    ETag: "12c077d-12-55dc4cfa4fffd"
    Accept-Ranges: bytes
    Content-Length: 18
    Vary: User-Agent
    Connection: close
    Content-Type: application/json

    {"power" : "high"}      // <-- i wanna fetch this

**NOTE:- Whenever I try to add anything in loop function for example:-**

    int i = 0;
    while(client.avilable()){
        c = client.read();
        serverResponse[i] = c; // trying to save output in an array
        i++;
    }

**The module doesn't even fetch data from the server it keeps restarting itself.
Output from arduino after adding above code in loop funtion:-**

    [WiFiEsp] Initializing ESP module
    [WiFiEsp] Initilization successful - 1.3.0
    Attempting to connect to WPA SSID: moto g
    [WiFiEsp] Connected to moto g
    You're connected to the network

    [WiFiEsp] Initializing ESP module
    [WiFiEsp] Initilization successful - 1.3.0
    Attempting to connect to WPA SSID: moto g
    [WiFiEsp] Connected to moto g
    You're connected to the network

    [WiFiEsp] Initializing ESP module
    [WiFiEsp] Initilization successful - 1.3.0
    Attempting to connect to WPA SSID: moto g
    [WiFiEsp] Connected to moto g
    You're connected to the network

This repeating again and again

sender: assistant

body:
When Arduinos unexpectedly restarts it is usually because you have drawn too much power or have caused a segmentation error or BSOD in Windows terms.  You aren't drawing to much power, so I suspect you are accessing elements of the array outside those that you should be.
Check that `i` never exceeds the maximum size of serverResponse, because:

    char serverResonse[10]
    for int i - 0; i < 50; i++)
      serverResponse[i] = 42;  // This will crash on the 11th loop.

I can't say if the above code will cause a restart, but that's dependent on what was using the 11th byte of the array before it got stomped on.


message:
Platform-independent functions for FastPWM?

I learned from [answers here][1] that `pinMode(0, OUTPUT)` is a platform-independent equivalent of `DDRB = 1<<DDB0`, on the ATTiny85.

Are there platform-independent functions for the following?

    TCCR0A = 2<<COM0A0 | 2<<COM0B0 | 3<<WGM00;
    TCCR0B = 0<<WGM02 | 1<<CS00;
    TCCR1 = 0<<PWM1A | 0<<COM1A0 | 1<<CS10;
    GTCCR = 1<<PWM1B | 2<<COM1B0;

Explanation of above code [here][2]. These calls enable FastPWM.

I checked the [Arduino API reference][3], but not sure which are the equivalent to above. How to determine?

  [1]: https://arduino.stackexchange.com/q/48356/41397
  [2]: https://www.re-innovation.co.uk/docs/fast-pwm-on-attiny85/
  [3]: https://www.arduino.cc/reference/en/

body:
It is highly unlikely there would be direct 1:1 functions that implement such discrete operations. Simply because such operations are pretty unique to a single family of microcontrollers. They are too low-level for an API to even consider wanting them.

Instead, there are higher level functions which may, if the chip requires it, include those operations.

The operations you list are all related to PWM, so the higher level function that would encompass them would be `analogWrite()`.


message:
Reading SMS using Arduino Uno and SIM800L and print on LCD (16x2 alphanumeric) using serial connection NEED HELP

Well, I am making a device, which has to receive SMS and print the text using am LCD display. Now I have code that can receive SMS and store it into a string variable using serial connection.
Here is my code:

    #include <LiquidCrystal.h>
    #include <SoftwareSerial.h>

    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;  //LCD pins
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
    String Arsp, Grsp;
    SoftwareSerial gsm(6,7); // RX, TX

    void setup() {
      Serial.begin(9600);
      Serial.println("Testing GSM SIM800L");
      gsm.begin(9600);
      gsm.println("AT"); //checking
      delay(1000);
      gsm.println("AT+CMGF=1");  //Set to Text mode
      delay(1000);
      gsm.println("AT+CNMI=1, 2, 0, 0, 0"); //Set to notification for new message, New message indication
      lcd.begin(16, 2);
    }

    void loop() {
      if(gsm.available()) {
        //Check if GSM Send any data
        Grsp = gsm.readString(); //Read data received from SIM800L GSM Module
        lcd.clear(); //Clear LCD Screen
        lcd.setCursor(0,0); //Set LCD cursor to First line, first row
        for(int i = 0; i<=100; i++) {
          //Print received string character by character
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print(Grsp); //Print string which received from GSM (sms, sender, sms index, receive time, etc)
            lcd.print("        ");
            lcd.print(i); //Print the string index
            delay(500);
        }
      }
    }

When my Arduino Uno is connected to PC and the Arduino serial monitor is already open,
it prints correctly this text received from GSM

    "  +CMT: "+995599093230","","18/01/05,16:29:57+16"  0.

In this case I sent a message with text "0". When I disconnect the USB and connect my Arduino Uno to 9V power supply and send the same message text it prints:

 `"  +CMTI:  "ME", "+995598403536", 40)`

In this case 40 is the index of the message received. I want to get the whole string as in the first case when the USB was connected.

I using Arduino GND and 5V to power the SIM800L. What I am doing wrong? Is this due to incorrect serial connection or incorrect code error?

body:
The PP3 battery you are trying to use is far from powerful enough to run a SIM800L. It's barely powerful enough to run an Arduino by itself for more than a couple of hours if you're lucky.

The SIM800L, as [the datasheet](http://wiki.seeedstudio.com/images/4/46/SIM800L_Hardware_Design_V1.00.pdf) tells us, must be powered by a supply which can provide *at least* 2A.

> The power supply range of SIM800L is from 3.4V to 4.4V. Recommended voltage is 4.0V. The transmitting burst will cause voltage drop and the power supply myst be able to provide sufficient current up to 2A.

The Arduino's on-board 5V regulator can't provide more than 800mA if you're lucky (far less if the incoming voltage is more than around 7V due to heat dissipation). Running from USB may allow peaks of up to 2A on a DCP USB socket without the Arduino's PTC fuse blowing.

A [typical PP3 battery](http://www.farnell.com/datasheets/1842389.pdf) has an impedance of 1.7 ohms. That means a dead short circuit across the terminals would theoretically allow 9/1.7 = 5.2A maximum ever to flow. That kind of current would dissipate about 46W in heat inside the battery causing it to explode. Also at that current, given the typical low capacity of about 154mAh, the battery would be flat within about 100 seconds.

The maximum rated current for one of these batteries (at least, the maximum current shown on any of the graphs in the datasheet) is 250mA.

You need to power your SIM800L in a completely different manner, including two important things:

1. You need a power source that can provide 2A at the rated input voltage of your module (5V?)
2. That source needs to either be separate from the Arduino (except the ground, which must connect to the Arduino as well as the module) or if it is 5V may be used to directly power the Arduino through the 5V pin.


message:
How can I light one led from two different sensors?

I want to light **one led** with two sensors, the first one is a **PIR** and the other one is a **Photocell** sensor.

The idea is to turn on the led if the PIR sensor detects movement, and also to turn the led on if the room gets darker(detected by the photocell).

I managed to make a code, but with TWO led's, a different one for every sensor.

    int ledPin = 13;
    int ledPin1=12;
    const int ldrPin = A0;
    int inputPin = 2;
    int pirState = LOW;
    int val = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(ledPin1, OUTPUT);
      pinMode(inputPin, INPUT);
      pinMode(ldrPin, INPUT);
    }

    void loop() {

      int ldrStatus=analogRead(ldrPin);
       if(ldrStatus<=400)
     {
        digitalWrite(ledPin, HIGH);
        delay(500);
        Serial.println("LED ON");
     }
       else digitalWrite(ledPin, LOW);
        val = digitalRead(inputPin);
          if (val == HIGH) {
            digitalWrite(ledPin1, HIGH);
              if (pirState == LOW) {
                Serial.println("Motion detected!");
                pirState = HIGH;
             }
          } else {
              delay(5000);
              digitalWrite(ledPin1, LOW);
                if (pirState == HIGH){
                 Serial.println("Motion ended!");
                 pirState = LOW;
               }
         }
      }

body:
    int ledPin = 13;

    int ldrPin = A0;

    int PIR_Pin = 2;

    void setup()

    {

        Serial.begin(115200);

        pinMode(ledPin, OUTPUT);

        pinMode(PIR_Pin, INPUT);

        Serial.println("Started Monitoring!");
    }

    void loop()
    {

        boolean lightStatus = ( analogRead(ldrPin) <= 400 ) ;
        digitalWrite(ledPin,  lightStatus);

        if(lightStatus) Serial.println("Light Triggered!");

        if(digitalRead(PIR_Pin) == LOW)
        {
             Serial.println("Motion Triggered!");
             digitalWrite(ledPin, HIGH);
             delay(5000);
             digitalWrite(ledPin, LOW);
         }
    }

<s>To keep it simple serial code is removed, if needed can be added easily that should not be a big issue. </s>
Still this can be done in much more efficient way. This is just one solution.

Note: haven't complied/error checked the code as i am writing this on a phone. Hope it should work as intended, errors if any, shall be minor ones.  Comment below if any issues.

Update 1: added code to send triggered status over serial comm.

Update 2: corrected "Boolean" to be as "boolean"


message:
How to communicate with ESP8266 ESP01 by sending data through softwareserial on Arduino Uno?

I am able to send AT commands when connecting to the software through the TX/RX pins (1, 0) and the ESP01 communicates perfectly. However, as soon as I start doing that same thing with code I can't get the ESP01 to respond whatsoever. All I'm trying to do is get an OK back from the serial monitor. I changed the baudrate on the ESP01 as well as my serial monitor from 115200 to 9600, 19200 using this command:

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

Troubleshooting steps taken:

1. Tried upping the voltage in case it wasn't getting enough current.
2. Tried different ESP01s.
3. Tried switching TX and RX pins.
4. Tried using different pins on the Uno (2 and 3, 10 and 11, 7 and 8).
5. tried changing `myESP.println("AT");` to `myESP.write("AT\n\r");`.

Nothing works. I've done a ton of research and I haven't found anything wrong with what I'm doing, do you guys have any ideas?

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

    #define TX 3
    #define RX 2
    String ssid = "*****";
    String password = "******";

    #include "SoftwareSerial.h"

    SoftwareSerial myESP(RX,TX);

    void setup() {
      pinMode(RX, INPUT);
      pinMode(TX, OUTPUT);
      myESP.begin(19200);
      Serial.begin(19200);
    }

    void loop() {
      myESP.println("AT");
      delay(5000);
    }

Schematic is as follows:
TX -> pin 3
RX -> pin 2
Vcc -> 3.3v
GND -> Ground
CH_PD -> Vcc

body:
Alright so I figured out my issue. Here's the answer for anyone with this problem in the future.

1. Remove `pinMode(RX, INPUT);`
and ` pinMode(TX, OUTPUT);`.
2. SoftwareSerial isn't going to relay the response back, so you have to program a response in, that's why sending "AT" by itself to the serial port is pointless.


body:
How about this:

    void loop() {
      while(Serial.available() > 0) {
         myESP.write(Serial.read());
      }
      while(myESP.available() > 0) {
         Serial.write(myESP.read());
      }
    }

That code will continue to load data to and from the software serial not just one byte. You can also use string concatenation:

    String data = "";
    while(Serial.available() > 0) {
       data += Serial.read();
    }

Or arrays:

    int data_max = 4096;
    int data_size = 0;
    char data[data_max];
    while(Serial.available() > 0) {
       if(data_size < data_max) data[data_size++] = Serial.read();
    }


message:
How to solve the white blocks on LCD keypad display?

I have just bought my first Arduino (a Mega 2560 R3 clone by ELEGOO), and I got a [cheap LCD display][1] to go with it. I cannot for the life of me get it to display anything other than a row of white blocks (although I uploaded a different sketch that I change the numbers of one of the ports and now it shows the top 3 blocks of the second row as white as well).

When I read the notes on the example LCD sketch "Display" it says the following:

The circuit:

 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

However, when I plug my display into the Arduino the pins don't seem to go into the same ports and there is no other way of fitting it in. For reference my pins go:

    LCD - Mega2560

     VSS - AREF,
     VDD - GND,
     V0 - 13,
     RS - 12,
     RW - 11,
     E - 10,
     D0 - 9,
     D1 - 8,
     D2 - 7,
     D3 - 6,
     D4 - 5,
     D6 - 4,
     D7 - 3,
     D8 - 2,
     A - 1-TX,
     K - 0-RX,

     RST - RESET,
     5V - 5V,
     VIN - VIN,
     A0 - A0,
     A1 - A1,
     A2 - A2,
     A3 - A3,
     A4 - A4,
     A5 - A5,

I am not sure what to do any assistance you can provide would be greatly appreciated.

Liam

  [1]: https://www.amazon.co.uk/gp/product/B01EYW5R5M/ref=oh_aui_detailpage_o00_s01?ie=UTF8&psc=1

body:
The words you use to describe the parts of the display and which sketch you are using need to be more precise.

Regarding the part you linked to in your question, the dark blue part is the [LCD][1] (Liquid Crystal Display).  Not many buy just this part.  It is too hard to use.

Under it is a green board with the commonly found [Hitachi LCD Controller][2].  This is what most people buy and call the LCD. [Many Arduino sketches are written for the Hitachi LCD Controller][3]. While you could connect this type of board directly to an Arduno, you would have to make a special cable which must follow the pin assignments in the particular sketch you are using!

Finally, the darker board beneath the green board appears to be an Arduino shield.  Normally Arduino shields adapt what ever circuit happens to be upon the shield to the Arduino Uno pins and form-factor.  However, again, you mush use a sketch which which follow the pin assignments for the particular shield!

Armed with this knowledge, you should be using/looking-for a sketch specific to your Arduino shield. I suspect you are using the wrong sketch and this is resulting in "white blocks" on your LCD display.

Other considerations:

1. It is possible your contrast in incorrectly set.  Identify if this control is available on the shield you are using and consider adjusting it.

2. Is the shield plugged in correctly?  Check to make sure all the pins are connected to the Arduino.  Most shields are designed specifically for the Arduino Uno form factor.

3. If you are still having problems, consider buying everything (the Arduino Uno and the LCD shield) from one specific well known vendor which can supply support through direct contact or forums.  Usually a good vendor will provide support especially if they provide all parts of a project.

Other approaches:

You should find a sketch which works with your LCD & Buttons Arduino shield.  However, as you have figured out the paths between the Arduino and the Hitachi like LCD Module you might try using the [LiquidCrystal Library][4].  When this library is instantiated, the pins of the Arduino which are to control the Hitachi like LCD module are passed as arguments.  Using the information in the question, it is likely the instantiation should look similar to this:

    LiquidCrystal(12, 10, 5, d5, 4, 3)

...Note, you are missing "d5" in your question.  So the above is likely not correct.  Also, from your description, the Arduino appears to control contrast ("V0" pin) for this shield.  As the LiquidCrystal library does not appear to support this, you may need to create additional code to control contrast.

  [1]: https://en.wikipedia.org/wiki/Liquid-crystal_display
  [2]: https://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller
  [3]: https://www.arduino.cc/en/Tutorial/HelloWorld
  [4]: https://www.arduino.cc/en/Reference/LiquidCrystal


body:
I finally solved the issue, it turns out there was nothing wrong with the LCD shield or the sketch, the problem was the MEGA 2560 (by ELEGOO). The solder joint at port 'Digital 5' was missing, the pin was through the board but there was no joint. All I did to fix it was to properly solder the joint like the others are and it started to work.

Just in case anyone has a similar sort of problem as I did or wants to check the ports are working this is the sketch that I was using when I discovered the missing joint, its a simply scrolling LED sketch:

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

     /*
      For Loop Iteration

     Demonstrates the use of a for() loop.
     Lights multiple LEDs in sequence, then in reverse.

     The circuit:
     * LEDs from pins 2 through 7 to ground

     created 2006
     by David A. Mellis
     modified 30 Aug 2011
     by Tom Igoe

    This example code is in the public domain.

     http://www.arduino.cc/en/Tutorial/ForLoop
     */

    int timer = 100;           // The higher the number, the slower the timing.

    void setup() {
      // use a for loop to initialize each pin as an output:
      for (int thisPin = ***2***; thisPin < ***13***; thisPin++) {
        pinMode(thisPin, OUTPUT);
      }
    }

    void loop() {
      // loop from the lowest pin to the highest:
      for (int thisPin = ***2***; thisPin < ***13***; thisPin++) {
        // turn the pin on:
        digitalWrite(thisPin, HIGH);
        delay(timer);
        // turn the pin off:
        digitalWrite(thisPin, LOW);
      }

      // loop from the highest pin to the lowest:
      for (int thisPin = ***7***; thisPin >= ***13***; thisPin--) {
        // turn the pin on:
        digitalWrite(thisPin, HIGH);
        delay(timer);
        // turn the pin off:
        digitalWrite(thisPin, LOW);
      }
    }

you can modify the numbers that are in asterisks in order to check whichever pins you need.

To use it you build the following circuit:

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

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

Then simply change which port you connect the wire from the anode of the LED to and wait for the LED to flash on.

Thank you to everyone who posted a message to try and help me fix it, youve helped me learn a lot.

Liam


message:
Hardware Serial connection for Arduino Mega 2560 NEO GY-GPSMV2 GPS module

My project is **Vehicle Tracking System**, One of my module is GPS module [(Neo GY-GPSMV2)][1]. I can successfully see the GPS coordinates via Software Serial. But what I want is that my Arduino should not be connected to my laptop. So I should use Hardware Serial (correct me if I'm wrong). But I read some blogs **that I should use resistors to avoid damage** to m GPS module if I will use Hardware Serial. I searched for the wiring of it then I see this. [![enter image description here][2]][2] (Please remind that I'm using Mega so please just focus on the wiring). So I bought a 10k and 4.7k resistors. My **question is how can I appl this on an actual wiring?** should I split the wire? or what?

  [1]: https://www.ebay.com/i/253247982818?rt=nc
  [2]: https://i.stack.imgur.com/DJxsi.jpg

body:
Most importantly, I want to point out that a Mega has 4 `HardwareSerial` ports: `Serial`, `Serial1`, `Serial2` and `Serial3`.  There is no reason to use an inefficient software serial port library.  Software serial libraries use the processor to handle each bit transition, so they use much more CPU time.

 `SoftwareSerial` is particularly inefficient, because it disables interrupts for the entire time that a character is being sent or received, and it can't do both at the same time.  This will interfere with your sketch or other libraries.  [This answer](https://arduino.stackexchange.com/questions/34126#34130) lists the various serial port choices.

**To answer your question:**

> ... how can I apply this on an actual wiring? should I split the wire? or what?

Yes, 3 things get connected together at two places.  Most people use breadboards for prototyping.  Stick two wire ends (a "split" wire) and one end of a resistor into a common row of the breadboard, connecting them electrically.

But for a permanent solution, you should solder two separate wires and one end of the resistor together.  A small piece of perfboard can help secure the wires and discrete components.  It's a little kludgey, but you can strip the insulation from the middle of one piece of wire (don't split the wire) and solder one end of the resistor to it.

BTW, I always recommend real level-shifter modules that use FETs.  They're fast, so you can also use them for SPI interfaces, like an SD card, and they're bi-directional (5V to or from 3.3V).  And they're cheap.  You would just solder individual wires from the Arduino and the GPS device to various through holes in the module PCB.

The picture in your post shows a direct connection between the GPS transmit pin and the Arduino receive pin.  While this will not damage either pin, the GPS transmit voltage is not quite within the range *specified* for the Arduino receive pin.

Note the use of the word "specified".  If you read the specifications for the two devices, you will see that a logic 1 out of the GPS pin (called VOH) is slightly under the minimum acceptable voltage for the logic 1 input to an Arduino pin (called VIH).

You can also use discrete components to "step-up" the GPS TX voltage up a little.  You can google for many different solutions.  [Hackaday has a nice summary](https://hackaday.com/2016/12/05/taking-it-to-another-level-making-3-3v-and-5v-logic-communicate-with-level-shifters/).  MicroChip AppNote DS41285A has many suggestions.  Again, I would strongly suggest using a level-shifting module.

Many people report using a direct connection without problems.  It is possible that:

* the actual devices have a higher VOH and/or lower VIH, or
* the data is received with various amounts of errors, and the GPS parsing library (or sketch) ignores the errors.  Take a look at my [NeoGPS](https://github.com/SlashDevin/NeoGPS) library.  It is the fastest, smallest, most accurate and most reliable GPS library.  It can help you detect (and reject) bad data.


message:
Can't see second Arduino port on Ubuntu

I have connected two arduinos to `/etc/ttyUSB0` and `/etc/ttyUSB1`.

Only one is visible in Arduino IDE. Why and how to force second?

**UPDATE**

    $ ls -l /dev/serial/by-id
    total 0
    lrwxrwxrwx 1 root root 13 Jan  6 23:32 usb-1a86_USB2.0-Serial-if00-port0 -> ../../ttyUSB1

I.e. it shows port, which IS NOT SHOWN in Arduino IDE (only `/dev/ttyUSB0` is shown.

**ALSO**

I can see both ports if run `arduino` with sudo. Should I run it with sudo?

Permissions are same

    $ ls -l ttyUSB?
    crw-rw-rw- 1 root dialout 188, 0 Jan  6 23:26 ttyUSB0
    crw-rw-rw- 1 root dialout 188, 1 Jan  6 23:39 ttyUSB1

body:
You have to add use your user to the dialout group, as explained in the [installation instructions for Linux][1].

    sudo usermod -a -G dialout $USER

Then log out and back in again.

  [1]: https://www.arduino.cc/en/Guide/Linux


message:
I'm trying to display the numbers 0-99 by multiplexing to two 7 segment displays. One number does not display

//Numbers 0-9.
    int numberArray[10][7] = {
      { 0, 0, 0, 0, 0, 0, 1 }, //0
      { 1, 0, 0, 1, 1, 1, 1 }, //1
      { 0, 0, 1, 0, 0, 1, 0 }, //2
      { 0, 0, 0, 0, 1, 1, 0 }, //3
      { 1, 0, 0, 1, 1, 0, 0 }, //4
      { 0, 1, 0, 0, 1, 0, 0 }, //5
      { 0, 1, 0, 0, 0, 0, 0 }, //6
      { 0, 0, 0, 1, 1, 1, 1 }, //7
      { 0, 0, 0, 0, 0, 0, 0 }, //8
      { 0, 0, 0, 0, 1, 0, 0 }, //9
    };

    //Turn off all segments (common anode --> high = off)
    void reset() {
      for (int i = 12; i >= 6; i--) {
        digitalWrite(i, 1);
      }
    }

    //turn on both segments (don't write anything to them)
    void on(){
      digitalWrite(4,1);
      digitalWrite(5,1);
    }

    void setup() {
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(5, OUTPUT);
      reset();
      on();
    }
    void loop() {
      for (int i=0;i<99;i++){
        twoDigitNumber(i);
      }
    }

    void twoDigitNumber(int number){
        digitalWrite(4,1);                   //turn on left display
        digitalWrite(5,0);                   //turn on right display
        digit(int(floor(number/10)));        //display the tens digit
        delay(10);
        digitalWrite(4,0);                   //turn off left display
        digitalWrite(5,1);                   //turn on right display
        digit(int(number-floor(number/10))); //display the ones digit
        delay(10);
    }

    //make the displays show a single digit number
    void digit(int number) {
      for (int i = 12; i >= 6; i--) {
        digitalWrite(i, numberArray[number][12 - i]);
      }
    }

This is my first time doing anything at all with Arduino, and I'm also brand new to the language.

I have a bit of circuitry attached to the display. I'm using 2n5551 NPN transistors to act as a switch. Collectors connected to 5v, bases are connected to pin 4/5 with a 200 ohm resistor. Emitters are connected to the common anode of the displays. pin 4 is for the left display, pin 5 for the right display. These are to display different numbers in each display. Something's probably wrong with this but I'm having a hard time learning about transistors.

When I use the function twoDigitNumber(), it only displays the number on the left display, but I can see a very dim copy of that same number on the right display. int() is there because i thought floor() would make it into a double and cause issues, but that didn't fix it.

I know every segment works. When I use digit(), it shows the same digit on both displays (as expected).

Any help is appreciated.

body:
Missing `pinmode(4,OUTPUT)` in your `setup` routine.

As a general comment, using variable names instead of 'magic numbers' makes your code easier to read - and thus usually easier to debug. for example:

    const int leftDisplay = 4;
    const int rightDisplay = 5;
    const int seg1 = 12;
    const int seg2 = 11;
    [...]

You can also use `HIGH` and `LOW` instead of `1` and `0` for the `digitalwrite` elements


message:
4-wire shielded cable for I2C and power

I have two PCBs with ATmega328 that will communicate through I2C protocol. The master will also provide power for the slave, which is located at a relatively short distance (30-40cm or 12-16 inches).

Is it feasible to use the same cable for power (3.3V) and communication?

Thank you.

body:
Sure. Why wouldn't it be? Power is (pretty) static and noiseless.

Just be warned that having the clock and data in the same twisted pair (if your cable has twisted pairs) could cause issues over longer distances. I2C isn't designed for running over cables like that - it's designed for routing round short traces on a PCB.


message:
How to connnect Arduino to Wemos D1 (send data)?

I made a project with an **Arduino Uno**, a 16x2 LCD **display** and a DS18B20 **temperature sensor**. It shows the temperature in the display:

[![Arduino Uno with 16x2 LCD and temperature sensor][1]][1]

I want to connect it to Internet so I got a Wemos D1 Mini. It works great: it send data through my router.

But I need to connect my project with the Wemos D1 Mini:
[![Wemos D1 Mini pins][2]][2]
I think that I just need to send the data (temperatures grades) from my project to Wemos so then Wemos resolve it.

How can I do it?

  [1]: https://i.stack.imgur.com/69IcP.jpg
  [2]: https://i.stack.imgur.com/t0iJR.png

body:
- A) Throw out the Arduino, and just connect your display and sensor to the WeMos directly.
- B) Connect the Arduino to the WeMos using UART, SPI or I²C and send the temperature value to the WeMos. Keep in mind that the Arduino UNO is a 5V device, and the maximum voltage for the ESP8266 is 3.3V, so you'll need a level shifter.
You can send the temperature as a binary value (beware of framing errors), but the easiest way is to use a text-based protocol. Since you just have to send a single value, you can just use a single delimiter (e.g. new line). That makes it very easy to parse.


body:
If you want to use the Wemos D1 only as a 'network adapter', put a firmware into esp8266. 'Classic' is Espressif AT firmware in esp with WiFiEsp library in your sketch. New option is WiFi Link firmmware in the esp with [WiFi Link library][1] used in your sketch.

Both libraries recommended by me (WiFiEsp and WiFiLink) have standard Arduino networking API like the Ethernet and WiFi library.

[WiFi Link firmware][2] is an Arduino sketch for the esp8266.

  [1]: https://github.com/jandrassy/arduino-library-wifilink
  [2]: https://github.com/jandrassy/arduino-firmware-wifilink


message:
Connect ESP-01 to USB Uart

for programming my ESP-01 chip I bought an "USB Uart", but it looks different to all the ones in all tutorials. I don't know how to connect the uart to the esp.
The uart i bought has following pins: 3V3, DTR, RXI, TX0, GND, +5V. The ESP01 has the known layout (http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family#esp-01).

Once connected: Do I need an external power source, or do i just connect the usb uart to my computer?

Many thanks

body:
Just to give an anwser for users struggling with the same problem I will sum up what helped me.

To connect the UART to the ESP the `Beginner's Guide to the ESP8266` from @tttapa was very helpful. Another helpful link was this one:
https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/

So in my case I just needed the GND, 3V3, RXI and TX0 pins from my UART.

I needed no external powersupply for the flashing process and some simple examples.


body:
You can program the ESP-01 whith described method in this page:

[https://zinventor.wordpress.com/primeros-pasos-con-esp8266/][1]

  [1]: https://zinventor.wordpress.com/primeros-pasos-con-esp8266/

Its works fine!


message:
Help connecting ILI9341 LCD SPI Display to arduino uno

I got this lcd with touchscreen from a store but i have no idea on how to connect it to the arduino uno.
Any help is appreciated.

[This][1] is where i bought it from.

[The display][2]

[My Arduino][3]

  [1]: https://www.optimusdigital.ro/ro/optoelectronice-lcd-uri/3544-modul-lcd-spi-de-28-cu-touchscreen-controller-ili9341-i-xpt2046-240x320-px.html?search_query=Modul LCD SPI de 2.8'' cu Touchscreen - Controller ILI9341 și XPT2046 (240x320 px)&results=1
  [2]: https://i.stack.imgur.com/KDTRI.jpg
  [3]: https://i.stack.imgur.com/M3bmD.jpg

body:
1. Download and install a suitable library
2. Wire the display to the Arduino as per the markings on the display
3. Try some of the examples for the library you are using.


body:
You can get it working by two methods

1. using a voltage divider e.g to shift from 5V to 3.3V you could use two resistors, 100k and 200k respecfully and between both resistors there is voltage of 3.3. One for each pin that needs it.

2. Using 10K resistors in series between the LCD and the arduino. I really don't know how is working but it works fine that way.

I tested both methods, also the MISO pin from the LCD can be connected directly to your arduino.


message:
DIY printer + Arduino. Can I use the position sensor? Multithreading?

I'm trying to make a computer-controlled painter/drawer/CNC, something like [this][1], from an old junk printer that didn't work... I have got as far as a working motor shield that can move the sliding trolley back and forth by running the DC for a short amount of time, and running the stepper that would be "paper feed". But it is currently just some gears and roller.

1: Assuming I can attach the paper-feed gear to a platform to move it in both X and Y directions, is there still no way I can multithread Arduino code? Searching for this, I found results in some really old howtos/forums that say you cannot, but you can fake it by doing one thing then another. I would want a serial command to send the Arduino to say, "start 3mm right" and while doing so, run "3mm forward" for example for a diagonal line. I've only run this on commands that are run intermittently and can block while the command is running [like so][2].

2: There is a clear "tape" with lines on it that goes through the sliding trolley and has a ribbon coming out of the sliding trolley that I assume is reference indicating that it is x mm away from the end, that lets the printer see how long to move. Would it be feasible to reverse-engineer this type of device to use in this custom application? Could this be done with an oscilloscope output connected to pins on the ribbon?

  [1]: https://www.instructables.com/id/DIY-3axis-CNC-plotter-out-of-old-printers/
  [2]: https://github.com/programmin1/HowToTrainYourRobot/blob/master/StepperShieldTest/StepperShieldTest.ino

body:
You can multi*task* on arduino by doing stuff for one task for a bit and then do stuff for another task for a bit and switch back and forth like that.

However many arduino libs tend to rely on blocking calls and don't support giving control back to calling code so time spent in `delay()` calls can be used by other code.


body:
I recommend using the [AccelStepper library](http://www.airspayce.com/mikem/arduino/AccelStepper/) (installable via the Library Manager) which will allow you to drive multiple stepper motors at once without blocking commands.

1. It's possible to multithread on an Arduino but it's a sophisticated operation that you don't actually need to do for this application. Better instead to call one motor move, then the next, in rapid succession in your main loop. The AccelStepper library sort of builds this in when you're using it for position-based control; you tell one motor where to move and then run `motor.run()` as often as possible in the loop to actually send the commands to your driver to move it. (You *also* tell the other other motor to move, and also run `motortwo.run()` just as often as `motor.run()` in the loop; neither command takes much time at all to run.) For precisely coordinated multi-motor moves, look at the `MultiStepper` example included in the library, but note that the sort of thing I'm describing, implemented in the similarly-named `MultipleSteppers` example, will do the trick for you.

2. Regarding that "clear tape," my suspicion is if you look close, you'll find it's got lots of very narrowly spaced black and clear bands. It is used to report position data back to the motor driver. It more than likely has a photointerruptor that reads its movement. You can read the speed (but not absolute position) of that tape by monitoring the clear and black sections moving through the photointerruptor. For higher precision of data, likely necessary because the tape will be moving relatively fast, you'll likely want to use an [interrupt](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/) feature of the chip to watch the ticks as they go by, which is designed to take precedence over other would-be simultaneous operations the chip is doing.

Good luck with the project!


message:
Arduino Analog Input: why the weird fluctuation?

I am using an Arduino Uno. `analogRead(A0)` (or whichever channel I use) returns 0 when it is grounded with Arduino Gnd, and 1023 when connected to Arduino 5v. But when I connect it to a current sensor (ACS712) it is always fluctuating like this:

>0, 0, 0, 0, 0, 0, 1023, 1023, 1023, 1023, 1023, 441, 446, 0, 0, 0, 0, 1023, 1023...

I also tried it with a potentiometer (10K) and analog joystick: the results are the same. I tried changing different power supplies (both Arduino's and the sensor's (ACS712, potentiometer, joystick)). I even tested it on an Arduino Mega, but no luck. Such extreme fluctuation are making no sense to me. Kindly help me what could be the issue.

My wiring diagram is attached to this post. And I use an external supply to the ACS712. Is it possible that Static electricity is causing this issue?

Code:

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

    void loop() {
      float value = analogRead(A0);
      Serial.print("Raw:");
      Serial.println(value);
      delay(500);
    }

Thanks.

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

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

body:
You need to connect together the grounds from your external power supply and the Arduino.

At the moment the two devices are floating - there's no commonly-agreed 0v point.


body:
I had a similar issue with fluctuating values. Make sure you are setting in your code the analog PIN as `INPUT` pin. On some boards you have to specify it explicitly, like this:

    pinMode(A1, INPUT);


message:
Is it possible to increase the voltage on 3.3v output to 5v on an ESP board to power a DC motor?

I am trying to use an ESP32s controller connected to an RC car DC motor. I found that when using my Arduino this is easily accomplished, and I can see that my output pin produces 5v for the motor to spin. My ESP32, however, only produces 3.3v, so of course the motor does not spin. Do I need to use a motor driver board, transistors, or will the ESP32 simply not work in this scenario?

Thanks in advance.

body:
You should not power a motor from a micro-controller, period, regardless if that is an ATmega or an ESP32.

Instead, you need to use a motor driver circuit - this isn't really so much about *voltage* amplification, as it is about *current* amplification. The actual I/O output voltage of your ESP32 is likely very close to 3.3v. If you are measuring 1.8v, that is only because you motor is loading the pin so heavily (and improperly) that the voltage sags.

Without the specs of your motor, it's not really possible to provide any specific advice. But you should seek an FET-based solution, not one based on bipolar transistors.  The old bipolar L293D, L298, etc parts are horribly lossy and extremely unsuited to low voltages motors. In some low-voltage, low-current cases, the FET-based TB6612FNG can be a good solution - **but again, this depends entirely on the unstated requirements of your motor**. Typically only very lightweight or weak "RC cars" could use such drive, for more serious ones you should look at hobby-grade Electronic Speed Controller (ESC) modules, or their equivalent circuitry.

These motor driver chips will have two supply inputs. One supplies the logic and would typically share the microcontroller's supply voltage. The other supplies the motors - it might in light duty cases be whatever is supply the microcontroller's regulator, but in more power-hungry cases would often be a unique supply. Both grounds should be connected together and connected to the microcontroller's ground, but in such a way that the ground current for the motors flows directly from the power supply, and never *through* the microcontroller board.


body: I figured out my issue. I was only getting 1.8v output because I was testing my lead after a led light I had plugged in. Once I removed the led, my voltage went to 3.3v, which was expected.


message:
Serial.parseInt value always goes back to 0

I am trying to read a value between 1000 and 2000 from my Serial Monitor and use it to drive some motors through ESC.

The code works when I use a potentiometer mapped for 1000-2000. I am now trying to use a Serial Monitor, but the "val" keeps going from the value I enter (between 1000 and 2000) and quickly returns to 0.

Why is this?

Here is the code for reference:
<!-- language-all: lang-cpp -->

    #include <Servo.h>//Using servo library to control ESC
    Servo esc1; //Creating a servo class with name as esc1
    Servo esc2; //Creating a servo class with name as esc2
    Servo esc3; //Creating a servo class with name as esc3
    Servo esc4; //Creating a servo class with name as esc4
    void setup()
    {
      esc1.attach(7); //Specify the esc signal pin,Here as D10
      esc2.attach(6); //Specify the esc signal pin,Here as D9
      esc3.attach(5); //Specify the esc signal pin,Here as D8
      esc4.attach(4); //Specify the esc signal pin,Here as D7
      esc1.writeMicroseconds(1000); //initialize the signal to 1000
      esc2.writeMicroseconds(1000); //initialize the signal to 1000
      esc3.writeMicroseconds(1000); //initialize the signal to 1000
      esc4.writeMicroseconds(1000); //initialize the signal to 1000
      Serial.begin(9600);
    }
    void loop()
    {
      int val; //Creating a variable val
      Serial.println("Input ESC Speed between 1000 and 2000:");
      while (Serial.available() > 0) {
        val = Serial.parseInt();
        Serial.println(val);
      }//Checks for a character in the serial monitor
      Serial.println(val);
      esc1.writeMicroseconds(val); //using val as the signal to esc
      esc2.writeMicroseconds(val); //using val as the signal to esc
      esc3.writeMicroseconds(val); //using val as the signal to esc
      esc4.writeMicroseconds(val); //using val as the signal to esc
    }

body:
This code will work IF you set the Serial Monitor to "No Line Ending" (OSX 10.6.8. IDE Version 1.0.6.2). parseInt() doesn't like the NL + CR chars.

    unsigned int val;

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

    void loop(){
      Serial.println("Input ESC Speed between 1000 and 2000:");
      while(Serial.available() > 0){
        val = Serial.parseInt();
      }
      if(val > 0){Serial.println(val);}
      delay(1000);
    }

There is another way to get the integer value using this code:

    char inputBuffer[16];
    unsigned int val;

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

    void loop(){
      Serial.println("Input ESC Speed between 1000 and 2000:");
      while(Serial.available() > 0){

        // A function that reads characters from the serial port into a buffer.
        Serial.readBytes(inputBuffer, sizeof(inputBuffer));

        // Convert string to integer
        // cplusplus.com/reference/cstdlib/atoi/
        val = atoi(inputBuffer);

        // memset clears buffer and updates string length so strlen(inputBuffer) is accurate.
        memset(inputBuffer, 0, sizeof(inputBuffer));
      }
      if(val > 0){Serial.println(val);}
      delay(1000);
    }

The Binary sketch size is 94 bytes less than the first example using parseInt. The second sketch will work with ANY Serial Monitor Line Ending settings.


message:
Powering Arduino from 7805 voltage regulator

I am trying to build an Arduino Uno based robot. My questions are the following:

1) The motor driver also has an on-board 78M05 voltage regulator from ST electronics. I used a 9V battery to power the robot, and the 9V was connected to the input of the voltage regulator, and the +5V output I used to power the Arduino. I did so by connecting the 5V from the regulator to the 5V pin on the Arduino and the GND's together. I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

2) I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

body:
> I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

Nothing wrong with that as long as it is regulated 5V (which yours is). You can use either the 5V pin on the header, or the 5V pin on the ICSP connector. They are both the same.  It is good practice to connect a diode between 5V and VIN to prevent current flowing backwards through the onboard regulator should something connected to VIN want to draw current.

> I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

A regulator has a "drop-out" voltage. That is often in the order of 1.2V for these kind of regulators (it's certainly right for the Arduino's on-board one.

You are providing less than the regulation voltage plus the drop-out voltage, so the output of the regulator will be the input voltage minus the drop-out voltage.

As long as that is above the lowest voltage the Arduino can run from at 16MHz then it will still work fine. You should be fine down to about 4V output from the regulator, and even lower if you're lucky (you may start getting stability problems though since the ATMega328P isn't rated to run at 16MHz at lower voltages).

It also means that the GPIOs on the Arduino will be running at a lower voltage as well.


message:
How can I loop for a set amount of time when a condition is met?

I'm trying to create an Arduino project with a light sensor and a buzzer. The idea is that when the sensor detects that the lights have gone off, the buzzer will sound for 5 seconds. At some point, the lights will come back on, but when they go back off, I need the buzzer to sound again.

At the moment the buzzer does sound the first time the lights are turned off but after the lights have come back on and then off again, it won't sound and I can't figure out why.

    int lightSensor = 2;
    int buzzer = 3;
    long startTime,stopTime;
    long myDesiredTime = 5000;

    void setup()
    {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(lightSensor, INPUT);
      pinMode(buzzer, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorState = digitalRead(lightSensor);

      switch(sensorState)
      {
      case 1:
        while (sensorState == 1)
        {
          if(stopTime-startTime<=myDesiredTime && sensorState == 1)
          {
            runBuzzer();
            stopTime=millis();
          }
        }
      }
    }

    void runBuzzer()
    {
      tone(buzzer, 1000); // Send 1KHz sound signal...
      delay(1000);        // ...for 1 sec
      noTone(buzzer);     // Stop sound...
      delay(1000);
    }

body: Understand that your `while (sensorState == 1)` in your `switch()` is an infinite loop, with no way out (even if internally it gives the desired 5 seconds of sound).


body:
Think of it like this. Any time you use a while loop your code has the rains until its done its job.

It's important to remember that the loop() function in Arduino should not be blocked. This line:

`while (sensorState == 1)`

will block forever. The condition is never changed from within the while loop. Theres a simple way you could fix this which would be to set `sensorState` and update it inside the while loop. But lets not do that. Because thats inefficient and you'll likely run into this problem again in more complex programs and that solution here won't still be a solution.

What you're trying to do is called concurrency. Your program should have obvious units of execution. Your two units are: "run a buzzer for 5 seconds" and "set off an event when a sensor reads true." where the first is depended on the second. So its conditional. That sounds like a job for `if`

When you code in `{` and `}` it is a block. It's not quite a context but is a distinct mode of execution.

So technically this:

    void loop() {
        if( ... ) {
          ...
        }
        if ( ... ) {
          ...
        }
    }

Is two modes of execution. Since loop() is executed repeatedly. With that in mind when you program you can then use a variable to control the what gets executed as needed. So:

    void loop() {
        int sensorState = digitalRead(lightSensor);
        if( sensorState == 1 && buzzer_enabled == 0) { // set off an event when a sensor reads true.
            buzzer_enabled = 1;
            startTime = millis();
        }
        if ( buzzer_enabled == 1 ) { // run a buzzer for 5 seconds
            endTime = millis();
            if(stopTime - startTime <= myDesiredTime) {
                runBuzzer();
            } else {
                buzzer_enabled = 0;
            }
        }
    }

We could stop here. But the use of delay is also blocking in the loop function and it is only for perception. So here's the whole thing without delays using a check against the modulus of diffTime.

    int lightSensor = 2;
    int buzzer = 3;

    long startTime,stopTime;
    long myDesiredTime = 5000;

    bool buzzer_enabled = false;
    bool buzzer_active = false;

    int sensorState;
    int prevSensorState = 0;

    void setup()
    {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(lightSensor, INPUT);
      pinMode(buzzer, OUTPUT);
    }

    void loop() {
        sensorState = digitalRead(lightSensor);
        if( sensorState == 1 && prevSensorState == 0 ) { // set off an event when a sensor reads true.
            buzzer_enabled = true;
            startTime = millis();
        }
        prevSensorState = sensorState;
        if ( buzzer_enabled == true ) { // run a buzzer for 5 seconds
            stopTime = millis();
            long diffTime = stopTime - startTime;
            if( (diffTime % 2000) < 1000 ) {
                if(buzzer_active == false) {
                    buzzer_active = true;
                    //tone(buzzer, 1000);
                }
            } else {
                if(buzzer_active == true) {
                    buzzer_active = false;
                    //noTone(buzzer);
                }
            }
            if(diffTime > myDesiredTime) {
                buzzer_enabled = false;
            }
        }
    }

No need for delay >:3 And all for free you got a new feature which is that if you set off the event again (the light goes off) the buzzer is extended another 5 seconds. If you don't want that all you have to do is add ` && buzzer_enabled == false` to the first if.


body:
You have two major issues here:

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorState = digitalRead(lightSensor);

      switch(sensorState)
      {
      case 1:
        while (sensorState == 1)
        {
          if(stopTime-startTime<=myDesiredTime && sensorState == 1)
          {
            runBuzzer();
            stopTime=millis();
          }
        }
      }
    }

The first is that you never re-read sensorState. The second is that you are comparing stopTime before setting a value to it. Try re-arranging like this:

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorState = digitalRead(lightSensor);

      switch(sensorState)
      {
      case 1:
        while (sensorState == 1)
        {
          stopTime=millis();
          if(stopTime - startTime <= myDesiredTime)
          {
            runBuzzer();
          }
        sensorState = digitalRead(lightSensor);  // read sensorState again
        }
      }
    }

---

> In your example, the buzzer does not sound when the light has been switch on and then back off again.

Good point. Well, we can simplify somewhat:

    void loop() {

      if (digitalRead(lightSensor) == HIGH)
        {
        startTime = millis ();  // remember when we started
        while (digitalRead(lightSensor) == HIGH &&
               millis () - startTime <= myDesiredTime)
          {
          runBuzzer();
          }  // end of while switch still closed and time not up
        while (digitalRead(lightSensor) == HIGH) { } // wait for sensor go to LOW
        delay (200);  // debounce
        }    // end of switch being closed
    }      // end of loop


message:
Interfacing Aduino Nano and RDM8800

I'm attempting to use an Arduino Nano with the RDM8800 to read data from NFC tags. After soldering wires between the Nano and the RDM8800, I attempted to test these devices using code similar to what has been used successfully on other serial devices similar to the RDM8800. Below is the code I used to test.

Wiring:

    Nano - RDM8800
    --------------
     5V  -  5V
    GND  -  GND
     D3  -  TX
     D2  -  RX

Tags Tested:

 - NTAG 216 (ISO14443A)
 - MiFare Classic 1k (ISO14443A)

Code:

    #include <SoftwareSerial.h>

    SoftwareSerial soft(2,3);

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

    void loop() {
      if(soft.available() > 0) {
        String serialData = soft.readString();
        Serial.println(serialData);
        writeAck();
      }

    }

    void writeAck() {
      uint8_t payload[] = "ACK|0|\n";
      soft.write(payload, sizeof(payload));
    }

I watched the serial monitor and attempted to scan two different NFC tags that matched the ISO14443A compatibility that should ship with the RDM8800, according to [this][1] article. I got no information returned on the serial monitor.

After, assuming the issue is with the firmware, I attempted to upload the firmware to the RDM8800, with no success. I installed the needed board support to the Arduino IDE, as outlined in [the intro article][1]. Not having a USB to serial tool, I used another Nano and simply bridged the connection between the GND and RST pins. I was unable to upload the firmware to the RDM8800, getting the error below each time I tried.

Error:

    avrdude: stk500_recv(): programmer is not responding

I believe that it's possible that I can't upload the firmware to the RDM8800 because the setup I used with the Nano as the USB to serial tool lacked a reset button. The image in [the intro article][1], says to connect the TX RX GND 5V and RST pins, but the image that it says shows this only shows the TX RX GND and 5V pins connected(See below).

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

The information that I've found on the RDM8800 and its use is very limited and so is my knowledge on this topic. I'm unsure how I should proceed right now. I believe that I'm taking the right approach to setup code to scan NFC tags, but I could be wrong there. I'm very unsure on what I'm doing in relation to the potential firmware issue. Overall, I'm simply unsure on how to proceed and I'm looking for more knowledgeable people to give me some advice on how to proceed.

Relevant Resources:
[RDM8800 Itead Wiki Page][3]
[RDM8800 Data Sheet][4]
[RDM8800 Schematic][5]
[RDM8800 Introduction Article][1]

  [1]: https://www.itead.cc/blog/introduction-to-rdm8800-a-13-56mhz-configurable-rfid-module
  [2]: https://i.stack.imgur.com/KrQVu.jpg
  [3]: https://www.itead.cc/wiki/RDM8800
  [4]: ftp://imall.iteadstudio.com/Modules/IM131218001/DS_IM131218001.pdf
  [5]: ftp://imall.iteadstudio.com/Modules/IM131218001/SCH_IM131218001.pdf

body:
SoftwareSerial constructor is rx pin first then tx pin.

You have `SoftwareSerial soft(2,3);` But you said that

    D3 - TX
    D2 - RX

Which means soft rx is going to its rx and soft tx is going to its tx. These need to be swapped. Either swap the wires or change it to:

    SoftwareSerial soft(3,2);


message:
softwareserial between arduino uno and esp8266

I have an Arduino UNO and HUZZAH ESP8266  module.  I need to send data between Arduino UNO and ESP module via Software Serial.  Right now I have the ESP module write data and Arduino UNO display data, but not working. When I run the Arduino UNO  and open its Serial Monitor, nothing is printed using below source code.

1. ESP8266 RX PIN connected to Arduino UNO PIN 2.
2. ESP8266 TX PIN connected to Arduino UNO PIN 3.
3. Using the FTDI cable that came with HUZZAH ESP8266 to power this module.  I just individually connected the RX and TX pins to the ARDUINO PIN 2 and 3 as mentioned above.

Any ideas what why not working? Below is code for both modules. Thanks,

Arduino UNO

    #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // RX | TX

    void setup(void){
      //Start hardware Serial communication
      Serial.begin(115200);

      //Start the software serial for communication with the ESP8266 component
      ESPserial.begin(57600);

    }

    void loop(void){

    if (ESPserial.available()){
      Serial.println("ESP available!!!");
      Serial.println(ESPserial.read());
    }

    }

HUZZAH ESP8266

    #include <ESP8266WiFi.h>

    #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // RX | TX

    void setup(void){
      //Start the software serial for communication with the Arduino UNO component
      ESPserial.begin(57600);

      //TODO: setup Wifi
    }

    void loop(void){
       ESPserial.write("This message generated by ESP module.");
       delay(500);
    }

body:
Make sure that:

 1. RX pin on the Arduino UNO is connected to the TX pin on the ESP8266.
 2. TX pin on the Arduino UNO is connected to the RX pin on the ESP8266.
 3. Baud rate should be set to the same value from both the Arduino and ESP8266.

I don't know about your arduino but looking at this schematic, your RX and TX should be swapped.

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

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


body: Adding to the above answer. UNO's TX is at 5V , while ESP8266 's RX is at 3.3V, as it is a 3.3V module. So its better to use a resistive divider to bring UNO' TX to 3.3V and then feed to ESP's RX, instead of directly connecting them eachother.


body:
//ESP

    #include "SoftwareSerial.h"

    SoftwareSerial ArduinoUno(D2,D3); //Rx, Tx

    void setup() {

    Serial.begin(9600);

    ArduinoUno.begin(4800);

    pinMode(D2, INPUT);

    pinMode(D3, OUTPUT);

    }

    void loop() {

    }

    /******************************************************************************/

//UNO

    #include "SoftwareSerial.h"

    SoftwareSerial ArduinoUno(3,2); //Rx, Tx

    void setup() {

    Serial.begin(9600);

    ArduinoUno.begin(4800);

    }

    void loop() {

      if(ArduinoUno.available() > 0){

        //float val = ArduinoUno.parseFloat();

        Serial.println(ArduinoUno.read());

      }

      delay(30);

    }


message:
Measure an AA battery?

If I'm going to measure an AA battery (about 1.5 v) with a USB-powered Arduino, I will connect the battery's +ve terminal to the A0 pin. Shall I connect the -ve terminal to the gnd pin too?

body: Yes you could although this means you're measuring in relation to the Arduino's logic voltage, which is slightly below 5v (due to a diode's voltage drop) or the voltage of vref.


message:
Arduino ISR timing question

Im trying to understand how the Arduino ISR keeps track of timing between pulses stored in a variable, if that variable is latter used.

Say, for example, you have a magnet mounted on a circular object, that passes a reed switch. Using this to trigger the ISR that calls a function that would have something like counts++ in it, then storing that value in a variable.

If that varible is used latter to turn on a motor, for example, according to the count capture, how does the arduino MCU know the freq or timing to output the count or pulses of the magnet passing the reed switch, at the same frequency that the counts were received? For example, a magnet mounted on a 2 inch dia shaft would turn slower past a reed switch than one mounted on a .5 inch shaft, or one could vary the speed of the magnet past the reed as they wish. So how does counter++ keep track of this freq? is it reading the attachinterupt pin (or is the function that is being called, keeping track) or does the ISR time stamp each pulse it receives and store that interval in the declared variable? so when the variable is used again, it has this interval stored in it?

To be more clear, if it takes one second for the magnet to complete one revolution, how does the MCU know it took one second and store this, along with the counts of the revolutions?

Thanks for any help

body:
All the interrupt does is count. It has no concept of time.  For instance:

    volatile uint32_t revolutions = 0;
    void count() {
        revolutions++;
    }
    ....
    attachInterrupt(0, count, FALLING);

will just count up 1 every time the interrupt triggers.

To be able to convert that count into something meaningful you have to manually introduce the concept of time - that is, the count of "revolutions" (for example) between two points in time.  And it's up to your sketch to implement that.

The simplest way may be:

    // For anything more than an 8 bit value on an 8 bit machine
    // make a critical section to save and reset the count
    cli();
    uint32_t savedResolutions = revolutions;
    revolutions = 0;
    sei();

    Serial.print(savedRevolutions);
    Serial.println(F(" revolutions per second"));

    // Introduce the concept of time - this will
    // make it get the count once a second.
    delay(1000);

Of course, instead of `delay()` you can use `millis()` in much the same way as the `BlinkWithoutDelay` example in the IDE.

It is possible (as long as you're not counting too fast) to incorporate the time element into the interrupt routine by keeping track of the time in a variable:

    volatile uint32_t rps = 0;

    void count() {
        static uint32_t revolutions = 0;
        static uint32_t timestamp = millis();

        revolutions++;

        if (millis() - timestamp >= 1000) {
            timestamp = millis();
            rps = revolutions;
            revolutions = 0;
        }
    }
    ....
    attachInterrupt(0, count, FALLING);

Then you can just reference the `rps` variable at any time to get the revolutions per second. Again it should really be queried inside a *critical section* to prevent the value being changed while you're actively reading it...

    cli();
    uint32_t myRPS = rps;
    sei();

    Serial.print(myRPS);
    Serial.println(F(" revolutions per second"));


message:
PWM output while using I2C with the ATTiny library

I've noticed that when using the USI interface on the ATTiny to send I2C via the methods from "Wire.h" with the ATTiny Arduino implementation included from the library manager ([ATTinyCore][1]), while `analogWrite` PWM on PB4 (Arduino pin 4, physical pin 3) works OK, it seems attempting to use it on PB1 (Arduino pin 1, physical pin 6) behaves erratically or hangs the processor.

Is this expected behavior, and is there a workaround? With the `SDA` line on PWM pin 0, physical pin 5 if that's the case it means when using the hardware USI to do I2C communications, I'm down to a single hardware PWM output, which is kind of a bummer.

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

  [1]: https://github.com/SpenceKonde/ATTinyCore
  [2]: https://i.stack.imgur.com/9LFZx.jpg

body:
This is normal.

Timer0 is used as the clock source for the USI. It's the only internal clock source that can be used. The only other option is to use "software polled" mode where it's up to the sketch (or support library) to manually create the clock signal (less than desirable) by setting a bit in a register at the right time.

So you can only use Timer1 for your own (PWM) purposes while using the USI.


message:
Reading and comparing data from Arduino Uno EEPROM

I'm trying to read compare data from EEPROM (Arduino UNO). Reading is working fine but comparing it using the '==' operator is not working as expected.

    //string 'True' is already stored in EEPROM

    int addr = 0;
    char value = EEPROM.read(addr);

    Serial.println(value);// this line successfully prints the letter 'T'

    // but this function is not working
    if (value == "T") {
      Serial.println("foo");
    }

body:
There is a HUGE difference between `"string"` and `'c' 'h' 'a' 'r'`.

You are comparing address of string `"T"` with the numerical value of character `'T'`.

The expression: `if (value == 'T')` will be much better.