message:
MPU6050 accelerometer giving output as -1 -1. Can anyone tell the issue in the code?

// MPU-6050 Short Example Sketch
    // By Arduino User JohnChi
    // August 17, 2014
    // Public Domain
    #include<Wire.h>
    const int MPU_addr=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

    void setup() {
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0); // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
      Serial.begin(9600);
    }

    void loop() {
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
      Serial.print("AcX = "); Serial.print(AcX);
      Serial.print(" | AcY = "); Serial.print(AcY);
      Serial.print(" | AcZ = "); Serial.print(AcZ);
      Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
      Serial.print(" | GyX = "); Serial.print(GyX);
      Serial.print(" | GyY = "); Serial.print(GyY);
      Serial.print(" | GyZ = "); Serial.println(GyZ);
      delay(333);
    }

Serial Monitor output:

    AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
    AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
    […]

body:
I found that there was a communication problem between MPU and Arduino which I found using code given in this link http://playground.arduino.cc/Main/I2cScanner .
Then I found thought problem Must be in MPU or arduino and problem was in Arduino MCU.
So after changing the Arduino MCU it worked


sender: user

message:
Function, struct or class?

I am trying to learn more about arduino programming, and recently i've written functions for randomizing and then modifying a single array. Now i'd like to do the same for four individual arrays. This is where i'm getting stuck. My questions:

Am i right to assume that it's not possible calling a function for multiple individual arrays?

Perhaps a separate question, but if a class or struct would be more suitable for multiple instances, what are the major differences worth considering to choose the right approach?

sender: assistant

body:
> Am i right to assume that it's not possible calling a function for multiple individual arrays?

What would give you that impression?  An array is just a pointer to a block of memory - as such it's just a variable. You can pass as many as you like to a function.

Just remember that a function can't know how big the array is that you pass it, since it only gets the pointer to the start of the array, so you need to pass the size of the array with it. You can't rely on the `sizeof` operator, since that is a compile-time directive that gives the size of a variable, which inside the function will be the size of a pointer (2 bytes on an 8 bit system). It can only give the size of an array (and then only the memory size in bytes, not the count of elements) if its run in the same (or a subordinate) scope as the declaration of the array.

> Perhaps a separate question, but if a class or struct would be more suitable for multiple instances, what are the major differences worth considering to choose the right approach?

A struct is just a way of grouping variables into compound types. Think of them as database records. Great for if you want to keep related, but different, information together in one block.  Classes are the same thing but add functions as well.*

----

* That's a very simplistic description. In actuality you can have functions in structs and not have functions in classes. The real difference between them is how access controls (private/protected/public) are implemented (there is none in structs, and they are all there in classes) and how inheritance / polymorphism works.


body:
Are you trying to use the same function for different arrays at different times, or are you trying to use a function that handles four different arrays at the same time?

If the former, you'd write something like

    void myfunc( T *arr, size_t size ) // where T is the type of the array
    {
      for ( size_t i = 0; i < size; i++ )
        arr[i] = some_new_value();
    }

then call it for each array:

    T arr1[N];  // where T is int, float, double, whatever
    T arr2[M];
    T arr3[O];
    T arr4[P];

    myFunc( arr1, N );
    myFunc( arr2, M );
    myFunc( arr3, O );
    myFunc( arr4, P );

This assumes all the arrays have the same base type (e.g., they're all arrays of `int`).

If you want a function to work on four arrays simultaneously, you'd write it as

    void myFunc( T *a1, size_t a1_size,
                 T *a2, size_t a2_size,
                 T *a3, size_t a3_size,
                 T *a4, size_t a4_size )
    {
      // code for handling each array
    }

While I wrote it such that all the arrays have the same type, it doesn't have to be this way.  Each array can be a different type (`a1` can be `int`, `a2` can be `double`, etc.).


message:
ESP8266 send number in IP address

I want to easily send a number from a phone to my esp8266.
I have an app that sends the number in the format IP/number.
How can I modify the code to give my the number behind the IP address as an integer?

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>

    MDNSResponder mdns;

    // Replace with your network credentials
    const char* ssid = "YOUR_SSID";
    const char* password = "YOUR_PASSWORD";

    ESP8266WebServer server(80);

    String webPage = "";

    void setup(void){

      delay(1000);
      Serial.begin(115200);
      WiFi.begin(ssid, password);
      Serial.println("");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());

      if (mdns.begin("esp8266", WiFi.localIP())) {
        Serial.println("MDNS responder started");
      }

      server.on("/", [](){
        Serial.println("device connected");
      });
      server.begin();
      Serial.println("HTTP server started");
    }

    void loop(void){
      server.handleClient();
    }

