body:
I'm working on a project that has 3 RGB LEDs. I want to make a simple method that I can call to control the LEDs for example:

    showColor(left, 255, 0, 50);

Which would light up the left LED at 100% red, 0% green, and 20% blue. The code I have running for the method is:

     void showColor(int ledPosition, int redIntensity, int blueIntensity, int greenIntensity)
        {
          if (ledPosition == left)
          {
            analogWrite (redPin1, redIntesity);
            analogWrite (greenPin1, greenIntesity);
            analogWrite (bluePin1, blueIntesity);
          }
          else if (ledPosition == middle)
          {
            analogWrite (redPin2, redIntesity);
            analogWrite (greenPin2, greenIntesity);
            analogWrite (bluePin2, blueIntesity);
          }
          else if (ledPosition == right)
          {
            analogWrite (redPin3, redIntesity);
            analogWrite (greenPin3, greenIntesity);
            analogWrite (bluePin3, blueIntesity);
          }
          else if (ledPosition == all)
          {
            for (int index=0, index < 3 ; index++)
            {
              analogWrite (redPins[index], redIntensity);
              analogWrite (greenPins[index], greenIntensity);
              analogWrite (bluePins[index], blueIntensity);
            }
          }
        }

I'm getting tons of errors, like that all of the Intensity variables are not declared and that left, right, all, and middle are not declared. I don't know if this is possible, or what I'm doing wrong. I think I've seen something like this before somewhere else, and I don't want to just use 1 variable to control everything. An answer would be greatly appreciated!

title: Is there a way to put multiple integers in a method?

Answers: 3

body:
Check your spelling `Intensity` instead of `Intesity`.

Consider using `switch` instead of `if-then-else`.

Define `left`, `right` and `middle` as [integer] constants somewhere (and probably something more descriptive like `rightLED`, `leftLED` and `middleLED`) because your code is looking for an `int`, instead you give it something undefined like left, right and middle (and all). I would consider using bitwise operators for identifying the LEDS, instead of a simple integer flag as this gives future flexibility in lighting up combinations without changing your code (the current function would be rewritten to accommodate this).

body:
There are two errors in your code:

1. The word “Intensity” should always be spelled like this, rather than
   “Intesity” (missing “n”)
2. In `for (int index=0; index < 3; index++)`, the separators should be
   semicolons, not commas.

Other than that, and provided proper declarations, your function
compiles just fine.

body:
This answer is slightly off track, but after reading the title my first though was this.

You can have a function that takes multiple integer parameters and there is nothing wrong with that, but there comes a point in your code where you should be looking at better data management.  In this case you have three intensity values that are always going to be related so you could look at a class or struct to hold the data as a single object.

    struct Colour
    {
        int Red;
        int Green;
        int Blue;
        Colour (const int& r = 0, const int& g = 0, const int& b = 0)
            : Red(r)
            , Green(g)
            , Blue(b)
        {}
    }

This would allow you to define an object (called LEDLeft) that held the value for that LED, i.e.

    Colour LEDLeft(0xFF, 0xFF, 0x00);    // Define a yellow left LED.

Extending this further you could define a second structure that defined the pins to control the LED, and a third that paired the current colour with the LED.

    struct LED
    {
        LEDPinout Pins;
        Colour    Colour;
       // Constructor ...
    }

Its about this point that using a class rather than a struct would be a better (more conventional*) idea.  i.e.

    // THIS IS NOT COMPLETE CODE - IT HAS NOT BEEN TESTED.
    class LED
    {
        LED (const int& pinRed, const int& pinGreen, const int& pinBlue);
        LED (const LED& other);  // Copy constructor

        void SetColour(const Colour& colour);
        Colour GetColour(void)const;
    }

    static const Colour RED(0xFF, 0x00, 0x00);
    static const Colour BLUE(0x00, 0x00, 0xFF);
    enum Positions {Left = 0, Middle, Right, All};
    LED TheLeds[] = {LED(2, 3, 4), LED(5, 6, 7), LED(8, 9, 10)};
    TheLeds[Left].SetColour (RED);
    TheLeds[Right].SetColour (RED);
    TheLeds[Middle].SetColour (RED);
    delay(1000);
    for (int loop = 0; loop < All; ++loop)
        TheLeds[loop].SetColour(BLUE);
    delay(1000);


