text:
How to recover an I2C bus when SDA is stuck low? Edit: SDA line stuck high
See edit at the end of the message.
I have an Arduino in master mode connected via I2c to a slave, with 2k pull-up resistors on SDA and SCL. Sometimes the SDA line is stuck low, which causes my program to hang indefinitely.
How to recover from such a scenario?
Edit1: Since the SDA line is tied low the problem probably comes from the master. My guess is that the slave waits for the rest of the clock pulses that never come.
I'm not using the Wire library. I wrote my own implementation based on the AMmega328P datasheet.
void TWIInit() {
  TWSR = 0x00;
  TWBR = 0x48; // SCL = 100khz
  TWCR = (1 << TWEN);
}

void TWIStart() {
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
}

void TWIStop() {
  TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
  while (TWCR & (1 << TWSTO));
}

void TWIWrite(uint8_t data) {
  TWDR = uint8_data;
  TWCR = (1 << TWINT) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
}
unsigned int TWIReadACK() {
  TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
  while ((TWCR & (1 << TWINT)) == 0);
  return TWDR;
}

unsigned int TWIReadNACK() {
  TWCR = (1 << TWINT) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
  return TWDR;
}

unsigned int TWIGetStatus() {
  unsigned int statusOfRegister;
  statusOfRegister = TWSR & 0xF8;
  return statusOfRegister;
}

int TWISendBytes(uint8_t slaveAddr, uint8_t regAddr, uint8_t buf[], int numbBytes) {
  TWIStart();
  if (TWIGetStatus() != 0x08) {
    TWIStop();
    return 1;
  }
  // send address and Write bit
  TWIWrite(slaveAddr & 0xFE);
  if (TWIGetStatus() != 0x18) {
    TWIStop();
    return 1;
  }
  // send the register address
  TWIWrite(regAddr);
  if (TWIGetStatus() != 0x28) {
    TWIStop();
    return 1;
  }
  // send bytes
  for (int i = 0; i < numbBytes; i++) {
    TWIWrite(buf[i]);
    if (TWIGetStatus() != 0x28) {
      TWIStop();
      return 1;
    }
  }
  TWIStop();
  return 0;
}

int TWIGetBytes(uint8_t slaveAddr, uint8_t regAddr, uint8_t buf[], int numbBytes) {
  TWIStart();
  if (TWIGetStatus() != 0x08) {
    TWIStop();
    return 1;
  }
  // send address and Write bit
  TWIWrite(slaveAddr & 0xFE);
  if (TWIGetStatus() != 0x18) {
    TWIStop();
    return 1;
  }
  // send the register address
  TWIWrite(regAddr);
  if (TWIGetStatus() != 0x28) {
    TWIStop();
    return 1;
  }
  // repeated start
  TWIStart();
  if (TWIGetStatus() != 0x10) {
    TWIStop();
    return 1;
  }
  // send address and Read bit
  TWIWrite(slaveAddr | 0x01);
  if (TWIGetStatus() != 0x40) {
    TWIStop();
    return 1;
  }
  // get bytes
  for (int i = 0; i < numbBytes; i++) {
    if (i == (numbBytes - 1)) {
      buf[i] = TWIReadNACK();
      if (TWIGetStatus() != 0x58) {
        TWIStop();
        return 1;
      }
    } else {
      buf[i] = TWIReadACK();
      if (TWIGetStatus() != 0x50) {
        TWIStop();
        return 1;
      }
    }
  }
  TWIStop();
  return 0;
}

Edit2: The SDA line, and SCL, is held high not low as I first incorrectly assumed (I probably did something wrong when I measured it and thought it was low but anyway.) The problem was that the resistors I was using as pull-up resistors were in fact 1k not 2k. I changed them for 2k resistors and the problem disappeared.

First you'd have to figure out how it is happening.  If resetting the ATmega CPU doesn't clear it, it's probably not the Arduino's fault, and hence off-topic here.  Identification of the chip and traces captured with a cheap logic analyzer would be a help.  I recall a temperature/humidity chip that would jam the bus so badly if read in a certain mode that even removing power wouldn't clear it, you had to literally short the supply rail to ground.

write non blocking code

@ChrisStratton Resetting the Arduino clears it. And I realized that if the SDA line is low it is because the slave is waiting a clock from the master. So the problem must comes from my code. Also I'm not using the Wire library but instead wrote my own functions to handle the I2C communications. So it is likely there's a problem in the way I implemented it.

