body:
c will perform implied casts for standard data types, normally without issuing any warnings.

This can catch you out at times.

So if you try to store a float into an int then it will be rounded down to the next integer. Since floats sometimes have rounding errors this can result in the value being 1 less than expected. e.g. 5 / 2.5 should give 2.0 but due to rounding may result in 1.99999999999. When saved as an int that would then give a value of 1.

If you want to round to the nearest integer then first add 0.5.

While the casts are implied and so not technically needed it can sometimes be a good idea to still include them explicitly just to make it clearer in the code that values are going to get rounded down.

The other thing to keep in mind is how variable types are promoted by the implied casts.

e.g. consider the following two lines:

float x = 3 + 2/4.0;

float x = 3.0 + 2/4;

In the first the calculation it is: int + int / double = int + double = double

In the second it is: double + int / int = double + int = double

So both result in a double that is then converted to a float (arduino is a little non-standard here, doubles are just floats anyway).

However the resulting values will be different. The first one will give
the expected 3.5 while the second one will give 3.0 because 2/4 is an integer calculation and will have a value of 0. In order to get the correct value either the 2 or the 4 must be cast to a float or double before the division operation takes place.

For your specific questions:

`Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);` is perfectly valid, all calculations will be performed as doubles and the end result cast to an int however you may get rounding issues as mentioned above. Changing the line to `Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n) + 0.5);` will round to the nearest integer which is probably what you want.

For the second question, `floatVal = intVal - intVal*Buffer[intVal];` there is no need for a cast, the value will be calculated as an int and then there is an implied cast to a float. However I'm not sure what the point of using a float is here since the result is always going to be an integer, using a float will only slow things down.


sender: user

message:
Make arduino board controler for watering system with power bank

I am trying to build an off-grid automatic watering system, and I was thinking of many options and the most reliable one that I found is to use a power bank which is charged by a solar panel.

So, I have a solar panel that outputs 5V, and I can charge a standard power bank with it. In addition to this, I bought a USB pump which I can also power with the power bank and controlled using an Arduino board. The problem is that the power bank doesn't support charging and discharging at the same time, and I thought that I could use an Arduino board to control this, but I have no knowledge on this. Therefore, I need help.

Is it possible to have a system like the one sketched below, where the Arduino board controls the input/output of the power bank?

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

The black path is my current path, but I was wondering if I could do the red path so that I can have both chargings from the solar panel and discharge due to the pump and Arduino board.

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

sender: assistant

body:
Is it possible? Yes.
Is it easy? Maybe.

A relay shield or similar would allow you to break the power connection from the solar panel to the power bank input, wait 5 seconds and then connect the power bank output to the pump.<br>
Once you are done with the pump you could disconnect power from it and reconnect the charging power.

That is all fairly straight forward, maybe a dozen lines of code and some very simple wiring.

The issue is where does the arduino get power from? Or more accurately how does the arduino maintain power during the transitions between different power sources. How much of an issue this is depends a lot on how quickly the power pack transitions from charging to outputting and back and how you want the system to behave overnight or other times when there pump is idle but there isn't much sun light.

Also have you done a power budget? How much power does your pump take and how much power does your solar panel output under normal usage? Based on those two how long per day can you run the pump for assuming an ~80% efficient battery pack.


body:
You should be able to solve it with two diodes, preferably Schotty diodes, they have a low forward drop voltage.

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

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


message:
How to send a number to Arduino via Python over serial?

I call an API in Python and it gives as output as a single digit and an Arduino program receives this number over serial and displays it on a 7-segment display.

I wrote a different program in which Arduino sends the data and a Python program receives it. That worked but the following program is not working. What is the problem?

I am using Python 3 and Arduino Uno.

Python program:

    import serial ,requests, json, time
    arduino = serial.Serial('COM1', 9600, timeout=.1)
    time.sleep(1)
    response = requests.get("https://traffic.cit.api.here.com/traffic/6.1/flow.json?bbox=12.9808,77.5759;12.9803,77.5767&app_id=zbvY0tdRs089c3ZTKqWR&app_code=pxAtGksNBgVD9V5XF5nEzA",)
    #CALLING API
    response.content.decode("utf-8")
    data = response.json()
    text = str(data) #CONVERSION TO STRING
    l = len(text)
    for i in range(0,l): #Taking out the number
        if text[i] == 'J':
            j = text[i + 5]
            print (j)
            arduino.write(j) #writing over serial
            break

Arduino program:

    int a=2;
    int b=3;
    int c=4;
    int d=5;
    int e=6;
    int f=7;
    int g=8;
    int h=9;
    int rx_byte = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(a, OUTPUT);
      pinMode(b, OUTPUT);
      pinMode(c, OUTPUT);
      pinMode(d, OUTPUT);
      pinMode(e, OUTPUT);
      pinMode(f, OUTPUT);
      pinMode(g, OUTPUT);
      pinMode(h, OUTPUT);
      digitalWrite(h, 0);  // start with the "dot" off
    }

    void loop() {
      if (Serial.available() > 0) {
        rx_byte = Serial.read(); //reading serial
        switch (rx_byte) {
        case 0:
          zero();
          break;
        case 1:
          one();
          break;
        case 2:
          two();
          break;
        case 3:
          three();
          break;
        case 4:
          four();
          break;
        case 5:
          five();
          break;
        case 6:
          six();
          break;
        case 7:
          seven();
          break;
        case 8:
          eight();
          break;
        case 9:
          nine();
          break;
        }
      }
    }

    // write '9'

    void eight() {
      digitalWrite(a, 1);
      digitalWrite(b, 1);
      digitalWrite(c, 1);
      digitalWrite(d, 1);
      digitalWrite(e, 1);
      digitalWrite(f, 1);
      digitalWrite(g, 1);

    }
    void seven() {
      digitalWrite(a, 1);
      digitalWrite(b, 1);
      digitalWrite(c, 1);
      digitalWrite(d, 0);
      digitalWrite(e, 0);
      digitalWrite(f, 0);
      digitalWrite(g, 0);

    }
    void six() {
      digitalWrite(a, 1);
      digitalWrite(b, 0);
      digitalWrite(c, 1);
      digitalWrite(d, 1);
      digitalWrite(e, 1);
      digitalWrite(f, 1);
      digitalWrite(g, 1);
    }
    void five() {
      digitalWrite(a, 1);
      digitalWrite(b, 0);
      digitalWrite(c, 1);
      digitalWrite(d, 1);
      digitalWrite(e, 0);
      digitalWrite(f, 1);
      digitalWrite(g, 1);

    }
    void four() {
      digitalWrite(a, 0);
      digitalWrite(b, 1);
      digitalWrite(c, 1);
      digitalWrite(d, 0);
      digitalWrite(e, 0);
      digitalWrite(f, 1);
      digitalWrite(g, 1);
    }
    void three() {
      digitalWrite(a, 1);
      digitalWrite(b, 1);
      digitalWrite(c, 1);
      digitalWrite(d, 1);
      digitalWrite(e, 0);
      digitalWrite(f, 0);
      digitalWrite(g, 1);

    }
    void two() {
      digitalWrite(a, 1);
      digitalWrite(b, 1);
      digitalWrite(c, 0);
      digitalWrite(d, 1);
      digitalWrite(e, 1);
      digitalWrite(f, 0);
      digitalWrite(g, 1);
    }
    void one() {
      digitalWrite(a, 0);
      digitalWrite(b, 1);
      digitalWrite(c, 1);
      digitalWrite(d, 0);
      digitalWrite(e, 0);
      digitalWrite(f, 0);
      digitalWrite(g, 0);

    }
    void zero() {
      digitalWrite(a, 1);
      digitalWrite(b, 1);
      digitalWrite(c, 1);
      digitalWrite(d, 1);
      digitalWrite(e, 1);
      digitalWrite(f, 1);
      digitalWrite(g, 0);

    }
    void nine() {
      digitalWrite(a, 1);
      digitalWrite(b, 1);
      digitalWrite(c, 1);
      digitalWrite(d, 0);
      digitalWrite(e, 0);
      digitalWrite(f, 1);
      digitalWrite(g, 1);

    }

I am quite new to programming. Please help.

body:
I think you are sending ASCII values 0 - 9 over serial.  This is a bad idea, because they can be interpreted as control codes, always send printable characters.  So in this case send '0' to '9'.

Also you could make you code much smaller if you used arrays.

For instance

    int pins[8] = {2,3,4,5,6,7,8,9};
    int TheData [8][8] =
    {
        {1,1,1,1,1,1,0,0}, // 0
        {0,1,1,0,0,0,0,0}, // 1
        // etc
    };
    void write (int number)
    {
        for (int i = 0; i < 7; i++)
        {
           digitalWrite (pins[i], TheData[number][i]);
        }
    }

I'll let you figure out how to reduce setup to less than 3 lines :)


body:
The python code

    j = text[i + 5]
    print (j)
    arduino.write(j)

Is sending a single text character between '0' and '9', ascii values 48 to 58.