body:
    #include <avr/sleep.h>

    int wakePin = 2;                 // pin used for waking up
    int led=13;
    int flag=0;

    void wakeUpNow()
    {
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up
      int count=10;
      while(count!=0)
      {
        delay(1000);
        count--;
        Serial.println(count);
        delay(1000);
      }
    }

    void setup()
    {
      Serial.begin(9600);
      pinMode(wakePin, INPUT_PULLUP);  // wakePin is pin no. 2
      pinMode(led, OUTPUT);          //   led is pin no. 13
      attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
    }

    void sleepNow()
    {
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
        sleep_enable();                        // enables the sleep bit in the mcucr register
                          delay(500);
                          Serial.println("Rajat");
                          delay(500);
        attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                          delay(500);
                          Serial.println("Rajat");
                          delay(500);
        sleep_mode();     // here the device is actually put to sleep...!!
          // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                          delay(500);
                          Serial.println("Rajat2");
                          delay(500);
        detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
        sleep_disable();         // first thing after waking from sleep: disable sleep...
                          delay(500);
                          Serial.println("Rajat3");
                          delay(500);
           detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.

    }

    void loop()
    {
          digitalWrite(led, HIGH);
          delay(1000);
          digitalWrite(led, LOW);
          delay(1000);
        /* delay(500);
          Serial.println("jam");
          delay(500);  */
          if (flag==0)
          {
          sleepNow();     // sleep function called here
          flag=1;
          }
    }

After Last Rajat I give ground to INT0.

Output in serial monitor :

    Rajat
    Rajat
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    9
    8
    7
    6
    5
    4
    3
    2
    & so on..!

title: detachInterrupt(0) in arduino not working ? after giving continuous ground to INT0 wakeupnow function should execute once not again and again

Answers: 1

body:
You're detaching in completely the wrong place. After sleep_mode() returns from sleep and before the interrupt is detached you have an entire second of time where your interrupt can still fire. And it *will* fire, since a `LOW` interrupt will keep firing *while* the input is `LOW`.

    sleep_mode();     // here the device is actually put to sleep...!!
      // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                      delay(500);
                      Serial.println("Rajat2");
                      delay(500);
    detachInterrupt(0);

Instead you should detach the interrupt within the interrupt routine itself:

    void wakeUpNow()
    {
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up

        detachInterrupt(0);

      int count=10;
      while(count!=0)
      {
        delay(1000);
        count--;
        Serial.println(count);
        delay(1000);
      }
    }

Also, all those delays and Serial prints in an interrupt are seriously problematic. An interrupt should *never* `delay()` and should *never* `Serial.println()`.