So it would do something like this for and should be looking through every i between 0 and 200. :

    server.on("/"+String(i), [](){
        Serial.println("i");
      });

body:
First you need to extract the string that contains the number (after the /). Since it is already stored in consecutive memory you can pass the pointer to the character after the / symbol to the C function `atoi` to convert it to an integer.

I assume the pointer is already `\0` terminated.

You can use the C function `strchr` to search for the / symbol.

Tip: use a C compiler on a desktop/PC to check how these functions work. Once you know how to use them, copy them in your Arduino code. This is much faster than uploading/debugging sketches probably.


body:
First of all use the event function server.on with a path that corresponds to your function and use a url like this:

    192.0.2.2/recordnumber?num=100

With a url parmeter for your number. Your code might look like this:

At the top:

    int nums_size = 0;
    const int nums_max = 128;
    int nums[nums_max];

In setup:

    server.on("/recordnumber", [](){
        int num;
        if(server.hasArg("num")) {
          String num_str = server.arg("num");
          if(num_str.charAt(0) == '0') {
            num = 0;
          } else {
            num = num_str.toInt();
            if(num == 0) {
              server.send(400, "text/plain", "not a number");
              return;
            }
          }
          if(nums_size < nums_max) {
            nums[nums_size++] = num;
            server.send(200, "text/plain", "saved");
          } else {
            server.send(500, "text/plain", "full");
          }
        } else {
          server.send(400, "text/plain", "bad params");
        }
    });


message:
"Stand-alone" serial monitor

I usually use [Platformio][1] as IDE for my Arduino projects. I like it as an editor, but I don't like its serial monitor feature. So I often open the Arduino IDE in background to use its serial monitor, but this has some drawbacks (including a significant increase in my computer's CPU usage and battery consumption).

Is there an Arduino-compatible serial monitor application that just works as a serial monitor (and not also as an IDE)? I'm most interested in a MacOS application, but if you know a Windows one please tell me as well.

  [1]: http://platformio.org

body:
I use [CoolTerm][1], which is available for Mac, Windows and Linux. It is a great serial app, and you can have several windows open at the same, for each serial pipe you may be using (Bluetooth, Arduino Serial, etc).

  [1]: http://freeware.the-meiers.org/


body:
There's a list of serial port sniffers here, if you want to view raw data

[ softwarerecs.stackexchange serial-port-logging][1]

And a list here of programs which plot graphs from serial data:

[softwarerecs.stackexchange serial-data-plotting-programs ][2]

  [1]: https://softwarerecs.stackexchange.com/questions/7636/serial-port-logging/7639#7639

  [2]: https://arduino.stackexchange.com/questions/1180/serial-data-plotting-programs


body:
Consider building your own monitor in Python. This gives you flexibility since Python is cross platform and you can tailor the monitor to your needs.

 1. Install [Python][1].
 2. Install [pySerial][2] (`pip install pyserial`).
 3. Write a Python script to read and/or write to the Arduino across the serial port. There are some great examples out there such as [this example][3] and other [Stack Overflow answers.][4]

  [1]: https://www.python.org
  [2]: https://pythonhosted.org/pyserial/
  [3]: https://www.thepoorengineer.com/en/arduino-python-plot/
  [4]: https://stackoverflow.com/questions/24074914/python-to-arduino-serial-read-write


body:
On macOS, you can use the built-in `screen` command, e.g.:

    screen /dev/cu.usbmodem14201 9600

To exit, control-A followed by control-\\


message:
Unable to read data with 16 serial clock cycles