Is the problem gone when you do use the Arduino Wire library?

Ok so I found the issue. First the SDA line wasn't low but high. Second, I was using 1k pull-up resistors. So the actually issue was that the resistors prevented the slave or master to drive the line low. I changed them for 2k resistors and it stopped hanging. As an additional safety I added a watchdog to reset the Arduino if the program is hanging. @Jot The problem was the same with the Wire library.

I solved the problem by replacing the pull-up resistors with 2k Ohm resistors. I thought I connected 2k Ohm resistors when in fact their value was 1k. So sometimes the SDA line couldn't be driven low due to the too strong pull-up resistors and that caused the hanging.

4.7k is the more generally accepted value for the pull-ups. I have some screenshots here of the effect of different values for the resistors.


text:
Arduino library creation - Calling library and Merging
I am new to creating a library in Arduino. I was able to create a library from YouTube. I want to merge two other libraries into the library I created. Can you please help me to do so?
I already created a keywords.txt file for my library but the keywords are not getting highlighted in orange in the IDE. But it identifies as keywords.
Please guide me how to properly create a keywords file and merge the libraries.
Keywords below:
# -----------------------------------------------------------------------------------
# Syntax coloring for IotBlueEmon library
# -----------------------------------------------------------------------------------

# Datatypes (such as objects)
CurrentSense KEYWORD1

#Methods / functions
begin   KEYWORD2
Counter1   KEYWORD2
Counter2   KEYWORD2
counter3   KEYWORD2
getCNT1   KEYWORD2
getCNT2   KEYWORD2
getCNT3   KEYWORD2

# Constants

please delete the comment. it clutters up the post. you have added it correctly to the question. (there is a little red X next to the comment. it shows up when you hover the mouse pointer over the comment)

If you consult the Arduino Library Specification's section on keywords.txt:

A tab should be used to separate each name from the KEYWORD1/Keyword2/Literal1 identifier.

A true tab character is required, rather than spaces, as you have in your keywords.txt. It is common for text editors to be configured to add a given number of spaces when the tab key is pressed rather than a true tab character. That's great but in this case you will need to be sure that the tab character is used.
Note that the tab requirement will be relaxed in the Arduino IDE 1.9.0 release, which will also accept space(s) as a keywords separator but it's still best to use tabs for backwards compatibility since people will be using pre-1.9.0 IDE versions for years to come.

source: Stack Exchange

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

sort: votes


text:
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:
#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;
    }
}

you check for state StateGarage_Alarm, but you have no command that actually causes the state machine to enter that state. .... your state machine has some questionable functionality ... the StateGate_Opening state code sets the state to StateGate_Open without checking if the gate actually opened.  ... similar thing is being repeated in other parts of the code

the StateGate_Open is actually the problem with the code

for state 'StateGarage_Alarm', i've been doubting where should connect it to, and thought that with 'if' function it can be worked, so is it better to connect it to 'StateGate_Open' or 'StateGate_Closing' ?

what is the problem with 'StateGate_Open'? do i need to create 'boolean openGate'?

You could refactor this code and make it much easier to debug.  Each case could be reduced to a 5 element structure {IN1State, IN2State, EnableA, EnableB, StateGArage}.  garageClosed could be replaced with two extra StateGarage_ entries Opened and Closed.

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.

I have made the code like your example, but I made the structures separately for both state machines. It has 269 lines in total (longer than the first one). And both of the state machines did not operate....
Could you please tell me what is wrong? I left the code on my question above

I don't understand why you have duplicated the data and motor structures, there is no need.  You have also copied the state machine from the gate and used it for the garage, you have even left the letters the same.  This answer was not about making your code shorter, it was about making it easier to debug an maintain.

Feel free to mark it as an answer then.

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


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

data and http header are separated by an empty line. then see ArduinoJson library

@Juraj can you please explain data and header saperately by an empty line, is it good? Arduino output is exactly like this.

what you printed is a HTTP response. starting with HTTP/1.1 status line, then there are the HTTP headers. and then the empty line separates the header from body. in the body are your data. try using ArduinoHttpClient library over WiFiEspClient, if you do not want to parse the response self.

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.