body:
I am using Arduino UNO and has kept in SLEEP_MODE_PWR_DOWN mode & want it to wakeup using MPU6050 hardware INT pin (which should send a signal when MPU is in motion). I have used the article https://lukelectro.wordpress.com/2016/08/11/how-to-enable-motion-detection-interrupt-on-mpu6050/

        #include <Wire.h>
        //Analog port 4 (A4) = SDA (serial data)
        //Analog port 5 (A5) = SCL (serial clock)
        #define SIGNAL_PATH_RESET  0x68
        #define I2C_SLV0_ADDR      0x37
        #define ACCEL_CONFIG       0x1C
        #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
        #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
        #define MOT_DETECT_CTRL    0x69
        #define INT_ENABLE         0x38
        #define WHO_AM_I_MPU6050   0x75 // Should return 0x68
        #define INT_STATUS 0x3A
        //when nothing connected to AD0 than address is 0x68
        #define ADO 0
        #if ADO
        #define MPU6050_ADDRESS 0x69  // Device address when ADO = 1
        #else
        #define MPU6050_ADDRESS 0x68  // Device address when ADO = 0
        #endif

        /*    Example for using write byte
              Configure the accelerometer for self-test
              writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0xF0); // Enable self test on all three axes and set accelerometer range to +/- 8 g */
        void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
        {
          Wire.begin();
          Wire.beginTransmission(address);  // Initialize the Tx buffer
          Wire.write(subAddress);           // Put slave register address in Tx buffer
          Wire.write(data);                 // Put data in Tx buffer
          Wire.endTransmission();           // Send the Tx buffer
        //  Serial.println("mnnj");

        }

        //example showing using readbytev   ----    readByte(MPU6050_ADDRESS, GYRO_CONFIG);
        uint8

    _t readByte(uint8_t address, uint8_t subAddress)
    {
      uint8_t data;                            // `data` will store the register data
      Wire.beginTransmission(address);         // Initialize the Tx buffer
      Wire.write(subAddress);                  // Put slave register address in Tx buffer
      Wire.endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
      Wire.requestFrom(address, (uint8_t) 1);  // Read one byte from slave register address
      data = Wire.read();                      // Fill Rx buffer with result
      return data;                             // Return data read from slave register
    }

    void setup()
    {
       /*
        * #define SIGNAL_PATH_RESET  0x68
          #define I2C_SLV0_ADDR      0x37
          #define ACCEL_CONFIG       0x1C
          #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
          #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
          #define MOT_DETECT_CTRL    0x69
          #define INT_ENABLE         0x38
          #define WHO_AM_I_MPU6050 0x75 // Should return 0x68
          #define INT_STATUS 0x3A*/
        Serial.begin(9600);
        writeByte( MPU6050_ADDRESS, SIGNAL_PATH_RESET, 0x07);//Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
        writeByte( MPU6050_ADDRESS, I2C_SLV0_ADDR, 0x20);//write register 0x37 to select how to use the interrupt pin. For an active high, push-pull signal that stays until register (decimal) 58 is read, write 0x20.
        writeByte( MPU6050_ADDRESS, ACCEL_CONFIG, 0x01);//Write register 28 (==0x1C) to set the Digital High Pass Filter, bits 3:0. For example set it to 0x01 for 5Hz. (These 3 bits are grey in the data sheet, but they are used! Leaving them 0 means the filter always outputs 0.)
        writeByte( MPU6050_ADDRESS, MOT_THR, 0x14);  //Write the desired Motion threshold to register 0x1F (For example, write decimal 20).
        writeByte( MPU6050_ADDRESS, MOT_DUR, 0x01 );  //Set motion detect duration to 1  ms; LSB is 1 ms @ 1 kHz rate
        writeByte( MPU6050_ADDRESS, MOT_DETECT_CTRL, 0x15); //to register 0x69, write the motion detection decrement and a few other settings (for example write 0x15 to set both free-fall and motion decrements to 1 and accelerometer start-up delay to 5ms total by adding 1ms. )
        writeByte( MPU6050_ADDRESS, INT_ENABLE, 0x40 ); //write register 0x38, bit 6 (0x40), to enable motion detection interrupt.     */

        pinMode(13, OUTPUT);      // sets the digital LED pin 13 as output
        pinMode(7, INPUT);        // sets the digital pin 7 as input

    }
        uint16_t readdata;
    void loop()
    {
          Serial.println("scdf");

          if(digitalRead(7)==1)
          {
            while(1)
            {
              digitalWrite(13, 1);
              delay(100);
            }
          }

      //    readdata = readByte(MPU6050_ADDRESS,WHO_AM_I_MPU6050);
      //    Serial.println(readdata);
    }

title: How to generate hardware interrupt in mpu6050 to wakeup arduino from SLEEP_MODE_PWR_DOWN mode?

Answers: 1