The c code

    rx_byte = Serial.read(); //reading serial
    switch (rx_byte) {
      case 0:

is looking for absolute values between 0 and 9.

There are two easy options to fix this, option 1 change the case statement to look for the correct values:

    rx_byte = Serial.read(); //reading serial
    switch (rx_byte) {
      case '0':

or option 2, rely on the fact that the ascii for the numbers is always 48 more than the number represented and subtract that:

    rx_byte = Serial.read() - '0'; //reading serial
    switch (rx_byte) {
      case 0:

`-'0'` and `-48` would have exactly the same effect here only by using `'0'` it makes it clear we are offsetting by the ascii value of a 0 rather than by some other randomly created number. It also saves you having to remember what the correct value is for 0.

Generally since you are using the value in a case statement I'd recommend the first option, it's a little more intuitive and avoids an extra calculation that can look a little odd if you are new to programming.
The reason I mentioned the second option is that this is the method you would use if you wanted to use the rx_byte value as the index in an array for any reason.


message:
I'm getting watchdog timer resets in NodeMCU. How can I permanently disable or stop that?

I'm using NodeMCU for my project. At first it works fine, but after some days it is resetting frequently because of the watchdog timer. I have used the `Esp.wdtfeed()` method also. But it is not working. Can you please tell me what the problem exactly with or any solution? Here is my code:
<!-- language-all: lang-cpp -->

    void setup(void) {
      ESP.wdtDisable();
      ESP.wdtEnable(WDTO_8S);
      Serial.begin(9600);
      int n = WiFi.scanNetworks();
      Serial.println("");
      if (n == 0)
        Serial.println("no networks found");
      else {
        for(int i=0;i<n;i++) {
          if(WiFi.SSID(i)==ssid1) {
            WiFi.begin(ssid1,password1);
            ssid=ssid1;
          } else if(WiFi.SSID(i)==ssid2) {
            WiFi.begin(ssid2,password2);
            ssid=ssid2;
          } else if(WiFi.SSID(i)==ssid3) {
            WiFi.begin(ssid3,password3);
            ssid=ssid3;
          }
        }
      }
      display.init();
      display.flipScreenVertically();
      display.setFont(ArialMT_Plain_16);
      display.setTextAlignment(TEXT_ALIGN_LEFT);
      display.drawStringMaxWidth(15,15, 128,"Display started");
      display.display();
      // Wait for connection
      display.clear();
      int j=0;
      while(j<10) {
        display.drawStringMaxWidth(15,15, 128,"connected to");
        display.drawStringMaxWidth(15,32, 128,ssid);
        display.display();
        display.clear();
        delay(1000);
        j++;
      }
      display.drawStringMaxWidth(15,32, 128,"");
      display.display();
      Serial.print("Connected to ");
      display.clear();
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      if (mdns.begin("esp8266WebForm", WiFi.localIP())) {
        Serial.println("MDNS responder started");
      }
      server.onNotFound(handleNotFound);
      server.begin();
      Serial.print("Connect to http://esp8266WebForm.local or http://");
      Serial.println(WiFi.localIP());
      server.on("/", getvalues);
      pinMode(buzzPin,OUTPUT);
      pinMode(but,INPUT);
    }

    void loop(void) {
      ESP.wdtFeed();
      if((WiFi.status()== WL_DISCONNECTED)||(WiFi.status()==WL_CONNECTION_LOST)) {
        display.drawStringMaxWidth(15,15, 128,"disconnected");
        display.display();
        int n = WiFi.scanNetworks();
        Serial.println("");
        if (n == 0)
          Serial.println("no networks found");
        else {
          for(int i=0;i<n;i++) {
            if(WiFi.SSID(i)==ssid1) {
              WiFi.begin(ssid1,password1);
              ssid=ssid1;
            } else if(WiFi.SSID(i)==ssid2) {
              WiFi.begin(ssid2,password2);
              ssid=ssid2;
            } else if(WiFi.SSID(i)==ssid3) {
              WiFi.begin(ssid3,password3);
              ssid=ssid3;
            }
          }
          int j=0;
          display.clear();
          while(j<10) {
            display.drawStringMaxWidth(15,15, 128,"connected to");
            display.drawStringMaxWidth(15,32, 128,ssid);
            display.display();
            display.clear();
            delay(1000);
            j++;
          }
          display.clear();
          display.drawStringMaxWidth(15,32, 128,"");
          display.display();
        }
      }
      getvalues();
      delay(20000);
    }

body:
here my way to find the bug first
1.comment out the watchdog from the code.
2.debug the code flow and find it get struck. Debugging in the sense put "Serial.print()" in between your code where you feel stuck but here don't disable your watchdog.


body:
After long time I have seen this question and thought of answering as I found the issue at that time itself, But not posted here.

After debugging for long time, I got to know that there is a string i am initializing with the data fetched from a site which has been overflown beyond the memory of NodeMCU. due to which it has thrown watchdog exception, So please do memory management properly as NodeMCU cannot do data processing and all.


message:
How to convert numbers from Serial port input to HEX String?

I am trying to read digits (number from 0 to 255) from Serial port, convert them to HEX String and send them using SoftwareSerial as HEX.

For example:
when I send '60' trough the serial port, the SoftwareSerial will send '3C'

currently I am using the following code:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 4); // RX, TX

    String inputString     = "";
    boolean stringComplete = false;

    int HexInt = 0;
    String HexString = "00";

    void setup() {
      Serial.begin(115200);
      mySerial.begin(38400);
      inputString.reserve(200);
      delay(500);
      Serial.println("");
      mySerial.println("");
    }

    void loop() {
      serialEvent();
      if(stringComplete) {
        HexInt = inputString.toInt();
        HexString = String(HexInt,HEX);
        if (HexInt<16) HexString = "0" + HexString ;
        HexString.toUpperCase();

        mySerial.println(HexString);

        Serial.println(inputString); //debug
        stringComplete = false;
        inputString = "";
      }

    }

    void serialEvent() {
      while (Serial.available()) {
        char inChar = (char)Serial.read();
        if (inChar == '\n') continue;
        if (inChar == '\r') {
          stringComplete = true;
          if (inputString == "") inputString = "NULL";
          inputString.toUpperCase();
          continue;
        }
        inputString += inChar;
      }
    }

My question is:
Is there a more elegant / effective way to perform the same outcome?

body:
You have the number. It's made up of two nibbles, each representing 4 bits (1 hex character).

If you want to do a manual conversion take the first nibble (AND with 240) add it's value to "0" then do the same for the lower nibble (AND with 15).

### OR

What I would do is use:

    char HexString[3];
    sprintf(HexString,"X",HexInt);

since you're not dealing with floats, you're good to go.

### OR

edit: I recalled a `printf` function that we put together once before, I don't know if it would work with SoftwareSerial, so you might have to play around with it a bit, but as a 3rd option, you could try the following. I don't have access to an Arduino or compiler at the moment, otherwise I'd have a play with this right now.

Before your setup:

    // Function that printf and related will use to print
    int serial_putchar(char c, FILE* f) {
        if (c == '\n') serial_putchar('\r', f);
        return Serial.write(c) == 1? 0 : 1;
    }

    FILE serial_stdout;

In your setup, add:

    // Set up stdout
    fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
    stdout = &serial_stdout;

in your loop, change your assignment to:

    HexString = printf("X",HexInt);

from: https://arduino.stackexchange.com/a/480/304


message:
5 inch TFT LCD for Arduino

I want to use a 5 inch 800x480 TFT display (touch not needed) with an Arduino (mega, uno or due). I'm thinking of buying this display: [link (buydisplay.com)][1]. How can I connect this ?

I have also seen some pricier screens with [serial i2c connection.][2], but I don't understand the difference between this and using a shield?

Do anyone have any advice for displays to order and/or shields for Arduino ? Preferably a solution that I can reproduce by my self later for mass-production by doing be own circuit board.

Thanks in advance!

  [1]: http://www.buydisplay.com/default/5-tft-lcd-display-module-wvga-800x480-high-resolution-for-mp4-gps
  [2]: http://www.buydisplay.com/default/5-inch-tft-lcd-module-800x480-display-controller-i2c-serial-spi

body:
You need a driver board to run it. SSD1963 based ones are popular and are often included on the screen, especially the 7" ones on eBay.

Arduinos cannot drive a display directly. Small TFT screens often include the driver chip on them in the form of a Chip On Glass (CoG). That can't be done with the larger screens due to the sheer amount of memory needed to store the frame buffer. So an external chip has to be used, or a microcontroller with built in TFT interface.

Note that even with an SSD1963 (or equivalent - see the ones BuyDisplay sell are based on the RA8875) interfacing the Arduino to the TFT screen results will most likely be somewhat disappointing. Especially if you are interfacing using SPI or I2C which will create a bottleneck. Best is to interface with a 16-bit "8080" interface (16 data bits, read, write, chip select, reset and D/C), however that takes a lot of IO pins, and ideally a proper parallel interface to drive it quickly. And you want a lot of RAM for manipulating the data you want to display...


message:
Roadblock using template functions

As part of a larger project, I'm trying to create a simple template function that will take an array and a value, both of the same type, and fill the array with the value. I'm running into the error quoted below:

"specializing member '::Fill_With<int>' requires 'template<>' syntax"

Below is the offending code fragment:

    // Simple function to fill an array with a specified value.
    template <class T> void Fill_With(T target_array, T value){
        int Array_Size = sizeof(target_array) / sizeof(T);
        for(int l = 0; l < Array_Size; ++l){
            target_array[l] = value;
        }
    }

    int array1[4] = {1,2,3,4}, k = 0;
    Fill_With<int>(array1, k);

I've read numerous other forum posts on the error message, but haven't quite been able to figure out what I'm missing. I've read that I need to include a blank "template<>" header before the function declaration but that didn't seem to solve the issue.
What am I doing wrong? Thanks!

body:
Let's start by getting rid of the templates, as they make things more confusing. In the following, I replaced `T` with `int`.

    void Fill_With(int target_array, int value){
        int Array_Size = sizeof(target_array) / sizeof(int);
        for(int l = 0; l < Array_Size; ++l){
            target_array[l] = value;
        }
    }

Let's try it out! I pasted this into the Arduino IDE and compiled it. Here is the output:

    sketch_aug01a/sketch_aug01a.ino: In function 'void Fill_With(int, int)':
    sketch_aug01a:4: error: invalid types 'int[int]' for array subscript
             target_array[l] = value;
                           ^
    exit status 1
    invalid types 'int[int]' for array subscript

This is telling us that we're trying to subscript (that's the term for the `[]` syntax) a variable of type `int` with a variable of type `int`. In C++, a pointer to the start of an array has type `int *`, not `int`. Let's fix the type of `target_array` in the function signature:

    void Fill_With(int *target_array, int value){

It compiles, but if you ran it you would quickly run into a bug:

- When given an expression, the [`sizeof` operator](http://en.cppreference.com/w/cpp/language/sizeof) will return the number of bytes in the type of the expression. The type of the expression `target_array` is `int *`, so `sizeof(target_array) == sizeof(int *)`. On 32-bit systems, `sizeof(int *) == 32/8 == 4`.
- When given a type, the `sizeof` operator returns the number of bytes in the type. So `sizeof(int)` gives the number of bytes in an `int`, which is [guaranteed to be at least 2 bytes (16 bits)](http://en.cppreference.com/w/cpp/language/types#Properties), but is usually 4 or 8 (it depends on the system).

Together, this means that `Array_Size` ends up being some small number like 0 or 1, regardless of the contents of `target_array`. To fix this, you can instead pass in the length of the array as a parameter:

    void Fill_With(int *target_array, int array_size, int value){
        for(int l = 0; l < array_size; ++l){
            target_array[l] = value;
        }
    }

    int array1[4] = {1,2,3,4}, k = 0;
    Fill_With(array1, 4, k);

Now you can put the templates back in:

    template <class T> void Fill_With(T *target_array, int array_size, T value){
        for(int l = 0; l < array_size; ++l){
            target_array[l] = value;
        }
    }

    int array1[4] = {1,2,3,4}, k = 0;
    Fill_With<int>(array1, 4, k);

By the way, C++ already has this function built in. It's called [`std::fill`](http://en.cppreference.com/w/cpp/algorithm/fill). Here's how to use it:

    #include <algorithm>

    int array1[4] = {1,2,3,4}, k = 0;
    std::fill(array1, array1 + 4, k);


message:
Using 2 GY521(mpu6050)s with Arduino Uno R3

I am working on creating a motion sensor based on an Arduino and MPU6050 interface. I'd like to retorfit my code to be able to read 2 mpu6050 devices. Besides defining a 0x69 address and setting AD0 to high on one and AD0 to low on the other, what additional changes to I need to make to my code? I posted my original code below. Thanks in advance!

    //Basic code to setup and read raw values from mpu6050
    //matt_m 7-9-2017

    #include <Wire.h>

    //Registers: Accelerometer, Temp, Gyroscope
    #define ACCEL_XOUT_H 0x3B
    #define ACCEL_XOUT_L 0x3C
    #define ACCEL_YOUT_H 0x3D
    #define ACCEL_YOUT_L 0x3E
    #define ACCEL_ZOUT_H 0x3F
    #define ACCEL_ZOUT_L 0x40
    #define TEMP_OUT_H 0x41
    #define TEMP_OUT_L 0x42
    #define GYRO_XOUT_H 0x43
    #define GYRO_XOUT_L 0x44
    #define GYRO_YOUT_H 0x45
    #define GYRO_YOUT_L 0x46
    #define GYRO_ZOUT_H 0x47
    #define GYRO_ZOUT_L 0x48

    #define PWR_MGMT_1 0x6B
    #define PWR_MGMT_2 0x6C

    #define MPU6050 0x68 //Device address
    #define ACCEL_CONFIG 0x1C //Accelerometer configuration address
    #define GYRO_CONFIG 0x1B //Gyro configuration address

    //Sensor output scaling
    #define accSens 0 // 0 = 2g, 1 = 4g, 2 = 8g, 3 = 16g
    #define gyroSens 1 // 0 = 250rad/s, 1 = 500rad/s, 2 1000rad/s, 3 = 2000rad/s

    int16_t  AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;

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

    void loop() {
      read_mpu6050();
      Serial.println(AcX);  //value to display
    }

    //setup MPU6050
    void angle_setup()
    {
      Wire.begin();
      delay (100);
      writeTo(MPU6050, PWR_MGMT_1, 0); //wakeup from sleep
      writeTo(MPU6050, ACCEL_CONFIG, accSens << 3); // Specifying output scaling
      of accelerometer
      writeTo(MPU6050, GYRO_CONFIG, gyroSens << 3); // Specifying output scaling
      of gyroscope
      delay (100);
    }

    void read_mpu6050()
    {
      // read raw accel/gyro measurements from device
      Wire.beginTransmission(MPU6050);
      Wire.write(0x3B);                  // starting with register 0x3B
    (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU6050, 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)
    }

    void writeTo(byte device, byte toAddress, byte val) {
      Wire.beginTransmission(device);
      Wire.write(toAddress);
      Wire.write(val);
      Wire.endTransmission();
     }

*edit: This below is the code with my best guess of how to implement 2 sensors, alas, my the output on my serial monitor keeps spitting out erraneous -1s and 0s

    #include <Wire.h>

    //Registers: Accelerometer, Temp, Gyroscope
    #define ACCEL_XOUT_H 0x3B
    #define ACCEL_XOUT_L 0x3C
    #define ACCEL_YOUT_H 0x3D
    #define ACCEL_YOUT_L 0x3E
    #define ACCEL_ZOUT_H 0x3F
    #define ACCEL_ZOUT_L 0x40
    #define TEMP_OUT_H 0x41
    #define TEMP_OUT_L 0x42
    #define GYRO_XOUT_H 0x43
    #define GYRO_XOUT_L 0x44
    #define GYRO_YOUT_H 0x45
    #define GYRO_YOUT_L 0x46
    #define GYRO_ZOUT_H 0x47
    #define GYRO_ZOUT_L 0x48

    #define PWR_MGMT_1 0x6B
    #define PWR_MGMT_2 0x6C

    #define MPU60501 0x68 //Device address #1
    #define MPU60502 0x69 //Device address #2
    #define ACCEL_CONFIG 0x1C //Accelerometer configuration address
    #define GYRO_CONFIG 0x1B //Gyro configuration address

    //Sensor output scaling
    #define accSens 0 // 0 = 2g, 1 = 4g, 2 = 8g, 3 = 16g
    #define gyroSens 1 // 0 = 250rad/s, 1 = 500rad/s, 2 1000rad/s, 3 = 2000rad/s

    int16_t  AcX1, AcY1, AcZ1, Tmp1, GyX1, GyY1, GyZ1;
    int16_t  AcX2, AcY2, AcZ2, Tmp2, GyX2, GyY2, GyZ2;
    void setup() {
     pinMode(0, OUTPUT);
     digitalWrite(0, HIGH);
     pinMode(1, OUTPUT);
     digitalWrite(1,LOW);
     Serial.begin(115200);
     angle_setup1();
     angle_setup2();
    }

    void loop() {
      read_mpu60501();
      Serial.println(AcX1);  //value to display
      read_mpu60502();
      Serial.println(AcX2);  //value to display

    }

    //setup MPU60501
    void angle_setup1()
    {
      Wire.begin();
      delay (100);
      writeTo(MPU60501, PWR_MGMT_1, 0); //wakeup from sleep
      writeTo(MPU60501, ACCEL_CONFIG, accSens << 3); // Specifying output
    scaling of accelerometer
      writeTo(MPU60501, GYRO_CONFIG, gyroSens << 3); // Specifying output
    scaling of gyroscope
      delay (100);
    }

    void read_mpu60501()
    {
      // read raw accel/gyro measurements from device
      Wire.beginTransmission(MPU60501);
      Wire.write(0x3B);                  // starting with register 0x3B
    (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU60501, 14, true);  // request a total of 14 registers
      AcX1 = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C
    (ACCEL_XOUT_L)
      AcY1 = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E
    (ACCEL_YOUT_L)
      AcZ1 = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40
    (ACCEL_ZOUT_L)
      Tmp1 = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42
    (TEMP_OUT_L)
      GyX1 = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44
    (GYRO_XOUT_L)
      GyY1 = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46
    (GYRO_YOUT_L)
      GyZ1 = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48
    (GYRO_ZOUT_L)
    }

    //setup MPU60502
    void angle_setup2()
    {
      Wire.begin();
      delay (100);
      writeTo(MPU60502, PWR_MGMT_1, 0); //wakeup from sleep
      writeTo(MPU60502, ACCEL_CONFIG, accSens << 3); // Specifying output
    scaling of accelerometer
      writeTo(MPU60502, GYRO_CONFIG, gyroSens << 3); // Specifying output
    scaling of gyroscope
      delay (100);
     }
    void read_mpu60502()
     {
      // read raw accel/gyro measurements from device
      Wire.beginTransmission(MPU60502);
      Wire.write(0x3B);                  // starting with register 0x3B
    (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU60502, 14, true);  // request a total of 14 registers
      AcX2 = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C
    (ACCEL_XOUT_L)
      AcY2 = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E
    (ACCEL_YOUT_L)
      AcZ2 = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40
    (ACCEL_ZOUT_L)
      Tmp2 = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42
    (TEMP_OUT_L)
      GyX2 = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44
    (GYRO_XOUT_L)
      GyY2 = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46
    (GYRO_YOUT_L)
      GyZ2 = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48
    (GYRO_ZOUT_L)
    }

    void writeTo(byte device, byte toAddress, byte val) {
      Wire.beginTransmission(device);
      Wire.write(toAddress);
      Wire.write(val);
      Wire.endTransmission();
    }

`

body:
When ever you start looking at multiples of an object you should think of classes and structures to do things.

If you wrote a class:

    class MPU6050
    {
    public:
     // Class constructor
     MPU6050 (const byte& address = 0x68)
       :m_Address(address)
     {
     }

     // Class destructor
     ~MPU6050()
     {}

     //setup MPU60501
     void angle_setup (void)
     {
       // Wire.begin();    // This should be called in main setup.
       delay (100);
       writeTo(MPU60501, PWR_MGMT_1, 0); //wakeup from sleep
       writeTo(MPU60501, ACCEL_CONFIG, accSens << 3); // Specifying output scaling of accelerometer
       writeTo(MPU60501, GYRO_CONFIG, gyroSens << 3); // Specifying output scaling of gyroscope
       delay (100);
     }

     void read_mpu6050(void)
     {
       // read raw accel/gyro measurements from device
       Wire.beginTransmission(MPU60501);
       Wire.write(0x3B);                  // starting with register 0x3B (ACCEL_XOUT_H)
       Wire.endTransmission(false);
       Wire.requestFrom(MPU60501, 14, true);  // request a total of 14 registers
       AcX1 = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
       AcY1 = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
       AcZ1 = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
       Tmp1 = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
       GyX1 = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44(GYRO_XOUT_L)
       GyY1 = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
       GyZ1 = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
     }

     // Data member that could be private and have access functions, but...
     int16_t  AcX1;
     int16_t  AcY1;
     int16_t  AcZ1;
     int16_t  Tmp1;
     int16_t  GyX1;
     int16_t  GyY1;
     int16_t  GyZ1;

    private:
     byte m_Address;
    };

You could then have any number of sensors by going:

    MPU6050  SensorOne;  // Address is optional and defaults to 68.
    MPU6050  SensorTwo (0x69);

To access the data or functions in them:

    SensorOne.angle_setup();
    Serial.println(SensorOne.AcX1);

You could put the sensor in an array and then use loops everywhere, but there isn't much of a saving for two instances.


message:
Arduino + SIM808: How to get only the JSON object response without the header?

I have been successfully getting the response from my web server. The problem is I get the whole package with header and content/body:

    Recv: 325 bytes: HTTP/1.1 200 OK
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/8.5
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    X-Powered-By-Plesk: PleskWin
    Date: Wed, 02 Aug 2017 03:26:37 GMT
    Connection: close
    Content-Length: 18

    1501644397698.2585

I want to only assign this `1501644397698.2585` to my double variable. How can I do this?

This is the code which sends and prints the response:

    Serial.println("waiting to fetch...");
    sim808.send(http_cmd, sizeof(http_cmd)-1);
    while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0) {
        Serial.println("fetch over...");
        break;
      }
      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
    }

body:
You need to receive the whole header and them trim what you don't want. The easiest way of doing this is scanning the header string for a new line (\n) character. From the start of the string to the new line gives you a line of the header. If the length of this substring is < 1 then look for the next line. Now scan between the start and the new line and see if you see a colon (:), if you do then this line is part of the header, look for the next new line. Otherwise use strtod() to convert the data to a double.

It should be something like this (not compiled, not tested):

    char* response = ".........";
    char* pStartOfLine = response;
    char* pEndOfLine = response;
    bool bFoundData = false;
    while (!bFoundData && pEndOfLine)
    {
      while (pEndOfLine != NULL && *pEndOfLine != '\n')
        pEndOfLine++;
      if (pEndOfLine && pEndOFLine != pStartOfLine)
      {
        char* pStartOfData = pStartOfLine;
        while (pStartOfLine != pEndOfLine && *pStartOfLine != ':')
          pStartOfLine++;
        if (*pStartOfLine != ':')
        {
          theData = strtod (pStartOfData, NULL);
          bFoundData = true;
        }
      }
    }

If it's in a separate function then you could just return rather than use the Boolean.

The order of the lines in the header are not guaranteed, but will always be in the same order from the same device with the same software, so as a cheat you could look for 'Content-Length: 18\r\n' and then just take the next non-blank line after that, but this is a more hacky way of doing it.


message:
I have just done this same code but not getting exact time as per Indian timezone...What thing should I add to get exact time?

#include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    /*
       This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
    */

    static const int RXPin = 10, TXPin = 11;
    static const uint32_t GPSBaud = 9600;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);

    void setup() {
      Serial.begin(115200);
      ss.begin(GPSBaud);
      Serial.println(F("DeviceExample.ino"));
      Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
      Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
      Serial.println(F("by Mikal Hart"));
      Serial.println();
    }

    void loop() {
      // This sketch displays information every time a new sentence is correctly encoded.
      while (ss.available() > 0)
        if (gps.encode(ss.read()))
          displayInfo();
      if (millis() > 5000 && gps.charsProcessed() < 10) {
        Serial.println(F("No GPS detected: check wiring."));
        while(true);
      }
    }

    void displayInfo() {
      Serial.print(F("Location: "));
      if (gps.location.isValid()) {
        Serial.print(gps.location.lat(), 6);
        Serial.print(F(","));
        Serial.print(gps.location.lng(), 6);
      } else {
        Serial.print(F("INVALID"));
      }

      Serial.print(F("  Date/Time: "));
      if (gps.date.isValid()) {
        Serial.print(gps.date.month());
        Serial.print(F("/"));
        Serial.print(gps.date.day());
        Serial.print(F("/"));
        Serial.print(gps.date.year());
      } else {
        Serial.print(F("INVALID"));
      }

      Serial.print(F(" "));
      if (gps.time.isValid()) {
        if (gps.time.hour() < 10) Serial.print(F("0"));
        Serial.print(gps.time.hour());
        Serial.print(F(":"));
        if (gps.time.minute() < 10) Serial.print(F("0"));
        Serial.print(gps.time.minute());
        Serial.print(F(":"));
        if (gps.time.second() < 10) Serial.print(F("0"));
        Serial.print(gps.time.second());
        Serial.print(F("."));
        if (gps.time.centisecond() < 10) Serial.print(F("0"));
        Serial.print(gps.time.centisecond());
      } else {
        Serial.print(F("INVALID"));
      }
      Serial.println();
    }

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

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

body:
Use NeoGPS instead of TinyGPS, it has time and date functions for timezone offsets.

Ref:
https://forum.arduino.cc/index.php?topic=473294.msg3237680#msg3237680


message:
getting " .error: failed sending 1116 bytes warning: espcomm_send_command: didn't receive command response"

I'm getting error while uploading sketch into nodemcu ch340g as shown below
[![enter image description here][1]][1]

I have tried these things to rectify the error

1) Changed usb cable

2) changed the port

3) flashed the firmware with nodemcu_float_0.9.6-dev_20150704.bin by esptool.py

4) flashed with nodemcu flasher

But no change at all and it is showing same error only what can i do now
  [1]: https://i.stack.imgur.com/u5hnH.png

body:
> 3) flashed the firmware with nodemcu_float_0.9.6-dev_20150704.bin by esptool.py

So assuming that actually completed successfully you can rule out anything being wrong with your hardware. There is no difference between manually flashing a firmware file and flashing using the IDE.

You need to take a look at the command you used to flash that firmware successfully, especially things like which port you used and what baud rate, and make sure you replicate those same settings in the IDE. Especially the baud rate, which you can select in the Tools menu.


body:
Problem solved by doing this</br>
In boards, I have mentioned node MCU 1.0 and that's the mistake I have done, after changing the board to node MCU 0.9, then the program is uploading and thanks for all your suggestions


message:
What is the maximum SPI speed for a slave Uno/clone?

I have a Rapsberry Pi master sending SPI requests to an Uno Chinese clone slave : I send 16 characters to the Arduino, which answers 16 others characters. What I send is not important, it's the Arduino answer that matters.

When I set the speed on the Raspberry Pi at 1 Mbit/s with my C program, the received answer coming from the Arduino is mostly garbage (random characters), but this issue disappears with lower speeds.

So that leads me to this question : what is the maximum SPI speed for a slave Uno/clone, in order to have no errors ?

**Edit** : the Arduino code :

    #include <SPI.h>

    char receivingBuffer[5];
    char sendingBuffer[5] = {'T', 'e', 's', 't', '!'};

    volatile char bytes_received = 0;

    void setup()
    {

      SPCR |= bit(SPE);

      pinMode(MISO, OUTPUT);

      SPI.attachInterrupt();

      SPDR = sendingBuffer[bytes_received];

    }

    ISR(SPI_STC_vect)
    {

      if (++bytes_received == 5)
      {

        bytes_received = 0;

      }

      SPDR = sendingBuffer[bytes_received];

    }

    void loop()
    {

      //

    }

Also, the C code on the RPi :

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <wiringPiSPI.h>

    #define SPI_CHANNEL 0
    #define SPI_SPEED   1000000 // Hz.

    int main(void)
    {

       wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED);

       while (1)
       {

          char buf[5] = {'T', 'e', 's', 't', '?'};

          printf("Sending   : %s\n", buf);

          wiringPiSPIDataRW(SPI_CHANNEL, buf, 5);

          printf("Receiving : %s\n\n", buf);

          sleep(1);

       }

       return 1;

    }

body:
The maximum speed for Arduino as a slave is F_CPU/4, so it's 4Mbps.
When the Arduino is the master it can work at F_CPU/2, so it's 8Mbps


message:
Problem reading from GPS

Right now I am working on a project where I need to turn on four LEDs in sequence, 1100 before 12 am and 1010 after 12 am. I am using a GPS in this project and I want to access the time from the GPS. The problem is that I am not getting it. How to make it possible?

GPS module: RoyalTek 4216

CODE:

    #include <NMEAGPS.h>
    #include <SoftwareSerial.h>
    SoftwareSerial gpsPort( 50, 52 );
    #define gps_port Serial1
    NMEAGPS gps;
    gps_fix fix;

    void setup() {
      Serial.begin(9600);
      gpsPort.begin(9600);
      for (int thisPin = 2; thisPin <= 13; thisPin++) {
        pinMode(thisPin, OUTPUT);
        int i=0;
        long k;
      }
      for (int n = 22; n <= 52; n++) {
        pinMode(n, OUTPUT);
      }
    }
    // the loop routine runs over and over again forever:
    void loop() {
      while (gps.available(gpsPort)) {
        gps_fix fix = gps.read();
        Serial.print(F("DATE:  "));
        if (fix.valid.date && fix.valid.time) {
          // Shift the date/time to local time
          NeoGPS::clock_t localSeconds;
          NeoGPS::time_t  localTime; {
            using namespace NeoGPS;
            localSeconds = (clock_t) fix.dateTime;
            localSeconds += 5 * SECONDS_PER_HOUR + 30 * SECONDS_PER_MINUTE;
            localTime = localSeconds;
          }
          Serial.print( localTime.date);
          Serial.print( '/' );
          Serial.print( localTime.month);
          Serial.print( '/' );
          Serial.println( localTime.year);
          delay(500);
          Serial.print("\n*************************\n");
          {
            Serial.print( F("TIME:  "));
            Serial.print( localTime.hours );
            Serial.print( ':' );
            Serial.print( localTime.minutes );
            Serial.print( ':' );
            Serial.print( localTime.seconds );
            delay(500);
            Serial.print("\n");
            k=localTime.hours;
            int i=0;
            long k;
            if (k>=0 &&  i==0) {
              digitalWrite(2, HIGH);
              digitalWrite(3, HIGH);
              digitalWrite(4, HIGH);
              digitalWrite(5, HIGH);
              delay(5000);
            } else {
              digitalWrite(2, LOW);
              digitalWrite(3, LOW);
              digitalWrite(4, LOW);
              digitalWrite(5, LOW);
              delay(5000);
            }
          }
        }
      }
    }

body:
So you don't know how to read the time from a GPS?  Is that the problem?

Since you haven't stated the make and model of GPS and microprocessor I can only give you generic information.

GPS output their data in ASCII format over a serial link usually operating at 9600 BAUD.  So you need to connect you microprocessor to the GPS using a secondary serial port (Not the serial port you upload through).  On something with only one serial port (Uno, ESP8266, etc) you need to use the SoftwareSerial library to do this.

Then read from the serial port as you would do normally and parse the string you read to extract the time portion of the message, this should be quite easy to spot.  Most GPS's pump out two different messages at regular intervals and so you need to filter the message you don't want.

Relying on just a GPS for time is a bad idea, because you will get periods where the azimuth of the satellites is to low and you won't get sufficient coverage.  I would also use an real time clock (RTC) and use the GPS to update the RTC periodically and source the time from the RTC.


body:
I hate to have to say this and I always try not to, but your code is awful.  Firstly it doesn't compile, and I can say that without even trying because the errors are very obvious.  If you reply is that it does compile then you have posted the wrong code.

In Setup() you are setting loads of pins to output, why?  You are only using 4 pins, 2,3 4 and 5!

Having a `using namespace` line at the top of your code is bad enough, it negates the purposes of a namespace, but having it in the middle of you code is really bad.  Just type the extra few characters, it will save you a lot of grief in the long run.

Scoping chunks of code can be good, but not in this case, it makes the code harder to read.  It would be better if you wrote a function to factor the date time printing out, i.e.

    void PrintDT (char* type, int a, int b, int c, char sep)
    {
        Serial.print(type);
        Serial.print( a );
        Serial.print( sep );
        Serial.print( b );
        Serial.print( sep );
        Serial.println( c );
    }

And then called it:

    PrintDT(F("DATE:  "), localTime.date, localTime.month, local.year, '/');
    PrintDT(F("TIME:  "), localTime.hours, localTime.minutes, localTime.seconds, ':');

The less lines of code you have the easier it is to spot bugs.

Here is why I said it won't compile:

        k=localTime.hours;

        int i=0;
        long k;

        if (k>=0 &&  i==0)

You are assigning a value to k before you have declared it, but looking at setup it could be a copy and paste error, because you have similar lines up there.

Also assign meaningful names to your variables.  I'm guessing that k is the hours and i is meant to be minutes?  To be honest in this case I wouldn't use variables at all, just have this code

    if (localTime.Hours >= 0 && localTime.Minutes == 0)

But that if statement doesn't do what you say you want to do at the top of the question.  When the time has any number of hours, including zero, and the minutes are zero.  According to you question you want

    if (localTime.Hours == 0 && localTime.Minutes == 0)

But that means you will only see the lights on 1100 for 1 minute at midnight.

I hope that helps, There is nothing wrong with the process you are following, just some of the things you doing and the logic.  If it doesn't fix it, clarify what the exact error is and we'll see what we can do.


message:
ATmega328p hangs on USART RX interrupt

I was able to use USART without interrupt driven and it worked perfectly! However, when I tried adding interrupt on `USART_RX_vect`, the program does not work as expected anymore.

Below is my small program. The expected behavior of this program is everytime I press a button the LED should toggle its state, but also by default the LED will toggle its state every 500ms. Right now, the LED toggles every 500ms but
 the moment I press a button on my machine keyboard to send data to the ATmega328p, the program stops (the led freezes on its last state).

I am not using an external clock, but I wonder if that could be the problem or I am missing something in my code that I can't figure out.

I appreciate any help. Thank you.

    #ifndef F_CPU
    #define F_CPU 1000000UL
    #endif

    #define FOSC F_CPU
    #define BAUD 4800
    #define MYUBRR FOSC/16/BAUD-1

    #include <avr/io.h>
    #include <util/delay.h>
    #include <avr/interrupt.h>

    void USART_Init(unsigned int ubrr) {
       UBRR0H = (unsigned char)(ubrr>>8);
       UBRR0L = (unsigned char)ubrr;
       UCSR0B = (1<<RXEN0) | (1<<RXCIE0);
       UCSR0C |= (1<<UCSZ00 | (1 << UCSZ01));
    }

    IRS(USART_RX_vect) {
        PORTC ^= (1 << PC5);
    }

    int main(void) {
     USART_Init(MYUBRR);
     DDRC |= (1 << PC5);
     sei();
     while(1) {
      PORTC ^= (1 << PC5);
      _delay_ms(500);
     }
     return 0;
    }

**Edit#1**: I modified IRS handler:
Code:

    IRS(USART_RX_vect) {
     while(!(UCSR0A&(1<<RXC0))){};
     unsigned char received = UDR0;
     PORTC ^= (1 << PC5);
    }

Status: Program does not work.

**Edit#2**: Fixed typo ISR instead of IRS (pffff)

**Solution**: I was missing the code for consuming the RX buffer and I had a typo: IRS should be ISR. Thanks for @Edgar Bonet and @Majenko for the help!

body:
I suspect if you were a fly you would see your LED flashing very very rapidly.

The reason is, your interrupt will constantly trigger itself over and over and over again.

Why? Because you aren't reading the incoming character from the RX buffer. And until you do the chip will keep alerting you that there is something there to read by triggering the interrupt.


body: Just replace `IRS` (Internal Revenue Service) with `ISR` (Interrupt Service Routine).


message:
ESP8266 Send data to Firebase using Arduino Uno error

Good day everyone! I have a project, in which the data from a button (number of clicks) will be sent to a real-time Firebase database. Every time the button is clicked the counter increases and will be updated in the firebase database.

**Wifi Module:
Esp8266 Esp-01 + Esp-01 Adapter**

![Esp8266 Esp-01 + Esp-01 Adapter][1]

In my understanding, there are 2 ways to use this wifi module.

 1. Upload the code to the Arduino Uno and use AT commands in the module to send data to the web.

 2. Upload the code inside the WiFi Module itself and after that it can be a standalone SOC and does not need the Arduino anymore after the code has been uploaded.

I have tried the second way, but I got confused and stuck. So far I have successfully plugged the adapter in a breadboard and tested some AT commands.

Since I will be using the second way I won't be using these. So I tried this code:

     #include <ESP8266WiFi.h>
     #include <FirebaseArduino.h>

     #define FIREBASE_HOST "https://duck-917ba.firebaseio.com/"
     #define FIREBASE_AUTH "r3jNQCsxN2Y2dcfawimRlzjLjdBSXLjstwGeyB0oMK"

     #define WIFI_SSID "mywifi"
     #define WIFI_PASSWORD "621533515"

    const int  buttonPin = 8;
    int buttonPushCounter = 0;
    int buttonState = 0;
    int lastButtonState = 0;

    void setup() {
      pinMode(buttonPin, INPUT);
      Serial.begin(9600);
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      Serial.print("connecting");
      while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
      }
      Serial.println();
      Serial.print("connected: ");
      Serial.println(WiFi.localIP());
      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
      Firebase.setInt("clicks",0);
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      // compare the buttonState to its previous state
      if (buttonState != lastButtonState) {
        // if the state has changed, increment the counter
        if (buttonState == HIGH) {
          // if the current state is HIGH then the button went from off to on:
          buttonPushCounter++;
          Serial.println("on");
          Serial.print("number of button pushes: ");
          Serial.println(buttonPushCounter);
          Firebase.setInt("clicks", buttonPushCounter);
        } else {
          // if the current state is LOW then the button went from on to off:
          Serial.println("off");
        }
        // Delay a little bit to avoid bouncing
        delay(100);
      }
      // save the current state as the last state, for next time through the loop
      lastButtonState = buttonState;
    }

**So I have plugged my 4-pin adapter to the following:**

- ARD(TX)-ADAPTER(TX)

- ARD(RX)-ADAPTER(RX)

- ARD(5V)-ADAPTER(VCC)

- ARD(GND)-ADAPTER(GND)

I have set the Generic ESP8266 Module Board.

**Problems Encountered:**

I am supposed to select the port of the ESP8266 but I only see the Arduino UNO port in the port list. When I compile the code I get this error:

[![enter image description here][4]][4]

I am now confused on what the error is all about. I thought since I am using an adapter I can use the **PROGRAMMING MODE** of the module easily. But it seems like my adapter is not doing its job. According to some of my research I have to use  TTL or FTDI USB-to-serial dedicated module / Ground some wires while compiling which is very confusing for a beginner like me.

**So here are my final thoughts:**

1. Can I input/flash code in my module using my Arduino and adapter?

2. Since the button is plugged in the Arduino's pin 8, does that mean that the code in the module will be successfully inserted? I will still need the Arduino to be plugged in the buttons?

3. What could be the reason why the module won't appear in the Port List and generates the errors?

I know this is quite a long and boring topic but I know a lot of aspiring IOT developers out there are having the same issues about this wifi module. I hope we can solve it together. Thanks!

  [1]: https://i.stack.imgur.com/Fntdn.jpg
  [4]: https://i.stack.imgur.com/iIWu5.png

body:
> 1.) Can I input/flash code in my module using my arduino and adapter?

Yes

> 2.) Since the button is plugged in the pin 8 of arduino. Does that mean If the code in the module will be successfully inserted. I will still need the arduino to be plugged in the buttons?

The ESP8266 cannot magically know about the Arduino and the Arduino cannot magically know about the buttons. If you have buttons connected to the Arduino then the Arduino needs telling about them. If the Arduino and ESP8266 need to work together then they both need programming to work together. If, and only if, you connect the buttons to the ESP8266 and not the Arduino do you not need the Arduino.

> 3.) What could be the reason why the module won't appear in the Port List and generates the errors?

The Arduino is getting in the way. Connect Arduino RESET to Arduino GND to disable the ATMega328p chip which is also trying to use TX and RX and conflicting with the ESP8266. Or better still get a cheap USB to UART cable (just a couple of dollars on eBay) and connect the adaptor direct to your PC without the Arduino.


body:
Connect GP00 to ground
This is required to flash ESP8266


message:
Video streaming by ESP32

I'm making an Arduino car and controlling it with a game-pad by bluetooth.  I want to have a live video from it by using ESP32 board and ov7670 camera or vc0706 camera. How can I do this ??

body:
See the documents and information of arducam library it may help you.....
This lib uses to connect with OV5640 5MP Camera and in its examples you may got your answer...


message:
Unexpected results and hard crash when modifying and addressing arrays & variables within a struct

I'm trying to use a 2D array inside a struct on my arduino to store sensor readings. I'm having two main problems:

1: My Arduino is crashing and resetting when I try to access certain directories in my Array

2: My arraysize variable doesn't seem to be incrementing the way I'm expecting it to.

I've attached snippets of my code that I think are relevant.

    struct calibration
    {
      float NTU[];
      unsigned int readings[][28];
      unsigned int arraysize = 0;
    };

    //Main
    void loop() {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Waiting...");
      if (digitalRead(inputPin) == HIGH)
        TakeReadings();
      delay(50);
    }

    //after taking many readings from a sensor and averaging...

    Calibration.readings[Calibration.arraysize][0] = average;
    Calibration.arraysize++;
    PrintMatrixToSerial();

    //serial print function

    void PrintMatrixToSerial() {
      Serial.print("1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1");
      Serial.println();
      for (int i=0; i<Calibration.arraysize; i++) {
        for (int j=0; j<7; j++) {
          Serial.print(Calibration.readings[i][j]); Serial.print("   ");
        }
        Serial.print('\n');
      }
    }

When trying to assign values to my Calibration.readings array in certain directories, the Arduino hard crashes. For instance, a crash happens when the arduino tries to execute:

    Calibration.readings[Calibration.arraysize][2] = average;

Secondly, after running my TakeReadings() function only once, I expect Calibration.arraysize to be equal to 1, therefore the PrintMatrixToSerial() function should only print one row of data; however, the serial monitor prints many rows. The following is an example of the output:

1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1

11   298   0   65292   779   1284   6
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
0   167   167   167   167   4245   40853
167   167   167   167   167   167   167
319   167   167   167   167   167   167

Is there an issue with my struct, or array declaration? I'm stumped at the moment, so any help would be appreciated.

body:
You are not specifying a size for your `readings` array:

    unsigned int readings[][28];

That is not saying "Give me an array of an unknown number of chunks, each of 28 values", it is actually saying "Give me a pointer to a block of memory (which I will provide later) which is arranged in rows of 28 values".

In C you must either provide a size for an array, in which case the memory is statically allocated for you, or manually allocate the memory at a later date.

    unsigned int readings[16][28]; // 16 rows of 28 int values

Or, for dynamic allocation:

    unsigned int readings[][28];

    // allocate the memory ...
    blah.readings = malloc(16 * 28 * sizeof(int));
    // do things with your array ...
    // and free up the memory when finished:
    free(blah.readings);

On an embedded system it is generally to know how many readings you will be taking beforehand. That way you can allocate the correct number of rows to the array before you compile the program, which makes many things more efficient.


message:
More missed messages with longer cables with nRF24L01+?

I am using nRF24L01+ 2.4 GHz transceiver.

When I connect them directly (with SPI pins 10..13 from Arduino) to the adapter board for the nRF24L01 I get occasionally errors (meaning the receiver does not get the sent message).

However, I want to use one nRF24L01 purely for transmitting, and one for receiving. So each Arduino will have 2 nRFs, one for receiving, one for transmitting.

Since they both use SPI, I need to take the pins 10..13 to a breadboard and forward them from there to both nRFs. However, I did a test with only the transmitter, and found out I get more errors than direct wiring.

The only difference is that I now use extra jumper wires (4" / 10 cm). Can the extra cable length cause problems?
Would it help if I use less long M/F dupont cables? (so the total length still is 8"/20cm)? ... I don't have such short ones, so I cannot try.

I use for the breadboard to the nRFs 8"/20cm M/F dupont cables.

See picture below. The white/grey/red/blue 20cm/8" dupont cable directly wired to pins 10..13 Arduino gives less errors than the situation on the photo where the white/orange/red/blue 4"/10cm cables are added.

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

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

body:
the Antenna is interfering with the signals because of its proximity to the point on the bread board where you are connecting the wires, as Majenko said.

If you rotate the nRF24L01 board 180 degrees you will increase the distance between the wires and the antenna and this will reduce the interference, but because of the way radio waves propagate there is also a chance that it may make it worse.  The radio wave propagate from the antenna in a share particular to the antenna.  I don't know what shape this antenna puts out, I'd expect it to be omnidirectional (all ways) because of its purpose.  However all directions are not equal because of reflections, the shape of the antenna, defects in the shape of the antenna, etc and if the pattern of the propagation can be mapped you can identify the make of board and if the mapping is accurate enough even the instance of the board itself.

So, to cure interference:

 1. Increase the distance this reduces the power of the interference by the square of the distance.
 2. Change the orientation, usually by something other than 90 or 180 degrees.
 3. Shield the wires.

In short move the antenna further away from the wires, can you use MF DuPont wires to remove the radio from the breadboard all together.  The fact it won't sit still and is sliding all over you desk will probably help with reflections.


message:
Connecting Arduino Uno WiFi Developer Edition to the Internet

I recently bought an [Arduino Uno WiFi Developer Edition](http://www.arduino.org/products/boards/arduino-uno-wifi) from [here](http://www.robotshop.com/en/arduino-uno-wifi-microcontroller.html). Although all the other functionality appears to work (I’m able to upload/run programs, read sensors I plug in, etc.), I am not able to connect the Arduino to the internet. The Arduino has a built in ESP8266 chip which is compatible with the WiFi Link library, however, running ScanNetworks in the Arduino mac IDE (File > Examples > WiFi Link > ScanNetworks) doesn't work, nor does it print any errors. Other example files in that library don't work either. The CheckWiFiLinkFirmwareVersion program in the same library will print the welcome message "WiFi Link firmware check." but nothing after that.

I have tried every other WiFi library I could find in the library manager window (Sketch > Include Library > Manage Libraries), namely

 - Arduino Uno WiFi Dev Ed Library
 - WiFiEsp
 - WiFi101
 - WiFi

However, none of them work. Is the Arduino's WiFi chip defective, or am I doing something wrong? One reviews on the website that I bought the Arduino from said this (see [lenny](http://www.robotshop.com/en/arduino-uno-wifi-microcontroller.html#customer-reviews)):

> Arduino.org (which is different from arduino.cc) has not made software available to access the WiFi capabilities of this board. As far as I can tell, the wifi cannot be used. They keep saying that the software is coming soon.
>
> See this thread on their forum: http://www.arduino.org/forums/uno/arduino-uno-wifi-arduinowifi-library-incomplete-solution-for-mqtt-tcp-udp-socket-communication-540

In summary, is the Arduino Uno WiFi Developer Edition known to be defective? If not, what am I doing wrong? If it is, could I potentially get a WiFi shield and use that instead of the built in chip? I have other shields for the Arduino (e.g. an SD card shield) that are working fine.

body:
The correct WiFi library for that board is here:

* https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib

If that is not working you may have a defective board. Maybe the ESP8266 firmware is incorrect.


body:
I am sure it is not defective. You just don't understand how it works, because of it's architecture. In addition the original firmware and the UnoWifiDefEd library are strange and limited. I recommend using WiFi Link firmware and library.
I currently write a community documentation for the [Uno WiFi & WiFi Link][1]

  [1]: https://github.com/jandrassy/arduino-firmware-wifilink/blob/ota/UNOWIFI_DEV_ED.md


body:
Do you have access to the Webgui?

with the Webgui you can configure the wifi settings.
you do not need to upload sketches for this.
It is a good test if there is no defect.

Connect your PC Wi-Fi or with your smartphone directly to the Aduino uno wifi.
Start your browser and type in the following IP: 192.168.240.1
and now you should see the WebGUI.


message:
Format error with ESP8266 compile

I get this error when I try to compile and upload the code for the ESP826612E

    fork/exec /home/c/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++: exec format error

I don't understand what the problem is, It was working fine for days until today.

Anyone has solutions?

body:
I suspect you are running a 32-bit compiler on a 64-bit operating system. You will need to install the 32-bit support libraries.

    $ sudo apt-get install libc6-i386


message:
is a 5V cellphone power supply stabilised?

can I feed my arduino UNO with a 5V cellphone USB power supply ?
Since the arduino board doesn't regulate the 5V from the USB input, is a cellphone power supply sufficiently regulated ?

body:
Yes. USB is a standard. You can even use 5V power packs for portable gizmos.

Caution: Ken Shirrif have a good post about non-original USB chargers and its perils. ([A dozen USB chargers in the lab: Apple is very good, but not quite the best][1]). Read them and learn a lot.

I only use the original charger that comes with the cell or tablet (and that usually last longer that the cell or tablet that it comes with). I don't trust any third party USB charger or car adapter after Ken's analysis

  [1]: http://www.righto.com/2012/10/a-dozen-usb-chargers-in-lab-apple-is.html


body:
It is a USB (1.0 & 2.0) requirement that a USB Host power lines are 5 volts and can supply up to 500mA.  [Here is a USB power standards table from wikipedia.org.][1]

If your Arduino project pulls more, then the 5 volt level may drop.  That is to say, for more than 500mA you will need to consult the power pack specifications.

  [1]: https://en.wikipedia.org/wiki/USB#Power


body:
In general terms yes, the output of a USB power adaptor for a mobile phone will be suitably stabilised.

Most phones have the ability to monitor the voltage and adjust the charging current depending on the voltage they see. If the voltage drops below, say 4.5V, they will reduce the current they draw until it rises back above that threshold (as can be seen if you use a 1A cable on a 2A charger, the phone will throttle the current to within the 1A range since the cable imposes too high a voltage drop).

For this reason it is important that power adaptors put out the correct voltage otherwise mobile phones wouldn't be able to work properly with them.

Cheap imported USB power adaptors often fall far below proper safety standards, though, so you should use a proper branded one (Apple, Samsung, etc) from a reputable dealer, not something for $4 off eBay. Those cheap ones are a serious safety hazard and can cause electric shocks and fires.


message:
How can I know if I can stack some shield on another shield?

Yesterday I tried to stack a motor shield on a servo motor shield already stacked on my Arduino Uno.

But I realized that I have some problem when I try to use both of them. It seems like some energy is lost or the stepper motor connected to my servo motor shield move weirdly slowly.

I already checked online, and I found some explanations about stacking many shields. About making sure the shields don't use the same pins or SS. As a beginner, help would be very helpful. Thank you.

Here are the two shields I use.

 - Smart Servo Shield for dynamixel
https://store.arduino.cc/arduino-motor-shield-rev3

 - Smart Arduino Digital Servo Shield for Dynamixel AX
https://www.dfrobot.com/product-958.html

wiki : https://www.dfrobot.com/wiki/index.php/Digital_Servo_Shield_for_Arduino_SKU:DRI0027

On these links, you can find all the specs with the pins used. I think I have some pinß shared by both of them... But not sure.

Does anyone have a solution please? Many thanks in advance.

body:
First you have to compare the pinouts of the two shields. If the shields use completely different pins then yes, you can use them together.

However if they share pins then you need to look in more detail at what those pins are and how they are being used.

In your example you have SPI being used (pins 10-13) for one shield and PWM (3/11) and GPIO (8/9/12/13) and analog input (A0/A1) for the other shield.

You can see now that there is a conflict. For instance pin 13 for the SPI clock for the DFRobot shield is also being used for one of the GPIO pins of the Arduino shield. Pin 12 for MISO is being used as GPIO. Pin 11 for MOSI is also being used for PWM.

Those are disparate functions on the pin, so it can never work.

However if the SPI pins were being used for both shields *as SPI* then that *could* work. In that case it's only the "chip select" pin that needs to be unique for each shield, since SPI is a Master-Slave Bus protocol which can be shared amongst multiple shields.


message:
Writing on a SdCard

I'm writing on a SD card the value of a measured voltage. I've a good sampling/writing frequency but regularly the acquisition take a lot of time (like 4000us instead of 400us). I noticed that this "pause" appears every 85 values (my values are 6 bytes long, so it appears every 510 bytes).

So I have hypothesized that there is a buffer of 512 bytes somewhere which is full and need some times to empty.

But I don't know where is this buffer. In SDcard? in Arduino? And how can I avoid this issue?

Here, my results on 1Hz sinus with a zoom on the "break":[![enter image description here][1]][1]

And here my loop to read the value and write it on sd card:

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

  [1]: https://i.stack.imgur.com/Cb02t.jpg
  [2]: https://i.stack.imgur.com/iWD1Z.jpg

Hope you can help me guys !

body:
The buffer is in the SD card library. It is the size of one block on the SD card. When it is full it needs flushing out to the SD card, which takes time. Once that is done the buffer is then empty again and can be filled back up by your code.

It has to be done this way because SD cards work in blocks of 512 bytes.


body:
Possibilities:

- What you can do it measure what you need inside an interrupt routine (I hope the measurement itself does not take too long). Write it to a buffer in the interrupt routine. Your 'normal' loop can do the writing to the SD card.
- A possible very extensive solution would be to send the sampled data to another Arduino which can store it on an SD without affecting the sampling (since it's done on another Arduino).
- Using DMA (Direct Memory Access), however afaik this option is not available for an Arduino.


message:
Arduino IDE missing libread.s0.6

I just recently installed the ESP8266 libraries on the arduino IDE using the boards manager, the code compiles fine with the ESP, but when the board is changed to UNO, i get this error,

    opt/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libreadline.so.6: cannot open shared object file: No such file or directory

Any solution to this?

body:
So install it?

    $ sudo apt-get install libreadline6

Or, if you need the i386 version on an x64 platform:

    $ sudo apt-get install libreadline6:i386


message:
Use Print library to set string variable

I need a function that has the basic functionality of the Print library, accepting different kinds of argument types and parsing them. However, I would like to then store the result in a string/char array. Does anybody know how I might utilize the Print library to do so?

body:
You can get all the functionality of `Print` by creating your own class
that inherits from it. For this, you only need to implement the
`size_t write(uint8_t)` method that prints a single character. Here is a
simple class that inherits from both `Print` and `String`, i.e. you get
a `String` you can `print()` and `println()` into:

    // A String you can print() and println() into.
    class PrintString : public Print, public String
    {
    public:
        PrintString() : String() {}

        size_t write(uint8_t c) {
            *this += (char) c;
            return 1;
        }
    };

And here is how you could use it:

    PrintString answer;
    answer.print("The answer is ");
    answer.println(42);


message:
ESP8266 connecting keypad and lcd display

I have ESP8266 type - [![enter image description here][1]][1]

I have added a keypad [![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/GRAja.jpg
  [2]: https://i.stack.imgur.com/wj5VS.jpg

With a standard lcd display.

I have connected the keypad from d0 to d7, however after watching some tutorials i have to connect the lcd display(SDA,SCL) to D0 and D1, where i should connect the display to when they are taken by the keypad?

body:
You can read the keypad using a single analog input (A0 in ESP8266) using this circuit:

[![keypad resistor array][1]][1]

When you press a key, some resistors are connected between Vcc and Ground. For each key, the total resistence is different, and the voltage at the input pin is different.

To read the keypad, you read the voltage at the input pin A0. You also have a table that associate the readings with keys. You search in the table for the nearest entry to the value you get. That's your key.

Wire the circuit and make a little sketch to read the values for each key you press. That's how you construct your table.

The value at A0 will be a little different each time you read the pin. That's is normal. Don't expect a exact macht.

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


message:
Coding or Wiring? Dual Piezo sensor not triggering LED lights

I am running two piezos off an Arduino UNO and trying to get 10 LED lights to trigger when the piezo voltage exceeds a certain threshold. Problem is, the LEDs wont fire when the Piezo voltage exceeds that threshold and I'm not sure if it is a coding or wiring problem.

Below are pictures of the wiring (Top and bottom) and code. Any help is much appreciated!!

[![Breadboard][1]][1]

[![Arduino][2]][2]

  [1]: https://i.stack.imgur.com/r5NR1.png
  [2]: https://i.stack.imgur.com/SfE4q.jpg

<!-- language: lang-js -->

    /*
      Dual Piezo Bond Auger Sensor; Blinking LED Light Stack Sketch

      -----------------------------------------------------*/

    //Piezo 1 Pin (PiezoPin1)
    //Piezo 1 connected to A0
    int PP1 = 0;

    //Piezo 1 Pin (PiezoPin1)
    //Piezo 2 connected to A1
    int PP2 = 1;

    //Sets the threshold for the detected sound to trigger the LED
    const int threshold = 0.01;

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

      for (int i = 4; i < 12; i++) {
        pinMode(i, OUTPUT);
        //sets the led pins 2-11 to output
      }
    }

    void loop() {
      //Ensure to turn off ALL LEDs before continuing
      for (int i = 4; i < 12; i++) {
        digitalWrite(i, LOW);
      }

      /* Read the Piezos
        Reads both piezos and outputs the values. Triggers LED lights
        to fire when a peak voltage is exceeded
        Adjust the value based on the peak signal voltage you
        want to trigger the LED lights*/
      int Piezo1ADC = analogRead(PP1); // Read Piezo 1 ADC value
      float Piezo1V = Piezo1ADC / 1023.0 * 5.0; // Convert to voltage
      int Piezo2ADC = analogRead(PP2); // Read Piezo 2 ADC value
      float Piezo2V = Piezo2ADC / 1023.0 * 5.0; // Convert to voltage
      Serial.println(Piezo1V); //Print the voltage from Piezo 1
      Serial.println(Piezo2V); //Print the voltage from Piezo 2
    }

    // The blink function - used to turn the LEDs on and off
    void blink(int LEDPin11, int LEDPin2, int LEDPin3, int LEDPin4, int LEDPin5, int LEDPin6, int LEDPin7, int LEDPin8, int LEDPin9, int LEDPin10, int Piezo1V, int Piezo2V, int threshold) {
      if (Piezo1V >= threshold || Piezo2V >= threshold) {  //toggle status of LED pins linked to PP1
        // Blink the LEDs on for both Piezos
        { digitalWrite(LEDPin2, HIGH);
          // Delay so that you can see the LEDs go On.
          delay(10);
          // Turn the LEDs Off
          digitalWrite(LEDPin2, LOW);
          // Increase this Delay if you want to see an actual blinking effect.
          delay(10);
        }
        { digitalWrite(LEDPin3, HIGH);
          delay(10);
          digitalWrite(LEDPin3, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin4, HIGH);
          delay(10);
          digitalWrite(LEDPin4, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin5, HIGH);
          delay(10);
          digitalWrite(LEDPin5, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin6, HIGH);
          delay(10);
          digitalWrite(LEDPin6, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin7, HIGH);
          delay(10);
          digitalWrite(LEDPin7, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin8, HIGH);
          delay(10);
          digitalWrite(LEDPin8, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin9, HIGH);
          delay(10);
          digitalWrite(LEDPin9, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin10, HIGH);
          delay(10);
          digitalWrite(LEDPin10, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin11, HIGH);
          delay(10);
          digitalWrite(LEDPin11, LOW);
          delay(10);
        }
        { digitalWrite(LEDPin10, HIGH);
          delay(10);
          digitalWrite(LEDPin10, LOW);
          delay(10);
        }
      }
    }

body:
Well, you never call `blink`, so leds never get a chance to light up.

Also, you are turning down the led at the begining of each `loop`. That will cause flickring.

And you don't need so many parameters for `blink`. In fact, what you need is a little function for blinking just one led.

I think this sketch is what your are looking for (but I can't assure it's correct)

    /*
      Dual Piezo Bond Auger Sensor; Blinking LED Light Stack Sketch

      -----------------------------------------------------*/

    //Piezo 1 Pin (PiezoPin1)
    //Piezo 1 connected to A0
    int PP1 = 0;
    //Piezo 1 Pin (PiezoPin1)
    //Piezo 2 connected to A1
    int PP2 = 1;

    //Sets the threshold for the detected sound to trigger the LED
    const int threshold=0.01;

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

     for(int i = 4; i<12; i++) {
      pinMode(i, OUTPUT);
      //sets the led pins 2-11 to output
     }
    }

    void loop()
    {
     /* Read the Piezos
       Reads both piezos and outputs the values. Triggers LED lights
       to fire when a peak voltage is exceeded
       Adjust the value based on the peak signal voltage you
       want to trigger the LED lights*/
     int Piezo1ADC = analogRead(PP1); // Read Piezo 1 ADC value
     float Piezo1V = Piezo1ADC / 1023.0 * 5.0; // Convert to voltage
     int Piezo2ADC = analogRead(PP2); // Read Piezo 2 ADC value
     float Piezo2V = Piezo2ADC / 1023.0 * 5.0; // Convert to voltage
     Serial.println(Piezo1V); //Print the voltage from Piezo 1
     Serial.println(Piezo2V); //Print the voltage from Piezo 2

     if(Piezo1V >= threshold||Piezo2V >= threshold)  //toggle status of LED pins linked to PP1
      // Blink the LEDs on for both Piezos
     {
      {
       littleBlink(2);
       littleBlink(3);
       littleBlink(4);
       littleBlink(5);
       littleBlink(6);
       littleBlink(7);
       littleBlink(8);
       littleBlink(9);
       littleBlink(10);
       littleBlink(11);
      }
     }
    }

    void littleBlink(int pin)
    {
     digitalWrite(pin, HIGH);
     delay(10);
     digitalWrite(pin, LOW);
     delay(10);

    }


message:
Multiple SPIs on one Arduino [SOLVED]

**Setup**

- I have 2 Arduinos... each has two 2.4 GHz nRF24L01+ transceivers (so in total 4).
- Per Arduino, one is only for transmitting, while the other is for receiving (to prevent the need for switching between transmitting and receiving).
- The receiver and transmitter are on different channels (per Arduino, so channel 109 for receiver on arduino 1 and transmitter on arduino 2 and 112 for the other pair).

**SPI / Chip Select**

Because the nRF24L01+ are SPI devices, I need to use Chip Select, since there is only one SPI bus on an Arduino.

**Setup settings**

Since I can both receive and send (successfully) I did not add the Setup code (I used slowest speed 250 kbps, 16 bytes payload, no auto ack, no retries, highest power).

**Problem**

I can transmit/receive from both Arduinos, so all 4 transceivers work correctly.
However, what I see in the output (see directly after the logging), is when I send, a lot of messages which should be received are missed. See the log at the end

Also, when I remove the write and replace it by a delay(1) than I miss just occasionally a message, so I think the write is the problem.

**Assumption**

Is it possible that during the write so many message from the other Arduino are colliding? I would expect a very fast on-air time, and even than, using two different channels should not make messages collide.

So it seems, while calling the Transmit for one RF, the other does not receive somehow. I know the CS pin of the receiver is HIGH (inactive) during transmitting (transmitter CS pin is LOW), but I would assume messages would be received by the RF, and when I set the CS pin of the receiver to LOW (active), that I can read the messages.

**Code (of one of the Arduinos)**

The code for the other Arduino is almost similar (only opposite port names as transmitter/receiver)

    /*
    */
    #include <SPI.h>
    #include "RF24.h"

    static const uint8_t RECEIVER_CE    = 5; // Chip Enable
    static const uint8_t RECEIVER_CS    = 6; // Chip Select
    static const uint8_t TRANSMITTER_CE = 7; // Chip Enable
    static const uint8_t TRANSMITTER_CS = 8; // Chip Select

    RF24 radioReceiver(RECEIVER_CE, RECEIVER_CS);
    RF24 radioTransmitter(TRANSMITTER_CE, TRANSMITTER_CS);

    uint32_t counter = 0;

    static const int PAYLOAD_SIZE = 16;

    static const int NR_OF_LOG_ITEMS = 10;
    static const int LOG_LENGTH = 25;
    uint32_t logData[LOG_LENGTH][NR_OF_LOG_ITEMS];
    uint8_t currentLogLine = 0;

    void setup()
    {
      for (int m = 0; m < LOG_LENGTH; m++)
      {
        for (int n = 0; n < NR_OF_LOG_ITEMS; n++)
        {
          logData[m][n] = -1;
        }
      }

      pinMode(RECEIVER_CE   , OUTPUT);
      pinMode(RECEIVER_CS   , OUTPUT);
      pinMode(TRANSMITTER_CE, OUTPUT);
      pinMode(TRANSMITTER_CS, OUTPUT);

      digitalWrite(RECEIVER_CE   , HIGH);
      digitalWrite(TRANSMITTER_CE, HIGH);

      Serial.begin(250000);
      Serial.println(F("CONTROLLER"));

      digitalWrite(RECEIVER_CS   , LOW); // Select
      digitalWrite(TRANSMITTER_CS, HIGH); // Deselect

      radioReceiver.begin();
      radioReceiver.setPALevel(RF24_PA_MAX);
      radioReceiver.setChannel(109);
      radioReceiver.setDataRate(RF24_250KBPS);
      radioReceiver.setRetries(0, 0);
      radioReceiver.setAutoAck(false);
      //radioReceiver.enableAckPayload();
      radioReceiver.setPayloadSize(PAYLOAD_SIZE);
      //radioReceiver.enableDynamicPayloads();
      //radioReceiver.disableCRC();
      radioReceiver.setCRCLength(RF24_CRC_8);

      digitalWrite(RECEIVER_CS   , HIGH); // Deselect
      digitalWrite(TRANSMITTER_CS, LOW);  // Select

      radioTransmitter.begin();
      radioTransmitter.setPALevel(RF24_PA_MAX);
      radioTransmitter.setChannel(112);
      radioTransmitter.setDataRate(RF24_250KBPS);
      radioTransmitter.setRetries(0, 0);
      radioTransmitter.setAutoAck(false);
      //radioTransmitter.enableAckPayload();
      radioTransmitter.setPayloadSize(PAYLOAD_SIZE);
      //radioTransmitter.enableDynamicPayloads();
      radioTransmitter.disableCRC();
      radioTransmitter.setCRCLength(RF24_CRC_8);

      byte addresses[][6] = {"Read ", "Write"}; // TODO: Change name to slave/contr?
      radioReceiver.openReadingPipe(0, addresses[1]);
      radioTransmitter.openWritingPipe(addresses[0]);

      radioReceiver.startListening();
      radioTransmitter.stopListening();

      //radio.writeAckPayload(1, &counter, PAYLOAD_SIZE);
      //radio.printDetails();
    }

    uint8_t receiverBuffer   [PAYLOAD_SIZE];
    uint8_t transmitterBuffer[PAYLOAD_SIZE];

    uint32_t prevResponse = -1;
    uint32_t response;

    void loop(void)
    {
      // Transmit.
      //Serial.print("Sending: ");
      //Serial.println(counter);

      transmitterBuffer[0] = counter >> 24;
      transmitterBuffer[1] = (counter & 0x00FFFFFF) >> 16;
      transmitterBuffer[2] = (counter & 0x0000FF00) >> 8;
      transmitterBuffer[3] = (counter & 0x000000FF);

      digitalWrite(TRANSMITTER_CS, LOW);  // Select
      digitalWrite(RECEIVER_CS   , HIGH); // Deselect
      //if (!radioTransmitter.write(transmitterBuffer, PAYLOAD_SIZE))
      {
        //Serial.println(F("Sending failed."));
      }
      delay(10); // Fake write

      // Receive.
      byte pipeNo = 0;

      digitalWrite(TRANSMITTER_CS, HIGH);  // Deselect
      digitalWrite(RECEIVER_CS   , LOW); // Select

      while ( radioReceiver.available(&pipeNo))
      {
        radioReceiver.read(receiverBuffer, PAYLOAD_SIZE);

        response = (receiverBuffer[0] << 24) +
                   (receiverBuffer[1] << 16) +
                   (receiverBuffer[2] << 8) +
                   (receiverBuffer[3]);
        Serial.print("Received: ");
        Serial.print(response);

        if (prevResponse == -1)
        {
          prevResponse = response - 1;
        }
        else
        {
          if (prevResponse + 1 != response)
          {
            Serial.print(" MISSED ");
            Serial.print(response - prevResponse - 1);
          }
          prevResponse = response;
        }
        Serial.println("");
      }

      // Logging
      currentLogLine++;
      counter++;
      delay(10);  // Try again later
    }

**Log**

    Received: 10261 MISSED 15
    Received: 10262
    Received: 10263
    Sending: 245
    Received: 10278 MISSED 14
    Received: 10279
    Received: 10280
    Sending: 246
    Received: 10296 MISSED 15
    Received: 10298 MISSED 1
    Received: 10299
    Sending: 247

body:
[solved] ... I found out I HAVE to put one of the CS (chip select) pins to pin 10.

I thought it would not needed since the CS pin is different per SPI device, but it seems one needs to be on pin 10. Or at least, now I don't get problems sending/receiving (except some errors now and than, but that's normal with RF devices).

Thanks for everybody giving comments to my question.


message:
Mega + SIM808 GPRS GSM GPS IPX-SMA module power on from code

Is it possible to turn on the SIM808 module from code? There is a button in the SIM808 board to activate the module, but I need to turn it on from the code automatically. This is because my device will be stored hidden inside a vehicle so I do not have to keep turn on and off by hand.

[This][1] is the model.

  [1]: https://www.banggood.com/SIM808-Module-GSM-GPRS-GPS-SMS-Development-Board-IPX-SMA-with-Antenna-p-1062818.html

body:
Looking at the pictures it looks like it should be possible to take the two exposed connections of the switch and add flying leads to them and run them back to the microprocessor to allow it to turn them on and off.  The possible problem is the current that has to run through the switch.

You will need to investigate, but it looks like it could be done like that if you can't find a better solution.


message:
How to add this old BASIC code snippet to work in Arduino C++ for FastLED?

I've been trying to implement this old code that randomly transitions to RGB color into my Arduino board that uses FastLED.

    Static Col1, Col2, Col3 As Integer
    Static C1, C2, C3 As Integer
    If (Col1 = 0 Or Col1 = 250) And (Col2 = 0 Or Col2 = 250) And (Col3 = 0 Or Col3 = 250) Then
      C1 = Int(Rnd * 3)
      C2 = Int(Rnd * 3)
      C3 = Int(Rnd * 3)
    End If
    If C1 = 1 And Col1 <> 0 Then Col1 = Col1 - 10
    If C2 = 1 And Col2 <> 0 Then Col2 = Col2 - 10
    If C3 = 1 And Col3 <> 0 Then Col3 = Col3 - 10
    If C1 = 2 And Col1 <> 250 Then Col1 = Col1 + 10
    If C2 = 2 And Col2 <> 250 Then Col2 = Col2 + 10
    If C3 = 2 And Col3 <> 250 Then Col3 = Col3 + 10
    leds[x] = RGB(Col1, Col2, Col3)

Here is my Arduino setup:

    #include <FastLED.h>

    #define LED_COUNT 60
    #define LED_OUT       13
    #define BUTTON_IN     10
    #define ANALOG_INPUT  A9
    #define EXTRA_PIN_A    7
    #define EXTRA_PIN_B   11

    struct CRGB leds[LED_COUNT];

    void setup() {
      Serial.begin(57600);
      LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
      LEDS.show();
    }

    void loop() {
      //where to implement
    }

body:
Fairly simple. Understand what the basic code is trying to do and recreate that functionality in c.

In this case, it is looking for a set of conditions to trigger the generation of three random numbers which are then combined into a code for the run array.


body:
I think this should work fine:

    #include <FastLED.h>

    #define LED_COUNT     96
    #define LED_OUT       13
    #define BUTTON_IN     10
    #define ANALOG_INPUT  A9
    #define EXTRA_PIN_A    7
    #define EXTRA_PIN_B   11

    struct CRGB leds[LED_COUNT];

    void setup() {
      Serial.begin(57600);
      LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
      LEDS.show();
    }

    void colorLoop() {

      static int Col1;
      static int Col2;
      static int Col3;

      static int C1;
      static int C2;
      static int C3;

    if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the array
    C1 = random(1, 3);
    C2 = random(1, 3);
    C3 = random(1, 3);
    }

    if (((C1 == 1) && (Col1 != 0))) {
        Col1 = (Col1 - 10);
    }
    if (((C2 == 1) && (Col2 != 0))) {
        Col2 = (Col2 - 10);
    }
    if (((C3 == 1) && (Col3 != 0))) {
        Col3 = (Col3 - 10);
    }

    if (((C1 == 2) && (Col1 != 250))) {
        Col1 = (Col1 + 10);
    }
    if (((C2 == 2) && (Col2 != 250))) {
        Col2 = (Col2 + 10);
    }
    if (((C3 == 2) && (Col3 != 250))) {
        Col3 = (Col3 + 10);
    }

    for (uint8_t i = 0; i < LED_COUNT; i++) {
       leds[i] = CRGB(Col1, Col2, Col3);
      }
    delay(100);
    LEDS.show();
    }

    void loop() {
      colorLoop();
    }


message:
Arduino Micro disappears on osX 10.11.6

so I have an arduino micro, and it was working fine until the latest security update for OSX 10.11.6 now the port won't show up in the arduino IDE. This doesn't seem to be a problem with the Uno / Huzzah / Mega or Makey Makey, but the port shows up when the micro is booting up, then disappears when the boot is done.

Anyone else having this issue? I've googled and found something about signed ktels. I've also installed some extra FTDI drivers, but no dice. Cord is fine, and works w/ other devices.

Suggestions?

Thanks!

body: Found it. It was a weird timing thing, and I had to hit reset as the sketch was uploading. Seems to be fine now.


message:
Pointer problems using Adafruit MotorController

This may be a very simple problem but it has had me going round and round in circles, it is VERY similar to this [ <https://arduino.stackexchange.com/questions/28328/problem-with-wrapping-adafruit-motor-controller-function-calls-in-a-class>] question but try as I might I couldn't resolve the issue using this example. So I will include my code and hope that someone with more experience takes pity on me.
This code compiles with no errors but the motors don't start Like the linked question it all worked before it was separated into the individual files.

robot.ino:

    #include "E:\chhs2017\LegoRobotics\SketchesThatNeedToWork\RobotBase\RobotBase.h"

    RobotBase *base;

    void setup(){
  base = new RobotBase();
    }

    void loop(){
  base->moveRobotForward(base->HALF_SPEED);
    //  base->stopRobotAfter(1500);
    }

RobotBase.h:

    #ifndef ROBOTBASE_H
    #define ROBOTBASE_H

    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

 class RobotBase{

  public:
   const int MAX_SPEED = 255;
   const int THREE_QUARTER_SPEED = 190;
   const int HALF_SPEED = 127;
   const int QUARTER_SPEED = 90;
   const int MIN_SPEED = 30;

   RobotBase();

   void moveRobotForward(int inSpeed);
   void moveRobotBackward(int inSpeed);
   void moveRobotLeft(int inSpeed);
   void moveRobotRight(int inSpeed);
   void rotateRobotRight(int inSpeed);
   void rotateRobotLeft(int inSpeed);
   void stopRobotAfter(int time);

  protected:
   Adafruit_MotorShield AFMS;
   Adafruit_DCMotor *myMotorM1;
   Adafruit_DCMotor *myMotorM2;
   Adafruit_DCMotor *myMotorM3;
   Adafruit_DCMotor *myMotorM4;
 };
    #endif

RobotBase.ino:

    /*************************************************************
    * this is the robot base control class which is designed for a
    * four wheel robot construction using an Adafruit_DCMotor controller
    * and and arduino Uno
    **************************************************************/

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"
    #include "E:/chhs2017/LegoRobotics/SketchesThatNeedToWork/RobotBase/RobotBase.h"

    RobotBase::RobotBase()  {
     AFMS = Adafruit_MotorShield();
     myMotorM1 = AFMS.getMotor(1);
     myMotorM2 = AFMS.getMotor(2);
     myMotorM3 = AFMS.getMotor(3);
     myMotorM4 = AFMS.getMotor(4);
    }

    void RobotBase::stopRobotAfter(int time){
    delay(time);
    myMotorM1->run(RELEASE);
    myMotorM2->run(RELEASE);
    myMotorM3->run(RELEASE);
    myMotorM4->run(RELEASE);
 }

  void RobotBase::moveRobotForward(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(FORWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(FORWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(FORWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(FORWARD);
 }

 void RobotBase::moveRobotBackward(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(BACKWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(BACKWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(BACKWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(BACKWARD);
 }

 void RobotBase::moveRobotLeft(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(FORWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(BACKWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(FORWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(BACKWARD);
 }

 void RobotBase::moveRobotRight(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(BACKWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(FORWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(BACKWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(FORWARD);
 }

    void RobotBase::rotateRobotRight(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(FORWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(FORWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(BACKWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(BACKWARD);
    }

    void RobotBase::rotateRobotLeft(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(BACKWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(BACKWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(FORWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(FORWARD);
 }

Thanks in Advance!

body:
It may be the way you are initializing the motor shield object.
Try doing:

    RobotBase::RobotBase() : AFMS() {
         myMotorM1 = AFMS.getMotor(1);
         myMotorM2 = AFMS.getMotor(2);
         myMotorM3 = AFMS.getMotor(3);
         myMotorM4 = AFMS.getMotor(4);
    }


body:
Hey Guy's As I suspected it was actually an easy fix after leaving it alone for a couple of days came back with fresh eyes and saw the problem straight away. I had failed to start the MotorController board. So all that was needed was the begin function call `base->AFMS.begin();` in the setup of robot.ino, all working fine now.
Thanks again for your help.


message:
LinkNode D1 Serial stops working when using pinMode

The following code works. I get an output in the console every second of "Hello" and then the `analogValue` of the photoresistor.

    int greenLedPin = D1;
    int yellowLedPin = D2;
    int redLedPin = D3;

    int lightSensorPin = A0;
    int analogValue = 0;

    void setup() {
      Serial.begin(9600);
    //  pinMode(greenLedPin, OUTPUT);
    //  pinMode(yellowLedPin, OUTPUT);
    //  pinMode(redLedPin, OUTPUT);
    }

    void loop() {
      analogValue = analogRead(lightSensorPin);
      Serial.println("Hello.");
      Serial.println(analogValue);
      delay(1000);
    //  digitalWrite(greenLedPin, HIGH);
    //  digitalWrite(yellowLedPin, HIGH);
    //  digitalWrite(redLedPin, HIGH);
    }

Now as soon as I uncomment the `pinMode` commands nothing shows up on the console.

    int greenLedPin = D1;
    int yellowLedPin = D2;
    int redLedPin = D3;

    int lightSensorPin = A0;
    int analogValue = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(greenLedPin, OUTPUT);
      pinMode(yellowLedPin, OUTPUT);
      pinMode(redLedPin, OUTPUT);
    }

    void loop() {
      analogValue = analogRead(lightSensorPin);
      Serial.println("Hello.");
      Serial.println(analogValue);
      delay(1000);
    //  digitalWrite(greenLedPin, HIGH);
    //  digitalWrite(yellowLedPin, HIGH);
    //  digitalWrite(redLedPin, HIGH);
    }

Any idea what might be going on?

body:
Move **int greenLedPin = D1;** and **int redLedPin = D3;** to another pin, because D1 and D3 is Tx and Rx.

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

http://esp8266.github.io/Arduino/versions/2.0.0/doc/reference.html

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