text:
Platform-independent functions for FastPWM?
I learned from answers here 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. These calls enable FastPWM.
I checked the Arduino API reference, but not sure which are the equivalent to above. How to determine?

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_digital.c

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

Man, you're good! But, these fx are specifically to enable FastPWM. Any higher-level calls for FastPWM? thx!

Not that I am aware of in the standard Arduino API. We have them in the chipKIT API, and it's something we'd like to see adopted upstream, but alas not yet.

sweet! Chipkit is for programming AVR's with Java?

What on earth would give you that impression? chipKIT is for programming PIC32s with the Arduino API.

Why on Earth would you mention a pic library in an Arduino question?

It's not a library. It's a core. For the Arduino IDE. To implement the Arduino API. Like the DUE core or the ESP8266 core or the Maple core... OR... the ATTiny core. That's not Arduino. That's a third party core that implements the Arduino API. Exactly like chipKIT, just for a different architecture.

Ok, you mentioned ChipKIT API. i was not familiar with it. I assumed it had some relevance to this question. Your reply "What on earth would give you that impression" was unnecessarily disrespectful-- you spoke to me like i'm stupid. But i'm not stupid, i'm just unfamiliar with ChipKIT. No matter-- treating people like they're stupid is standard behavior for many people on stackexchange, including you too we see. Nothing unusual about it.

I was just surprised you got java from it somehow. I'd love to know the thought processes that resulted in Java...

i prolly saw java mentioned someplace in connection with chipKIT. My misunderstanding. http://chipkit32.github.io/chipKIT-core/core_how_to_hack_chipkit_core.html


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

What is your 9V supply?

Somethinf like this 9V Cell
https://www.google.com/search?client=firefox-b-ab&biw=1600&bih=777&tbm=isch&sa=1&ei=3bFPWvylDY3zsAG_h6uwBw&q=9V+cell&oq=9V+cell&gs_l=psy-ab.3...5364.6839.0.6980.0.0.0.0.0.0.0.0..0.0....0...1c..64.psy-ab..0.0.0....0.5s6BwlO-sC8#imgrc=0YK2n3P6ubCsVM:

Oh dear. Well, there you go then. Get a real battery or a mains power supply.

But fore some minutes  it works good, Is it real to get this problem using this cell?

Yep. Those batteries have almost no power.

And how can you explain me :)

I don't know how anyone can explain you. You're inexplicable.

It seems that you do not know exactly :D, and be carefull when are you commenting and see the screen every seceonds ;).

The PP3 batteries have around 154mAh. A typical AA cell has around 1500 to 2000mAh. Just a comparison. Add to that the fact that you're throwing away about half your power with the onboard 5V regulator...

Also asked at: http://forum.arduino.cc/index.php?topic=520835 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

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

You need a power source that can provide 2A at the rated input voltage of your module (5V?)
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.


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

Where does pirState come from? It hasn't been defined or initialized. And what signal is on inputPin? The general logic for doing something depending on either of two conditions is if( condition1 || condition2 ){ // do something here }

To make it easier you could add two boolean variables 'dark' and 'motion'. Make it true if it is dark and false for light and the other one true for motion and false for no motion from the PIR sensor. Then you can do the if-statement as @JRobert wrote about.

pirState is from the PIR Sensor, i was thinking that it should always be on low if there is no movement, I don't know if its the right way to do that but for now works. And the inputPin is also from the pir sensor.

your problem is that you do not have the program clear in your mind ... you do not want I want to light one led with two sensors .... you want monitor two sensors and light one LED .... you said that you have done it with two LEDs, so just modify your code so that both sensors have to satisfy a goal before the LED is activated

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

To keep it simple serial code is removed, if needed can be added easily that should not be a big issue.
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"

Yes, it works. Now I just need to print some messages so I can figure out which sensor turned the led on, because I will have 8 sensors in total, 4 of each. Thank you for the help!

@gollum updated answer with code for serial comm. Do compile n test.

I got an error: "Boolean was not declared in this scope". @25mhz

Try "bool" it should work

That should be "boolean" my bad, dint check that.


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

Tried upping the voltage in case it wasn't getting enough current.
Tried different ESP01s.
Tried switching TX and RX pins.
Tried using different pins on the Uno (2 and 3, 10 and 11, 7 and 8).
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?
#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

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

Please explain in your answer how this solves the problem. That way future viewers know how to solve this issue and why it fixes the problem.

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