body:
Well, this code worked. In this code, MPU's INT PIN is Active Low so generates Ground on motion which is than connected to INT0 or arduino UNO pin 2 which generates interrupt and wakes UP the MCU

    #include <avr/sleep.h>

    #include <Wire.h>
     //Analog port 4 (A4) = SDA (serial data)
    //Analog port 5 (A5) = SCL (serial clock)
    #define SIGNAL_PATH_RESET 0x68
    #define I2C_SLV0_ADDR 0x37
    #define ACCEL_CONFIG 0x1C
    #define MOT_THR 0x1F // Motion detection threshold bits [7:0]
    #define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
    #define MOT_DETECT_CTRL 0x69
    #define INT_ENABLE 0x38
    #define WHO_AM_I_MPU6050 0x75 // Should return 0x68
    #define INT_STATUS 0x3A
    //when nothing connected to AD0 than address is 0x68
    #define ADO 0
    #if ADO
    #define MPU6050_ADDRESS 0x69 // Device address when ADO = 1
    #else
    #define MPU6050_ADDRESS 0x68 // Device address when ADO = 0
    #endif

    int wakePin = 2; // pin used for waking up
    int led = 13;
    int flag = 0;

    void wakeUpNow() { // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP    (i.e. after getting interrupt)
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up

      delay(500);
      Serial.println("WOKEN UP !!!!!!!!!!");
      delay(500);
      int count = 10;
      while (count != 0) {
        delay(1000);
        count--;
        Serial.println(count);
        delay(1000);
      }
      // precautionary while we do other stuff
      detachInterrupt(0);

    }

    /*    Example for using write byte
          Configure the accelerometer for self-test
          writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0xF0); // Enable self test on all three axes and set accelerometer range to +/- 8 g */
    void writeByte(uint8_t address, uint8_t subAddress, uint8_t data) {
      Wire.begin();
      Wire.beginTransmission(address); // Initialize the Tx buffer
      Wire.write(subAddress); // Put slave register address in Tx buffer
      Wire.write(data); // Put data in Tx buffer
      Wire.endTransmission(); // Send the Tx buffer
      //  Serial.println("mnnj");

    }

    //example showing using readbytev   ----    readByte(MPU6050_ADDRESS, GYRO_CONFIG);
    uint8_t readByte(uint8_t address, uint8_t subAddress) {
      uint8_t data; // `data` will store the register data
      Wire.beginTransmission(address); // Initialize the Tx buffer
      Wire.write(subAddress); // Put slave register address in Tx buffer
      Wire.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive
      Wire.requestFrom(address, (uint8_t) 1); // Read one byte from slave register address
      data = Wire.read(); // Fill Rx buffer with result
      return data; // Return data read from slave register
    }

    void setup() {

      /*
       * #define SIGNAL_PATH_RESET  0x68
         #define I2C_SLV0_ADDR      0x37
         #define ACCEL_CONFIG       0x1C
         #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
         #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
         #define MOT_DETECT_CTRL    0x69
         #define INT_ENABLE         0x38
         #define WHO_AM_I_MPU6050 0x75 // Should return 0x68
         #define INT_STATUS 0x3A*/
      Serial.begin(9600);
      writeByte(MPU6050_ADDRESS, 0x6B, 0x00);
      writeByte(MPU6050_ADDRESS, SIGNAL_PATH_RESET, 0x07); //Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
      writeByte(MPU6050_ADDRESS, I2C_SLV0_ADDR, 0x20); //write register 0x37 to select how to use the interrupt pin. For an active high, push-pull signal that stays until register (decimal) 58 is read, write 0x20.
      writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0x01); //Write register 28 (==0x1C) to set the Digital High Pass Filter, bits 3:0. For example set it to 0x01 for 5Hz. (These 3 bits are grey in the data sheet, but they are used! Leaving them 0 means the filter always outputs 0.)
      writeByte(MPU6050_ADDRESS, MOT_THR, 10); //Write the desired Motion threshold to register 0x1F (For example, write decimal 20).
      writeByte(MPU6050_ADDRESS, MOT_DUR, 40); //Set motion detect duration to 1  ms; LSB is 1 ms @ 1 kHz rate
      writeByte(MPU6050_ADDRESS, MOT_DETECT_CTRL, 0x15); //to register 0x69, write the motion detection decrement and a few other settings (for example write 0x15 to set both free-fall and motion decrements to 1 and accelerometer start-up delay to 5ms total by adding 1ms. )
      writeByte(MPU6050_ADDRESS, INT_ENABLE, 0x40); //write register 0x38, bit 6 (0x40), to enable motion detection interrupt.
      writeByte(MPU6050_ADDRESS, 0x37, 160); // now INT pin is active low

      pinMode(2, INPUT); // sets the digital pin 7 as input

      pinMode(wakePin, INPUT_PULLUP); // wakePin is pin no. 2
      pinMode(led, OUTPUT); //   led is pin no. 13
      // attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW

    }

    void sleepNow() {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
      sleep_enable(); // enables the sleep bit in the mcucr register
      delay(500);
      Serial.println("About to sleep");
      delay(500);
      attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
      delay(500);
      Serial.println("Interupt attached");
      delay(500);
      sleep_mode(); // here the device is actually put to sleep...!!

      // THE PROGRAM CONTINUES FROM HERE AFTER INTERRUPT IS CLOSED
      delay(500);
      Serial.println("Continuing main program after interupt");
      delay(500);

      sleep_disable(); // first thing after waking from sleep: disable sl¯eep...
      delay(500);
      Serial.println("Sleep disabled");
      delay(500);
    }
    uint16_t readdata;
    void loop() {
      if (digitalRead(2) == 0) {
        {

          digitalWrite(13, 1);
          delay(100);
          digitalWrite(13, 0);
          delay(100);
        }
      }
      sleepNow(); // sleep function called here
      readdata = readByte(MPU6050_ADDRESS, 0x3A);
      Serial.print(readdata);
      Serial.print(",");
      readdata = readByte(MPU6050_ADDRESS, 0x37);
      Serial.println(readdata);

    }