I am trying to read data from an [AD7314 Temperature Sensor][1] that is connected to an Arduino Uno and output that value onto 6 LEDs also connected to the Arduino Uno board. From the image below, the sensor is showing only an output of `0011111111111111` during the streams of 16 clock cycles even after the chip enable goes from low to high before conversion to initiate a new one (it seems that the conversion is stuck). The datasheet says:

>A leading zero and 10 bits of data are transferred during a read operation. Read operations occur during streams of 16 clock pulses. Output data is updated on the rising edge of SCLK. The serial data is accessed in a number of bytes if 10 bits of data are being read. At the end of the read operation, the SDO line remains in the state of the last bit of data clocked out of the AD7314 until CE returns low

I am not sure where exactly I am going wrong during the read operation:

Note: for the Waveform image (Top to bottom):

- waveform 1: Chip Enable

- waveform 2: Serial Clock

- waveform 3: MISO Line

- waveform 4: MOSI Line

My code is below:

    #include <SPI.h>

    const int MOSI_PIN = 11;
    const int MISO_PIN = 12;
    const int SCK_PIN = 13;
    const int Slave_PIN = A0;

    // module data
    uint16_t myValFromTempSensor = 0;

    void setup () {
      SPI.begin ();
      SPI.beginTransaction(SPISettings(125000, MSBFIRST, SPI_MODE0));
      pinMode(5, OUTPUT); //LED 3
      pinMode(6, OUTPUT); //LED 4
      pinMode(7, OUTPUT); //LED 5
      pinMode(8, OUTPUT); //LED 6
      pinMode(9, OUTPUT); //LED 7
      pinMode(10, OUTPUT);//LED 8
      pinMode(MOSI_PIN, OUTPUT); // MOSI to SDI
      pinMode(MISO_PIN, INPUT); //MISO to SDO
      pinMode(SCK_PIN, OUTPUT); //CLOCK PIN to SCK
      pinMode(Slave_PIN,OUTPUT); //Slave pin

      digitalWrite(Slave_PIN, LOW);//Set slave low before communication
      for (int i = 5; i < 11; i++) {
        digitalWrite(i, LOW);
      }
      delay(100);
    } // end of setup

    void loop () {
      digitalWrite(Slave_PIN, HIGH);  //Set slave high to read data
      myValFromTempSensor = SPI.transfer(0x00); // Read Data from the device
      myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;// Bitshift to read next 8 bits
      digitalWrite(Slave_PIN, LOW);
      if(( myValFromTempSensor>=0) && ( myValFromTempSensor<=196)) {
        //Range 0C to 60C is  0 to 196
        digitalWrite(5, bitRead(myValFromTempSensor,0));
        digitalWrite(6, bitRead(myValFromTempSensor,1));
        digitalWrite(7, bitRead(myValFromTempSensor,2));
        digitalWrite(8, bitRead( myValFromTempSensor,3));
        digitalWrite(9, bitRead( myValFromTempSensor,4));
        digitalWrite(10, bitRead( myValFromTempSensor,5));
      } else {
        digitalWrite(5, 0);
        digitalWrite(6, 0);
        digitalWrite(7, 0);
        digitalWrite(8, 0);
        digitalWrite(9, 0);
        digitalWrite(10, 0);
      }
    }

[![SPI Waveform][2]][2]

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/AD7314.pdf
  [2]: https://i.stack.imgur.com/x4WHf.png

body:
This is not an answer to your question but I cannot add it as a remark since it involves code.

You can greatly reduce your code by using for loops, e.g.:

       pinMode(5, OUTPUT); //LED 3
       pinMode(6, OUTPUT); //LED 4
       pinMode(7, OUTPUT); //LED 5
       pinMode(8, OUTPUT); //LED 6
       pinMode(9, OUTPUT); //LED 7
       pinMode(10, OUTPUT);//LED 8

to

       int n;
       for (n = 5; n < 11; n++)
       {
          pinMode(n, OUTPUT);
       }

And

    digitalWrite(5,bitRead( myValFromTempSensor,0));
    digitalWrite(6,bitRead( myValFromTempSensor,1));
    digitalWrite(7,bitRead( myValFromTempSensor,2));
    digitalWrite(8,bitRead( myValFromTempSensor,3));
    digitalWrite(9,bitRead( myValFromTempSensor,4));
    digitalWrite(10,bitRead( myValFromTempSensor,5));