Remove pinMode(RX, INPUT);
and pinMode(TX, OUTPUT);.
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.

"SoftwareSerial isn't going to relay the response back"? Not clear what you were expecting, but @jdwolf's example of two while loops is the correct way to communicate from the Uno's terminal to an Uno-connected serial device. ESPs do indeed respond back and SoftwareSerial does collect that response for you. What do you mean by "you have to program a response in"?

RX from Arduino goes to TX on EXP, and
TX from Arduino goes to RX on ESP, BUT
Why not just put ESP01 in program mode and upload adruino code directly to it doing away with the AT commands

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


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

the pins don't seem to go into the same ports - can you elaborate on that? What do you mean by "same"?

Sorry im new to all this, what i mean is that the pins on the LCD dont seem to match up where the instructions in the code say they should go, (or at least where i think they should go)

OK, what sketch? Link please.

Are you just jamming a vanilla LCD module directly into the side of an Arduino rather than wiring it in properly? An LCD screen is not a shield.

I think you are assuming the pins of the LCD screen match up 1:1 with the pins of the shield. That is wrong. Very wrong. You should start with a tutorial for similar shields (they're all the same, for certain values of "same"), such as this one.

I followed a clip on youtube, but I basically have no idea what I am doing. The display that I have does seem to be designed to plug into an Arduino, it has pins on both sides that line up with the socket on the Arduino (the reset, a0-a5 etc).

this is the sort of thing I tried, the display is very similar to mine. Arduino LCD / Keypad Shield

This seems to be the exact same display as mine - Module Review #1 - LCD Keypad Shield for Arduino

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:
 /*
  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:

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

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 (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.  This is what most people buy and call the LCD. Many Arduino sketches are written for the Hitachi LCD Controller. 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:

It is possible your contrast in incorrectly set.  Identify if this control is available on the shield you are using and consider adjusting it.
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.
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.  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.

Thank you very much for such a detailed answer, I have used my multimeter and it turns out the pins on the green controller board under the display don't line in the same order as the pins on the LCD keypad shield.

I thought you bought those two (the green LED board (which likely has an Hitachi like interface) and the darker Arduino shield board) together from the same vendor!  Why would they not line up?

it came assembled as one unit. When I used my multimeter to check which pins on the green board were connected to which pins on the black board they seemed to come out different to what everyone else has

Ah! I see.  Well, there are differences between the Uno and Mega 2560.  See this discussion for more.  However I doubt this is the problem.  Note that many Hitachi LCD type board can work in 8 bit mode, 4 bit mode and even serial (uses only 1 bit) mode.  It looks like the sketch you are using is setting up the pins for 4 bit mode.  As what is written in the sketch does not match the wiring of the black board I still say you are using the wrong sketch.  Humm, are you using "LiquidCrystal lcd"? Let me add something to my answer.

Hum, this contrast issue is troublesome.  I see a big multi turn pot right next to the LCD's V0 pin.  I'm betting that controls the contrast and not the Arduino's pin 13 as you have in your question.


text:
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). 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.  (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?

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 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.  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 library.  It is the fastest, smallest, most accurate and most reliable GPS library.  It can help you detect (and reject) bad data.

Great answer slash-dev. 5 Bi-Directional Logic Level Shifters for $1.18USD. https://www.aliexpress.com/item/5pcs-lot-5V-3V-IIC-UART-SPI-Four-Channel-Level-Converter-Module-for-Arduino-Free-Shipping/1821378018.html?spm=2114.search0104.3.37.RsrApE&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10151_10065_10130_10068_10344_10547_10342_10343_10340_10548_10341_10084_10083_10139_10307_10059_10314_10534_100031_10604_10103_10142,searchweb201603_25,ppcSwitch_5&algo_expid=f05a8d79-9069-444a-b5e8-cf1361ee8656-5&algo_pvid=f05a8d79-9069-444a-b5e8-cf1361ee8656&transAbTest=ae803_4&priceBeautifyAB=0


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

What means are you using to verify that both of these devices exist right now ?  Incidentally, unlike some other operating systems, these identifiers are newly assigned each time the device is connected, and may refer to different devices at different times.  You can even get the assigned numbers to increment with a single device, if a program holds the old device file open while it is re-plugged.

What does ls -l /dev/serial/by-id show?

You can also verify it with gtkterm. Click "Configuration" and "Port" and open the drop down menu "Port:". Check if they both are there. Perhaps you can try the Arduino IDE with sudo. Did you set some kind of permission to /etc/ttyUSB0? Remove all the Arduino and Java from the repositories. Unpack the newest Arduino IDE into a folder and start it from that folder. Be sure to remove the librxtx-java from the repositories (I use synaptic).

@Jot this looks blind guessing

@ChrisStratton I can communicate with them, and they answer differently

Dims, did you try to run the Arduino IDE with sudo ? Can you tell which Arduino boards are connected? Has one of them a unknown bootloader? Did you remove Arduino, Java and librxtx from the repositories ?

Terrible advice.  You should NEVER EVER run the Arduion IDE (or any similar software) as root.  It's not designed to be safe for such use, and you run the risk of leaving behind files which your normal user won't be able to clean up or change.  Instead, either set up proper udev rules, put yourself in the group that owns serial devices, and restart.  Or temporarily chown the device in question to yourself - but if you do that you'll have to each time you plug it in.

just because a user has permission to access a serial port, does not mean the a user has permission to access any other ports ... access has to be granted for each com port separately, or a user has to be belong to a group that has access to previously specified ports

You have to add use your user to the dialout group, as explained in the installation instructions for Linux.
sudo usermod -a -G dialout $USER

Then log out and back in again.


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

This line looks wrong: digit(int(number-floor(number/10))); - don't you want the number mod 10? That is: digit (number % 10);

If the number is 42 your calculation would give you 42 - 4 which would be 38 and that is not in the range 0 to 9.

Looks like I forgot to multiply the tens by 10 first before subtracting it.

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

That worked. Thanks. I'm ashamed the solution was so easy.


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

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.

Thanks for the detailed answer. I'll give it a try and if something goes wrong, i'll try to find solution for noise mitigation. The thing is that near the cable(10 cm or 4 inches) there is a solenoid powered pump which is the reason i chose a shielded cable.


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

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:

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?

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.

Option A): Do I need a I2C converter between Wemos and LCD? Like this: https://www.digibay.in/image/cache/data/sachinelectronics/ED01/ED01-09-0020-A-600x600.jpg. Option B: Do you have a sample code or schematic code? Thanks.

A) you could do that to save pins, but you don't have to. B) Google for Serial input basics by Robin2 on forum.arduino.cc

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 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 is an Arduino sketch for the esp8266.


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

A Beginner's Guide to the ESP8266 Yes, you need an external power supply. Note that programming it would be much easier if you bought a USB-to-Serial adapter that breaks out both the DTR and RTS control lines. Or even better, get a WeMos D1 mini or similar.

@tttapa, why external power supply? I don't use one if connected to USB to UART.

@Juraj, the ESP8266 draws a lot of current, especially during WiFi transmission. The 3.3V from the USB to UART is just for the output drivers and maybe some external logic, it's not meant for driving any real loads. For instance, the 3.3V output from an FT232R is only rated for 50 mA. It can't handle the peak currents needed for RF communication. The ESP8266 can draw up to 300mA peak. Many people experience instability because of an incapable power supply.

Thanks so far for the answers. Recording to the "Beginner's Guide" i have connected the pins tx, rx and gnd to the esp01. Understanding this guide correctly i now need to connect the CH_PD and GPIO0 with a 10k resistor to Vcc, So after adding a power source i can start programming, right?

@tttapa, but for flashing is the 50 mA enough.

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.

You can program the ESP-01 whith described method in this page:
https://zinventor.wordpress.com/primeros-pasos-con-esp8266/
Its works fine!


text:
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 is where i bought it from.
The display
My Arduino

your device uses two controllers. ILI9341 and XPT2046.

Maybe, then, you should buy your toys from somewhere that at least gives you a clue what to do with them. Anyway, the pins are clearly marked.

section 7.6 of the ILI9341 datasheet

@Majenko in romania this kind of resources are found in a very small amount of shops.

@jsotola i am new to this stuff, can you help me understand what is going on there?

@xM0nSt3r So buy from somewhere that isn't Romania?

@jsotola by resources i mean parts like lcds, arduinos or anything from this niche.

@jsotola i know it has that diagram but can i use transistors to lower the voltage instead that logic level translator?

why is your question so general?  please update your question to be more specific.  ask what you are really asking ... (deleting my useless comments) ....

do some research ... there is a lot of information on this website about converting 3.3V signals to 5V

@jsotola a'right i am going to look into it, thank you for your time.

You can get it working by two methods

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

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

Can you give me more details about the wiring?

Read the words on the board and compare them to either the SPI manual page or the instructions for the library.

but can i use transistors to lower the voltage instead of that logic level translator?

Sorry, what are you talking about?

on the page i mentioned in the question it says i have to use this  to make it work, can i replace that with transistors?

Ah, it's a 3.3v display. You will need something to lower the 5V to 3.3V for the SPI signals. You may get away with resistive dividers, if you are lucky.

can you send me a link to those?

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


text:
DIY printer + Arduino. Can I use the position sensor? Multithreading?
I'm trying to make a computer-controlled painter/drawer/CNC, something like this, 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: 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?

You should really study how Arduino-based 3d printer firmwares (most of which are open source) solve this problem.  The tape you are describing is an incremental encoder, so it will only give you position if you count all of the changes in moving from a start position determined by something else such as a limit switch.

You could also look into using Grbl, which is a CNC style controlling software.  That might be able to help you run your motors, as it would be working with generic g-code, rather than having to invent a language yourself.

I strongly support @computercarguy. Building the CNC itself if enough work. And you need to be able to read the files exported by 3D design software. Better use an available software.

You can multitask 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.

Can it do IO threading? Or, with the way Serial.read() works blocking, would it be best to send a command like 'Left3 Forward4' and then run those at the same time with start motor1, start motor2, end motor2, end motor 1?

servo motor control is done using timed pin manipulation, serial communication auto fills a buffer that Serial.read() pulls out of. All of that can be done without ever blocking.

I recommend using the AccelStepper library (installable via the Library Manager) which will allow you to drive multiple stepper motors at once without blocking commands.

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


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

please add a schematic of your connections

You say you are supplying the ACS712 from an external supply.  Do you have the Arduino ground and the external supply ground connected?  A full schematic would be more useful because possibly the problem is not in the part shown.

Maybe you are just measuring an AC current, in which case the “fluctuations” are normal and expected.

@Mark Smith I am not using Arduino Gnd ACS712 is using Gnd from External PowerSupply....From Arduino I am only using its Analog Pin 0

@Edgar Bonet I am using DC supply as current source to ACS712

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.

You are awesome...Thanks for your help much appreciated. Solved my problem

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


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

where are you measuring 1.8v?

I wrote a simple sketch in my ide that pushes High and low voltage to one of my esp's output pins, with a 1 second delay in between each.

If you are measuring 1.8v, you are loading the pin beyond it's designed capability.

yes I should be using a resistor, it was a quick test.

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.

What I'm actually trying to do, is use an existing circuit's motor driver, and use the esp, to send the signals to it. The existing circuit has it's own 4.8 bat, and I have identified and soldered into the circuit at each point to send power to dc motor(s) L/R/B/F and an additional extended ground wire.  The esp is has its own power and will be the controller. I saw another post where someone was doing this but with an arduino uno (which works). Here are the pictures to the circuit before I soldered into it: https://1drv.ms/f/s!ApWkEol-uDERpBrBrpQp76IVMDuo

To have a valid question, you need to include the input specifications of what you are driving in the body of your question.  External links aren't really acceptable for critical parts of the problem statement.

Ok. Thanks for your answers. I think I figured out my problem.

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.

Then your LED was improperly connected.  Likely you forgot the current limiting resistor, or else you chose an LED and LED current which exceeded the capability of the ESP32.

Hi Chris, I was being lazy and just forgoing the resistor to test it quickly. Thanks


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

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

you use very annoying comment style in  your code. repeating the same thing over and over only makes the code less readable.

quickly returns to 0  ... how long does it take to return to zero?

jsotola it takes about a second

its almost as if Serial.parseInt is not going to my val integer...

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.

Thank you very much  VE7JRO, care to explain the second one? This one works, the first one not so much...even with the serial monitor set to "No Line Ending"
I think i understand my mistake now, i had int val; in my main program, resetting its value each loop around!!

Which O/S are you using? I'm wondering if the Serial Monitor behaves differently on different O/Ses. I'm using a very old version of OSX, 10.6.8.

I've add some comments to the while loop section of the second sketch.

i am using Windows 7 x64. thanks so much for the comments, very helpful!