body:
I currently have a `.ino` firmware file that I use in the Arduino IDE to program an ATmega328 micro-controller. I would like to get the file that the Arduino IDE uses to program the micro-controller.

Probably the IDE uses a hexadecimal (hex) file or something and sends it to the micro-controller through the serial.

How can I get this file being the only file that the IDE generates is the `.ino`?

title: How to get the firmware (hex) file from a .ino file containing the code

Answers: 3

body:
In the Preferences of the Arduino IDE; after `Show verbose output during:` check the box next to `compilation`.

Then when you compile you should get something like this at the bottom of the window:

    ...
    ...
    "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.elf" "/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.hex"
    Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

At the end of the third line from the bottom you get the `.hex` filename. In this case (on OSX) that would be `/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.hex`

body:
The easiest way to get the file is:

1. Sketch > Export Compiled Binary
1. Wait for the compilation process to finish
1. Sketch > Show Sketch Folder

You will find an extra file in the sketch folder, which in this case will have a `.hex` extension. This is the compiled file which would normally be uploaded to the Arduino board via **Sketch > Upload**.

Note that the "Export Compiled Binary" feature is only available from Arduino IDE 1.6.5 and newer.

body:
You are asking how to locate the compiled hex file. It's easy! Follow these steps:

1. In the Arduino IDE select `Sketch` > `Export Compiled Binary`. This performs a compile. Once complete, this command places a copy of the compiled `.hex` file into the directory of your sketch.
[![Export Compiled Binary][1]][1]
2. Then either browse to the sketch folder or in the IDE select `Sketch` > `Show Sketch Folder`.
[![Show Sketch Folder][2]][2]

This generates two hex files for the target micro-controller; one with the bootloader and one without the bootloader. These hex files can be uploaded to the micro-controller using a programmer such as the Atmel Ice or AVRISPmkII.

  [1]: https://i.stack.imgur.com/tO9jj.png
  [2]: https://i.stack.imgur.com/dTRLr.png


body:
it's been week that i am having issue,that i can’t get ultrasonic readings
when i connect with my esp8266 wifi module ,everytime it gives 0 cm reading.My

both hardwares work perfectly if i connect them individually.
i also divided a code of ultrasonic and esp8266 for the debugging steps,both are working. but when i combine both code together i get no response. In my database server i get 0 distance.