to

    int n = 0;
    for (n = 0; n < 6; n++)
    {
        digitalWrite(n + 5,bitRead( myValFromTempSensor, n));
    }

And

      digitalWrite(5,0);
      digitalWrite(6,0);
      digitalWrite(7,0);
      digitalWrite(8,0);
      digitalWrite(9,0);
      digitalWrite(10,0);

to

    int n;
    for (n = 5; n < 11; n++)
    {
        digitalWrite(n, 0);
    }

Instead of hardcoded values 5 and 11 you can use defines, e.g.

    #define LED_MIN 5
    #define LED_MAX 11

and change

    for (n = 5; n < 11; n++)

to

    for (n = LED_MIN; n < LED_MAX; n++)


body:
I see several issues here.

## Sensor output

According to the waveforms shown by your logical analyzer, the sensor is
outputting 0b0011111111111111. We have to discard the first (a padding
zero) and the last five bits (copies of DB0). We then end up with the
actual data bits being 0111111111. This has to be interpreted as a
signed fixed-point number in s.7.2 format, which gives 127.75 °C:
the maximum possible value the sensor can output, and well above its
maximum operating temperature.

I cannot tell what is going wrong here. It looks like the sensor is
either burning alive, or trying to tell you it's extremely unhappy.

## SPI mode

You wrote:

> `SPISettings(125000, MSBFIRST, SPI_MODE0)`

SPI mode 0 seems to be pretty common. In this mode, the data lines are
updated on the falling edge of the clock, and they are read on the
rising edge. However, according to your sensor's datasheet, it appears
this sensor works the other way around: it uses [SPI mode 1][]. Your
setting should reflect this.

## Decoding the data

You wrote:

> `myValFromTempSensor = SPI.transfer(0x00);`
> `myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;`

Here you are assuming the least significant byte is transmitted first.
This is not the case: you get a stream of 16 bits with the most
significant first. Thus, in terms of bytes, it's also MSB first.

Then, 6 of these 16 bits have to be discarded in order to get the actual
10 data bits. Since the Arduino has no 10-bit data type, and the
number is signed, it has to be sign-extended to 16-bits. All this can be
done in C/C++ by:

* left-shifting one bit to the left (discarding the zero padding bit)
* casting to a _signed_ 16-bit integer
* right-shifting (which [gcc implements using sign
  extension][signed shift]) six bits to the right

Or, in code:

    digitalWrite(Slave_PIN, HIGH);
    uint16_t raw_data = SPI.transfer16(0);
    digitalWrite(Slave_PIN, LOW);
    int temperature_reading = (int16_t)(raw_data << 1) >> 6;

[SPI mode 1]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase
[signed shift]: https://gcc.gnu.org/onlinedocs/gcc-5.5.0/gcc/Integers-implementation.html#Integers-implementation

------------------------------------------------------------------------

**Edit**: Here are more details about the data representation, and about
the conversion to 16-bits done by the expression
`(int16_t)(raw_data << 1) >> 6`.

According to the datasheet, the sensor gives the temperature as a 10-bit
_signed_ number in two's complement notation. If you fail to acknowledge
the fact that the result is signed, and you interpret the 10 bits
as an unsigned number, then a temperature of −1 °C will be
interpreted as +255 °C, which is obviously _very_ wrong.

Since it's a signed number, increasing the bit width of the temperature
to 16 bits has to be done using [sign extension][], i.e. the
missing bit positions have to be filled with copies of the leftmost bit
(the “sign bit”).

The datasheet also shows that the sensor sends a stream of 16-bits as
follows:

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

    0 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0

where the first bit is a padding zero, then come the ten data bits
db9 – db0, and then five extra copies of the last data bit.
These extra copies can  be seen in figure 3 (serial interface
digram), and can also be inferred from the sentence “the SDO line
remains in the state of the last bit of data clocked out of the AD7314”.

The line

    uint16_t raw_data = SPI.transfer16(0);

puts this bit pattern into the variable `raw_data`, which is a 16-bit
unsigned integer. Then, the operation `raw_data << 1` shifts this
pattern one bit position to the left, discarding the leftmost zero and
padding with another zero on the right, which gives:

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

    db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0 0