Note: using external power of 5v for ultrasonic sensor.
Is there any logical problem? please help Sir thanks.
Here is a code

    #include<ESP8266WiFi.h>
    #include<ESP8266HTTPClient.h>
    #define trigger 12
    # define echo 13
    float timex = 0;
    float distance = 0;
    float max_height = 0;
    float extra_space = 4.00;

    int TANK_SPECIAL_ID = 1;

    void setup() {
        pinMode(trigger, OUTPUT);
        pinMode(echo, INPUT);
        Serial.begin(115200);
        delay(5000);
        WiFi.begin("AndroidAP", "lovely12");

        Serial.println("Setup Initiated\ n");

        while (WiFi.status() != 3) {
            delay(500);
            Serial.println("Waiting for connection");
            Serial.print("WiFi Status: ");
            Serial.println(String(WiFi.status()));
        }
        Serial.println(String(WiFi.status()));
    }

    void loop() {
            HTTPClient http;
            int Percentage = 0;
            digitalWrite(trigger, LOW);
            delayMicroseconds(2);
            digitalWrite(trigger, HIGH);
            delayMicroseconds(10);
            digitalWrite(trigger, LOW);
            delayMicroseconds(2);
            timex = pulseIn(echo, HIGH);
            distance = timex * 340 / 20000;

            if (max_height == 0) {
                Serial.println("Setting max_height");
                max_height = distance;
                Serial.println("max_height configured..5 seconds delay");
                delay(5000);
                Percentage = -1;
                Serial.print("MAX HEIGHT: ");
                Serial.println(max_height);
            } else {
                int revVal = int(distance / max_height * 100);
                Percentage = revVal– 100;
                Serial.print("Current Ratings: ");
                Serial.print(distance);
                Serial.print(" cm");
                Serial.print(" | Percentage: ");
                Serial.print(Percentage);
                Serial.println(" %");

            }
            if (distance > -1) {
                String Data = "x=" + String(Percentage) + "&y=" + String(max_height) + "&z=" + String(TANK_SPECIAL_ID);
                http.begin("http://zaptraff.atwebpages.com/IOT/IOTCON.php");
                http.addHeader("application/x-www-form-urlencoded");

                int sent = http.POST(Data);
                Serial.print("Request val: ");
                Serial.println(sent);
                //String httpPayload = http.getString();
                //Serial.println(httpPayload);
                if (sent > 0) {
                    Serial.println("Data has been sent");
                } else {
                    Serial.println("unable to send data");
                }
            }
            delay(1000);
        }
    }

title: Ultrasonic sensor not getting reading while connecting to ESP8266

Answers: 1

body:
As the MIME type implies `application/x-www-form-urlencoded` is URL encoded. Non-alphanumeric characters must be percent encoded.