This is then cast to a signed number, which doesn't change the bit
pattern, but only the interpretation of the leftmost bit, which is now a
sign bit. Then, the number is shifted by 6 bit positions to the
right. Since this is an [arithmetic shift][], which does sign extension,
the leftmost bit (the “sign bit”) is replicated during the shift, which
yields:

    db9 db9 db9 db9 db9 db9 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0

And this is the expected result: the _same numeric value_ that was
originally stored in the “temperature value register” of the sensor,
only represented as a 16-bit number.

[sign extension]: https://en.wikipedia.org/wiki/Sign_extension
[arithmetic shift]: https://en.wikipedia.org/wiki/Arithmetic_shift


body:
If anyone stumbled on this thread later like I did, it may be helpful to understand that the binary response is a decimal number, specifically with 0.25c resolution. Meaning that the integer value that Edgar Bonet's (excellent) response will give you needs to be multiplied by 0.25 to get the actual temperature in Celsius.

I suggest multiplying by 0.25 because it will give the same result as dividing by 4 but without the risk of a divide by zero error. Also division is extremely slow on Arduino since the underlying instruction set does not have a divide instruction.

I  hope this helpful to someone at some point; if not sorry for the annoyance.


message:
Unable to upload the data on thingspeak using uno and esp8266

I am able to connect to thingspeak but now able to upload the data. here are my set of commands:

    AT+CIPMUX=0
    OK

    AT+CIPSTART="TCP","184.106.153.149", 80
    OK
    Linked

    AT+CIPSTATUS
    STATUS:3
    +CIPSTATUS:0,"TCP","184.106.153.149",80,0
    OK

    AT+CIPSEND=45
    > GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60

    busy s...

    SEND OK

    OK

and after some time unlink

I am giving these commands using arudino serial monitor.
Please help, I have searched a many blogs, youtube videos.

body:
You have a malformed HTTP request. You only have half of the first line.

A valid HTTP request would look more like this:

    GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60 HTTP/1.1
    Host: api.thingspeak.com
    Content-length: 0
    Connection: close
    <blank line>

Just sending "GET <path>: ain't gonna work. For a start, the server won't know what protocol you're speaking (HTTP/1.1), nor what website it's supposed to direct the request to (Host: api.thingspeak.com). Also, the final extra blank line is *required* to finish the request.


body:
   I got it working. Yo!

    #include <SoftwareSerial.h>
    #include <stdlib.h>

    // LED
    int ledPin = 13;
    // LM35 analog input
    int lm35Pin = 0;
    float my_value = 22;
    // replace with your channel's thingspeak API key
    String apiKey = "9PJEF1EP8ZMVY5JA";

    // connect 10 to TX of Serial USB
    // connect 11 to RX of serial USB
    SoftwareSerial ser(10, 11); // RX, TX

    // this runs once
    void setup() {
      // initialize the digital pin as an output.
      pinMode(ledPin, OUTPUT);

      // enable debug serial
      Serial.begin(9600);
      // enable software serial
      ser.begin(9600);

      // reset ESP8266
      ser.println("AT+RST");
    }

    // the loop
    void loop() {

      // blink LED on board
      digitalWrite(ledPin, HIGH);
      delay(200);
      digitalWrite(ledPin, LOW);

      // read the value from LM35.
      // read 10 values for averaging.

      // convert to temp:
      // temp value is in 0-1023 range
      // LM35 outputs 10mV/degree C. ie, 1 Volt => 100 degrees C
      // So Temp = (avg_val/1023)*5 Volts * 100 degrees/Volt
      my_value++;
      float temp = my_value;

      // convert to string
      char buf[16];
      String strTemp = dtostrf(temp, 4, 1, buf);

      Serial.println(strTemp);

      // TCP connection
      String cmd = "AT+CIPSTART=\"TCP\",\"";
      cmd += "184.106.153.149"; // api.thingspeak.com
      cmd += "\",80";
      ser.println(cmd);

      if(ser.find("Error")){
        Serial.println("AT+CIPSTART error");
        return;
      }

      // prepare GET string
      String getStr = "GET /update?api_key=";
      getStr += apiKey;
      getStr +="&field1=";
      getStr += String(strTemp);
      getStr +="&field2=";
      getStr += String(strTemp);
      getStr += "\r\n\r\n";

      // send data length
      cmd = "AT+CIPSEND=";
      cmd += String(getStr.length());
      ser.println(cmd);
      Serial.println(cmd);

      if(ser.find(">")){
        ser.print(getStr);
        Serial.println(getStr);
      }
      else{
        ser.println("AT+CIPCLOSE");
        // alert user
        Serial.println("AT+CIPCLOSE");
      }

      // thingspeak needs 15 sec delay between updates
      ser.println("AT+RST");
      delay(30000);
    }