It looks like this line:

    if (distance > -1) {

Should be:

    if (Percentage > -1) {

Further:

    Percentage = revVal– 100;

Is sometimes negative. So `String(Percentage)` is producing `-` which is likely tripping up your web server because this is an illegal character when parsing `x-www-form-urlencoded`.


body:
How can I turn the LED on and off using a received text message?

The sim card is able to receive the message but I can't change the pin status. I also can't see anything in the serial monitor upon reception of the message.

Below is my code.

    #include <SoftwareSerial.h>
    SoftwareSerial gsm(2,3);
    String msg;
    const int LED = 13;

    void setup() {
      gsm.begin(9600);
      Serial.begin(9600);
      Serial.println("PUMP CONTROL");
      Serial.println("t : to receive text");
      delay(1000);

      pinMode(LED, OUTPUT);
      digitalWrite(LED, HIGH);
    }

    void loop() {
      if (Serial.available()>0)
      switch(Serial.read())
      {
        case 't':
        showSMS();
        break;
      }
      if (gsm.available()>0)
      Serial.write(gsm.read());

      if ( msg == "ON")
      {
        digitalWrite(LED, HIGH);
        delay(1000);
      }
      if (msg == "OFF")
      {
        digitalWrite(LED, LOW);
        delay(1000);
      }
    }

    void showSMS()
    {
     gsm.print("AT+CMGF=1\r");
     gsm.print("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     if (gsm.available()>0)
     {
      msg=gsm.read();
      Serial.print(msg);
     }
    }

title: Controlling an LED using SIM900A and Arduino

Answers: 1

body:
Try this code.

    #include <SoftwareSerial.h>
    SoftwareSerial gsm(2,3);
    String msg;
    const int LED = 13;

    void setup() {
      gsm.begin(9600);
      Serial.begin(9600);
      Serial.println("PUMP CONTROL");
      Serial.println("t : to receive text");
      delay(1000);

      pinMode(LED, OUTPUT);
      digitalWrite(LED, HIGH);
    }

    void loop() {
      if (Serial.available()>0)
      switch(Serial.read())
      {
        case 't':
        showSMS();
        break;
      }

      while(gsm.available() > 0)
      {
        Serial.write(gsm.read());
      }

      if ( msg == "ON")
      {
        digitalWrite(LED, HIGH);
        delay(1000);
      } else if (msg == "OFF")
      {
        digitalWrite(LED, LOW);
        delay(1000);
      }
      if(msg != "") msg = "";
    }

    void showSMS()
    {
     gsm.print("AT+CMGF=1\r");
     gsm.print("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     msg = "";
     while(gsm.available() > 0)
     {
      msg += gsm.read();
     }
     Serial.println(msg);
    }


body:
Is the a way to check the status of a bit in an arduino Uno?

Like how in Atmel AVR, there is bit_is_clear or bit_is_set

title: Arduino status of bit

Answers: 3

body:
you can do it in a single line:

    bool isSet = (var & (1 << bitNumber)) != 0;

`1 << bitNumber` is a bit shift in this case it means that the 1 will be multiplied with the power of 2

`&` is the bitwise AND operator. The each bit of the result is 1 if and only if both the corresponding bits in the inputs is 1.

body:
Let's say there is a register called *r1*, and you want to do something if its *6th* bit is set to *1*.

Here are two equivalent if statements, both doing the same thing:

    if(r1&64){Do something;}
    if(r1&(1<<6)){Do something;}

----------

Tiny extra code information:

Let's say you want to do something if r1 = 01XX10XX00 where X means you don't care.

Here are three if statements, all doing the same thing:

    if((r1&0b11001100)==(0b01001000)){Do something;}
    if((r1&0b11001100)==((1<<6) | (1<<3))){Do something;}
    if((r1|0b00110011)==(0b01111011)){Do something;}

If you & (logic and) a 0 somewhere, then you are setting that bit to 0<br>
If you | (logic or) a 1 somewhere, then you are setting that bit to 1

----------

Best of luck on your future ventures.

body:
Arduino defines the function `bit()`, which makes it easy to do an `if`:

    if (val & bit(5)) { // Is bit 5 set?
        // Do something
    } // if

Note that you need to use the bit-and (`&`) operator, not the Boolean-and (`&&`) operator.

If you want to check if the bit is clear, you can use the not (`!`) operator - but then you need parentheses:

    if (!(val & bit(5))) { // Is bit 5 not-set (clear)?
        // Do something
    } // if


body:
I need to be able to connect a USB keyboard, like a tiny Xbox keyboard, or a nice wireless one, into an ESP8266-based thing to type passwords into the MCU. Adapting the PS2 lib for AVRs (PS2==USB pinouts for KBs) proved unreliable, so I tried a fake Pro Mini.

It worked much better, perfect with PS2, but only with a subset of my USB keyboards, namely a 104 Das Keyboard and an old-school Dell one. My 2002-era Mac keyboard doesn't work, none of my 5 wireless keyboards work, and neither do Xbox or foldable keyboards. Nothing that presents as a composite device works (like a keyboard with USB slots), only dead-simple (no fancy keys/knobs) keyboards seem to work.

1. Would a [USB host module](https://www.ebay.com/itm/201488640991) (like the Uno shield, but not a shield) let me read from more than just basic PS2-emulating USB keyboards?

2. Is the code to read basic alphanumeric keys consistent among different keyboards, or will each model need special instructions? (much like a driver would provide an actual OS)

3. If it's anything but "plug and play", what would be a simple way (no soldering) to securely input passwords into an MCU?

EDIT:

Early USB keyboards and PS2 keyboards have the same pinout and behavior, so you can use a Pro Mini and the [Arduino ps2keyboard](https://playground.arduino.cc/Main/PS2Keyboard) demo to read such USB keyboards, either with a passive USB keyboard to PS2 male adapter for less than $1 USD, or via a female USB wired the same. Fancier keyboards don't work as such, at all, hence the possible need for a USB host module.

title: Typing into ESP8266 with a USB keyboard

Answers: 2

body:
> My 2002-era Mac keyboard doesn't work,

That doesn't surprise me - modern Macs have never needed PS/2 support.

> none of my 5 wireless keyboards work,

That's because they're not keyboards, they're wireless transceivers that provide USB HID interfaces.

> and neither do Xbox or foldable keyboards.

Too modern, and of course XBox has never needed PS/2 support.

> Nothing that presents as a composite device works (like a keyboard with USB slots), only dead-simple (no fancy keys/knobs) keyboards seem to work.

Of course, they aren't PS/2 keyboards, they're USB devices.

Older keyboards provided dual operation - USB and PS/2. This is a function provided by the keyboard, not the USB standard. Mac keyboards, since the Apple computers never had PS/2 ports (since PS/2 is an IBM standard from the PS/2 computers back in the 80s & 90s). Modern keyboards that provide more than just a simple keyboard functionality cannot really provide PS/2 as well since that can't provide the other features of the keyboard. The same goes for composite devices, or wireless devices - they facilities they provide are in excess of what PS/2 can provide, so it would be illogical trying to provide PS/2 support - especially as PS/2 ports are getting rarer on computers now.

> Would a USB host module (like the Uno shield, but not a shield) let me read from more than just basic PS2-emulating USB keyboards?

Sure, if you can get the libraries working on the ESP8266, which may well be a huge challenge in- and of itself.

> Is the code to read basic alphanumeric keys consistent among different keyboards, or will each model need special instructions? (much like a driver would provide an actual OS)

All USB keyboards are class-compliant HID devices. They send HID reports in a standard format, maybe with custom additions. The basics are always the same though.

> If it's anything but "plug and play", what would be a simple way (no soldering) to securely input passwords into an MCU?

It'd be far from "plug and play" getting a USB host interface working with the ESP8266.  Consider other more simple routes, such as using serial, or configuring the ESP8266 as an access point and using a web browser to configure it.

body:
The USB Host Shield Library 2.0 has supported the ESP8266 for about a year. Support for the ESP32 was added more recently.

The following is a link to the project README listing the supported boards and microcontrollers.

https://github.com/felis/USB_Host_Shield_2.0#boards


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

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

    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.

title: How to recover an I2C bus when SDA is stuck low? Edit: SDA line stuck high

Answers: 1

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


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

<!-- language: lang-none -->

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

title: Arduino library creation - Calling library and Merging

Answers: 1

body:
If you consult the [Arduino Library Specification's section on keywords.txt](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords):

>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](https://github.com/arduino/Arduino/pull/6693) 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.


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

It also uses:

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

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

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

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

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

Here is my current full code:

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

    #include <Servo.h>

    Servo Servokey;

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

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

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

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

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

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

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

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

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

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

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

      Serial.begin(9600);
    }

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

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

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

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

Here's the other code:

    #include <Servo.h>

    Servo Servokey;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Serial.begin(9600);
    }

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

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

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

title: What is wrong with my state machines?

Answers: 1

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

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

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

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

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

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

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

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

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

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

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

     Serial.begin(9600);
    }

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

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

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

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

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

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

    #include "Servo.h"

    Servo Servokey;

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

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

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

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

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

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

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

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

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

    unsigned long interval = 10000;

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

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

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

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

     Serial.begin(9600);
    }

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

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

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

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

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

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

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


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

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

Answers: 1

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

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

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


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

Are there platform-independent functions for the following?

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

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

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

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

title: Platform-independent functions for FastPWM?

Answers: 1

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

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

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


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

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

Answers: 1

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

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

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

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

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

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

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

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


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

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

Answers: 1

body:
    int ledPin = 13;

    int ldrPin = A0;

    int PIR_Pin = 2;

    void setup()

    {

        Serial.begin(115200);

        pinMode(ledPin, OUTPUT);

        pinMode(PIR_Pin, INPUT);

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

    void loop()
    {

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

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

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

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

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

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

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


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

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

Troubleshooting steps taken:

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

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

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

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

    #include "SoftwareSerial.h"

    SoftwareSerial myESP(RX,TX);

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

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

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

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

Answers: 3

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

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

body:
How about this:

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

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

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

Or arrays:

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

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


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

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

The circuit:

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

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

    LCD - Mega2560

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

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

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

Liam

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

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

Answers: 2

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

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

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

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

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

Other considerations:

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

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

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

Other approaches:

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

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

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

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

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

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

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

     /*
      For Loop Iteration

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

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

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

    This example code is in the public domain.

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

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

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

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

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

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

To use it you build the following circuit:

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

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

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

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

Liam


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

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

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

Answers: 1

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

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

**To answer your question:**

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

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

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

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

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

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

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

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

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


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

title: Can't see second Arduino port on Ubuntu

Answers: 1

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

    sudo usermod -a -G dialout $USER

Then log out and back in again.

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