message:
Arduino Uno "if" statement is ignored in code and halts execution when using Serial.ReadString()

I'm having a weird issue with my Uno trying to power on a PWM fan using a MOSFET.

I'm setting a simple power on/off code using commands sent over the Serial Monitor, and although this code worked before, after I tried to add some code to control the speed of the PWM fan, my if statements do not work anymore, even with the simple power on/off code:

        String command;           //Define the string variable "command"

    void setup() {
      // put your setup code here, to run once:

      pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
      pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
      digitalWrite(5, LOW);   //Start with MOSFET off
      digitalWrite(13, LOW);  //Star with status LED off
      Serial.begin(9600);     //Start Serial comm for sending commands

    }

    void loop() {
      // put your main code here, to run repeatedly:

      Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

      while (Serial.available()==0) {        //Wait for user input stopping the code
        digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
        delay(100);
        digitalWrite(13, LOW);
        delay(100);
      }

      command=Serial.readString();          //Save the Serial Monitor String command to the "command" variable as a String
      Serial.println("data read");          //Confirm Serial Monitor input
      Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

      if (command=="On") {                  //Turn the MOSFET on
        digitalWrite(5, HIGH);
      } else if (command=="Off") {                  //Turn the MOSFET off
        digitalWrite(5, LOW);
      }
      else {                                 //Provide feedback for a wrong command
        Serial.println("Wrong command!");
      }
    }

This is my Serial Monitor output after sending "On":

    What's your command?
    data read
    On

    Wrong command!
    What's your command?

To check if the pin works, I tested a simple code that worked fine:

    void setup() {
      // put your setup code here, to run once:

      pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
      digitalWrite(5, LOW);   //Start with MOSFET off
      Serial.begin(9600);     //Start Serial comm for sending commands

    }

    void loop() {
      // put your main code here, to run repeatedly:

        digitalWrite(5, HIGH);
     delay(2000);
        digitalWrite(5, LOW);
     delay(2000);

    }

Does anyone have any idea why the if statements are not working anymore?

Thank you in advance!

AC

EDIT: After trying to use the "else" statement as recommended by per1234, the issue continues to happen, but changing the variable type to an integer works, although the Serial output is rather messy:

    int command;           //Define the int variable "command"

    void setup() {
      // put your setup code here, to run once:

      pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
      pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
      digitalWrite(5, LOW);   //Start with MOSFET off
      digitalWrite(13, LOW);  //Star with status LED off
      Serial.begin(9600);     //Start Serial comm for sending commands

    }

    void loop() {
      // put your main code here, to run repeatedly:

      Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

      while (Serial.available()==0) {        //Wait for user input stopping the code
        digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
        delay(100);
        digitalWrite(13, LOW);
        delay(100);
      }

      command=Serial.parseInt();          //Save the Serial Monitor imput command to the "command" variable as an int

      Serial.println("data read");          //Confirm Serial Monitor input
      Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

      if (command==1) {                  //Turn the MOSFET on
        digitalWrite(5, HIGH);
      }
      if (command==2) {                  //Turn the MOSFET off
        digitalWrite(5, LOW);
      }
      else {                                 //Provide feedback for a wrong command
        Serial.println("Wrong command!");
      }
    }

And the Serial Monitor output:

    What's your command?
    data read
    1
    What's your command?
    data read
    0
    Wrong command!
    What's your command?
    data read
    2
    What's your command?
    data read
    0
    Wrong command!
    What's your command?

Does anyone experience this issue? I even tried rolling back my IDE to 1.8.3, which I used to write the code the first time, then after a library update, and also getting version 1.8.5, it stopped working.

Also, anyone knows how to avoid the multiple Serial Monitor outputs?

I tested this with "String" variables to be able to get this fixed.

Also, a side question regarding the post size, should I remove the original code when editing, or should I move it to another answer?

Thank you.

body:
Let's look at what this code does when you send "On":

      if (command=="On") {                  //Turn the MOSFET on
        digitalWrite(5, HIGH);
      }

This will evaluate true so pin 5 is set to HIGH.

      if (command=="Off") {                  //Turn the MOSFET off
        digitalWrite(5, LOW);
      }

This will evaluate false so the else clause is executed:

      else {                                 //Provide feedback for a wrong command
        Serial.println("Wrong command!");
      }

So the output you are seeing is correct for your code. The problem is that your code doesn't match your intent. For that you need to change this line:

      if (command=="Off") {                  //Turn the MOSFET off

to:

      else if (command=="Off") {                  //Turn the MOSFET off

Then the else clause will only run if the command doesn't match "On" or "Off".

For more information see:
https://www.arduino.cc/reference/en/language/structure/control-structure/else/


body:
The problem with the *original* code is evidenced in the following:

    What's your command?
    data read
    On

    Wrong command!

See that blank line?  Nowhere in your sketch do you specifically print a blank line, rather it is being printed because the `command` string contains a carriage return and/or newline character captured with the input, which is causing a comparison of exact equality to fail.

To fix this, you could either trim these non-printing characters off the end, or use a different comparison, for example `command.startsWith("On")`.  But if you do use a start-of-string comparison, beware if you have any command verbs that extend other shorter ones.

You also have a bug in your block if-else statements, in that instead of

    if ...
    if ...
    else ...

you should have

    if ...
    else if ...
    else ....

So that the "none of the above" clause only runs when none of the conditions are satisfied, rather than running whenever the penultimate condition is not satisfied.

In terms of the numeric version producing an un-entered value of 0, this is the documented return value of the `parseInt()` methods if they time out without finding a valid integer.

It would be more traditional to use an end-of-line condition rather than a timeout to detect the end of user input.  Many traditional "until end of line" read mechanisms trim the line ending characters off the resulting string for you, eliminate the comparison problem, too.


body:
Thank you for your help.

I have been able to find the root cause of my original problem.

After reading this post on https://forum.arduino.cc/index.php?topic=73372.0, more specifically an answer regarding filtering for \n and \r characters and the Arduino IDE Serial Monitor line ending option.

My problem was caused by having the "Newline" option selected in the Serial Monitor. After selecting "No line ending", my original code runs as expected, and I know now how to use String variable and Serial.readString() in a more efficient way, and the if-else statements.

Also, the blank line mentioned by Chris Stratton is gone, and my search to fix that led me to the solution of the main problem, and the code also works 100% with the formatting help provided by per1234.

Thank you both again for the help.


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

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!

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


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

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

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


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

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

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

    }


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

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`?

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


message:
Ultrasonic sensor not getting reading while connecting to ESP8266

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

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


message:
Controlling an LED using SIM900A and Arduino

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

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


message:
Arduino status of bit

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

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


message:
Typing into ESP8266 with a USB keyboard

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.

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


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

See edit at the end of the message.

I have an Arduino in master mode connected via I2c to a slave, with 2k pull-up resistors on SDA and SCL. Sometimes the SDA line is stuck low, which causes my program to hang indefinitely.

How to recover from such a scenario?

Edit1: Since the SDA line is tied low the problem probably comes from the master. My guess is that the slave waits for the rest of the clock pulses that never come.

I'm not using the Wire library. I wrote my own implementation based on the AMmega328P datasheet.

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

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.


message:
Arduino library creation - Calling library and Merging

I am new to creating a library in Arduino. I was able to create a library from YouTube. I want to merge two other libraries into the library I created. Can you please help me to do so?

I already created a keywords.txt file for my library but the keywords are not getting highlighted in orange in the IDE. But it identifies as keywords.

Please guide me how to properly create a keywords file and merge the libraries.

Keywords below:

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

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.