body:
You can use a "Screw shield" between the motor shield and the Uno to make access to the unused pins easier.[![enter image description here][1]][1]

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


sender: user

message:
What is RSR 09TI chip?

There is a chip on Arduino UNO board which I can not find anything about. It is labeled RSR 09TI. It is placed near other power related components (see the image), but what is its purpose on the board?

[![RSR 09TI][1]][1]

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

sender: assistant

body:
I believe that is the dual op-amp that is used for both monitoring VIN to enable/disable the USB power, and as a buffer for the LED on pin 13.

In [the schematic](https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf) it's U1, and is an [LM358](http://www.ti.com/lit/ds/symlink/lm158-n.pdf).


message:
Using time function in arduino

how to get exact timestamp of a sensor reading and compare it with other sensor values in arduino?

Ex: Get the time of low reading of LDR and compare it

body:
As Majenko said you can use the millis() keyword.

Unless millis is not accurate enough. In that case you can use micros(), but this overflows every 70s if I'm correct, but you can offset it against millis().

If you need to compare two values, what you can do is:

   - get millis()
   - get micros()
   - read sensor data (optimize if needed)
   - get micros()

Average the difference of the micros, and add it to millis, and you have the average time for the sensor data readings.

Of course if it doesn't matter that all sensor data is read at approximately the same time, you can use millis() for each sensor data reading and work with those values.


message:
How to re-solder the resistor in order to reprogram the Atmega8U2

As I see here I need to reprogram the ATMEGA8u2: https://www.arduino.cc/en/Hacking/DFUProgramming8U2 I need to solder a 10k resistor into a specific place.

In a previous attempt I did that and resulted the following marks:

[![Previous reprogramming attempt][1]][1]

So How I can resolder the resistor in order to reprogram the atmega8u2?

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

body:
That pad connects to the same place as the circuit used for resetting the ATMega328P chip - that is, pin D7 on the ATMega8U2.

It just pulls the pin PD7 down to ground with more "force" than the internal pullup of the pin itself.

You can attach that resistor to anywhere along that line, and probably the most convenient place would be to the ATMega16U2 side of capacitor C5.

That capacitor has one end linked to the RESET pin on the main Arduino header, so you can connect a DMM in continuity test to that pin and "buzz out" each capacitor until you find the one point where it beeps (I think it's one that's right next to "Reset EN").

*Carefully* solder your resistor to the *opposite* side of the capacitor to the side that beeps (the side nearest the ATMega8U2 chip, probably), and connect the other end of the resistor to GND on one of the main headers.

By the way - get yourself a flux pen and apply flux to where you are soldering *before* you start soldering. It should help you avoid these kind of problems in the future. Also get a proper temperature controlled soldering iron (I use 350C for mine most of the time) and some solder wick to help recover from solder messes.  All part of the standard EE's toolkit.


body:
Looks like you ripped a pad off. To prevent that in the future, try using more flux and dropping the temp (Max around 320*C/610*F). The iron shouldn't be in contact with the board for more than about 3 seconds. No force should be necessary to remove components.

Not to worry though. Common beginner's mistake and not too hard to fix.

To prep this for repair:

 - Gently clean the area up with 91% isopropyl alcohol and cotton swabs.
 - Carefully scrape away the solder mask (blue paint) on what's left of the copper trace all the way back to the via (little hole). Try to remove all the solder mask from the via. Straighten and flatten the pulled up trace.
 - Clean, flux, and tin (apply as thin layer of solder) to the trace and remaining pad. Filling in the via is OK as it will give better surface area to attach the repair.
 - Flux and solder the resistor to the remaining pad to keep it in place and properly aligned for the repair.

To repair the damage:

 - We need to bridge the gap created by the damaged pad. A globby solder bridge may work, but wire is much better.
 - Find a piece of thin gauge solid core wire (30-22AWG. Some 24AWG from an ethernet cable would do fine).
 - Orient the wire so that it's directly over the remaining trace and also making contact with that end of the resistor.
 - You can trim it to size now or after soldering. It may be easier to keep in place if you trim it after soldering as long as you have some fine flush cut pliers. Either way, leave enough that it covers the entire cleaned and tinned portion of the trace.
 - Flux and solder the wire to both the resistor and trace. This will complete the circuit.
 - Clean again with alcohol. Let dry. Test the board.

Give [this Adafruit article](https://learn.adafruit.com/adafruit-guide-excellent-soldering/common-problems) a read. I've got extensive professional soldering training and endorse it fully as the best beginners soldering guide I've found.


message:
Arduino UNO reprogram the MEGA8u2 using external programmer

As they say in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 you need to solder a 10k resistor in order to reprogram/reset the MEGA8u2 chip on Arduino UNO but sometimes you may lack the needed tools.

Is there a way to reprogram the MEGA8u2 using an external programmer or an another arduino as a programmer?

My idea behind this is to use the ISP LAYOUT for ATMEGA8U2 in order to load the correct bootloader:

[![Possible pin layout][1]][1]

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

body:
Sure you can. Solder in a 6 pin header and you can program the ATMega8U2 using any Atmel hardware programmer. It's just a standard MCU, after all.  I'm not sure how the DFU side of things works - whether it's built into the chip in ROM or not1, but if it's just a bootloader in flash your programming may wipe it out stopping DFU from working in future. Not a problem if you can't get into DFU mode anyway.

----

1: The DFU is firmware stored in the "boot" region of the flash. As long as you don't erase or overwrite that region of the flash DFU will still function in future. Of course, you can also re-install the DFU firmware at any time you like.


message:
Arduino UNO(master read) + NANO(slave write) i2c buttons+stepper

First of all, I'm new to arduino. Check the EDIT line below the two codes.

I have connected motor shield to arduino uno. Connection between the two arduinos are A5 to A5, A4 to A4, 5V to 5V and GND to GND. I have a stepper connected to UNO, and a button connected to nano.

**EDIT5:** *I deleted the messy previous codes, the question was answered.*
However, I cant get the steppers to rotate(they only vibrate). Any advice is appreciated. The code right now is:

Master

    #include <Wire.h>
    #include <AFMotor.h>
    //define steppers
    AF_Stepper motor1(48, 1);
    AF_Stepper motor2(48, 2);

    //define variables
    int x = 0;
    int y = 0;

    void setup()
    {
      Wire.begin(5); //begin i2c communication
      Wire.onReceive(receiveEvent);
      motor1.setSpeed(10);  // 10 rpm
      motor2.setSpeed(10);  // 10 rpm

      motor1.release();
      motor2.release();
      delay(1000);
    }

    void loop()
    {
      delay(500); // wait 0.5 second
    }

    void receiveEvent(int howMany)
    {
        //read x,y from slave
        x = Wire.read();
        y = Wire.read();

        if (x == 1) //stepper1 rotate forward
        {
          motor1.step(100, FORWARD, SINGLE);
        }
        else if (x == 2) //stepper1 rotate backward
        {
          motor1.step(100, BACKWARD, SINGLE);
        }
         else if (y == 1) //stepper2 rotate forward
        {
          motor2.step(100, BACKWARD, SINGLE);
        }
         else if (y == 2) //stepper2 rotate backward
        {
          motor2.step(100, BACKWARD, SINGLE);
        }
    }

Slave

    #include <Wire.h>

    //define buttons
    const int button1 = 2;
    const int button2 = 3;
    const int button3 = 4;
    const int button4 = 5;

    //define state of buttons
    int buttonState1 = 0;
    int buttonState2 = 0;
    int buttonState3 = 0;
    int buttonState4 = 0;

    //define variables
    int x = 0;
    int y = 0;

    void setup()
    {
       //start i2c communication
       Wire.begin();
    }

    void loop()
    {
      //read state of buttons
      buttonState1 = digitalRead(button1);
      buttonState2 = digitalRead(button2);
      buttonState3 = digitalRead(button3);
      buttonState4 = digitalRead(button4);

        //if button1 is pressed,send x to master
        if(buttonState1 == HIGH){
          x = 1;
          Wire.beginTransmission(5);
          Wire.write(x);
          Wire.endTransmission();
        }
        //if button2 is pressed,send x to master
        else if(buttonState2 == HIGH)
        {
          x = 2;
          Wire.beginTransmission(5);
          Wire.write(x);
          Wire.endTransmission();
        }
        //if button3 is pressed,send y to master
        if(buttonState3 == HIGH){
          y = 1;
          Wire.beginTransmission(5);
          Wire.write(y);
          Wire.endTransmission();
        }
        //if button4 is pressed,send y to master
        else if(buttonState4 == HIGH)
        {
          y = 2;
          Wire.beginTransmission(5);
          Wire.write(y);
          Wire.endTransmission();
        }
    }

body:
There are many ways to do this. The master could be the central unit which makes all the decisions, or the slave could preprocess the information.

It is best to start with a single byte to make it work. But I have made examples for two bytes anyway.

The next examples requests two buttons via i2c. You can change the HIGH and LOW into an integer value, but this is a start to make it work.

**Master (without checking)**

    void loop()
    {
      Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
      int button1 = Wire.read();
      int button2 = Wire.read();

      Serial.print("button1=");
      Serial.println(button1 == HIGH ? "HIGH" : "LOW");

      Serial.print("button2=");
      Serial.println(button2 == HIGH ? "HIGH" : "LOW");

      // Some delay is needed, to prevent a 100% i2c bus load.
      // Perhaps 1 ms is enough, now 500 ms for testing.
      delay(500);
    }

**Master (with checking)**

    void loop()
    {
      Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
      if(Wire.available() == 2)   // are 2 bytes received ?
      {
        int button1 = Wire.read();
        int button2 = Wire.read();

        Serial.print("button1=");
        Serial.println(button1 == HIGH ? "HIGH" : "LOW");

        Serial.print("button2=");
        Serial.println(button2 == HIGH ? "HIGH" : "LOW");
      }
      else
      {
        Serial.println("The slave was not found");
      }

      // Some delay is needed, to prevent a 100% i2c bus load.
      // Perhaps 1 ms is enough, now 500 ms for testing.
      delay(500);
    }

**Slave (very simple)**

    void requestEvent()
    {
      buttonState1 = digitalRead(button1);
      buttonState2 = digitalRead(button2);
      Wire.write( (byte) buttonState1);
      Wire.write( (byte) buttonState2);
    }

**Slave (advanced, update button state in the loop)**

    #include <Wire.h>

    const int button1Pin = 2;
    const int button2Pin = 3;

    // Variables that are used in a interrupt and also outside
    // that interrupt must be declared as volatile.
    // Then the compiler knows that they can change at any moment.
    volatile byte buttonState1;
    volatile byte buttonState2;

    void setup()
    {
      pinMode(button1Pin,INPUT);
      pinMode(button2Pin,INPUT);
      Wire.begin(8);                // join i2c bus with address #8
      Wire.onRequest(requestEvent); // register event
    }

    void loop()
    {
      // keep the variables updated with the latest information.
      buttonState1 = (byte) digitalRead(button1Pin);
      buttonState2 = (byte) digitalRead(button2Pin);
    }

    // function that executes whenever data is requested by master
    // this function is registered as an event, see setup()
    void requestEvent()
    {
      // send the two bytes.
      Wire.write(buttonState1);
      Wire.write(buttonState2);
    }


message:
analog read only once a time

I was working on a school project in where i need to analog read form A0 and test if my value is bigger than some boundary (500 for example) to return 0 or 1
well with a simple code in an infinity loop
this will keep returning 0000000 and 1111111 for infinity
but need 1 only once when my analog value passes from 900 to 300 for example and I dont need once when It stays at 300.
and the same problem for 0 : I need 0 only once when it passes from 300 to 900 and not 0 from staying at 900
thanks for help in advance

body:
Store the current read value AND the previous value and check if a border has been crossed.

E.g.

    if Previous value < 500 AND current value >= 500
       Going from 0 to 1 -> return/send 1
    else if Previous value >= 500 AND current value < 500
       Going from 1 to 0 -> return/send 0

However, to make it more complicated, you might have debouncing effects, e.g. what if the value moves for some time around 500 to go to 200... It will still result in possibly many 0 and 1 boundary changes.

You can fix this easily by using two different value: by checking going lower < 490 and going higher > 510 (or any other appropriate value. Or use a debounce mechanism where it should be below or above the 500 value for a minimum (but short) amount of time.


body:
What you are talking about is *threshold with hysteresis*.  It's basically how the digital inputs work using *schmit triggers*.

    +------+ 1023
    | HIGH |
    +------+ 900
    | DEAD |
    +------+ 300
    | LOW  |
    +------+ 0

What you want to do needs to be done in two distinct sections:

1. Detect the incoming analog level, and
2. Control and record the status.

The first part is simple enough:

    int val = analogRead(0);
    if (val > 900) {
        // High
    } else if (val < 300) {
        // Low
    }

With that you have two blocks of code that are valid for the two bands you are interested in.  That is effectively like a button now - you have a "HIGH" and a "LOW" signal, just like `digitalRead()` gives you for a digital input.  Now you just need to couple that with some standard button toggling code.  That is - only change the status if the status actually should change.  And that's simple enough.  For example:

    if (newStatus != oldStatus) {
        oldStatus = newStatus;
        // Do something just once
    }

To expand that concept out, you get:

    static bool enabled = false; // This is the saved status

    int val = analogRead(0); // The incoming value

    if (val > 900) { // A HIGH signal.
        if (!enabled) { // It's not already recorded as HIGH
            enabled = true; // Record it as a HIGH
            Serial.println("1");
        }
    } else if (val < 300) { // A LOW signal
        if (enabled) { // It's currently HIGH, not LOW...
            enabled = false;
            Serial.println("0");
        }
    }

And there you have it.  If it goes HIGH and it's not recorded as HIGH then it's a *new* HIGH.  If it goes low and it's not recorded as LOW then it's a *new* LOW.


message:
Reading data from ThingSpeak via Arduino Uno+ESP8266

I am integrating thingspeak and arduino plus Esp8266 mean making a simple project which contain my android app to update the thingspeak channel and then want to read the data of that channel via arduino uno. the android parts works fine but at the arduino side i got stuck and unable to read the channel data via esp8266(attached to my arduino uno).
Here is my code.any help would be appreciated.
it shows in serial monitor connecting to thingspeak.com and show nothing next.

    #include "WiFiEsp.h"

    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(2,3); // RX, TX
    #endif

    char ssid[] = "M T G";            // your network SSID (name)
    char pass[] = "androidGUII";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    char server[] = "arduino.cc";

    // Initialize the Ethernet client object
    WiFiEspClient client;
    static const char* host = "api.thingspeak.com";
    static const char* apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
    void setup()
    {
      // initialize serial for debugging
      Serial.begin(115200);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);

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

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }
      // you're connected now, so print out the data
      Serial.println("You're connected to the network");
      printWifiStatus();
      Serial.println();
    }

    void loop()
    {
          const int httpPort = 80;
        if (!client.connect(host, httpPort)) {
            Serial.println("connection failed");
            return;
        }
      client.println("GET /channels/xxxxxxx/feeds.json?api_key=xxxxxxxxxx&results=2 HTTP/1.1");
      while (client.available() == 0);  // wait till something comes in; you may want to add a timeout here
      Serial.println(client.read());
      client.stop();  // close socket
      delay(10000);
    }
    void printWifiStatus()
    {
      // print the SSID of the network you're attached to
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

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

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

body:
HTTP GET request needs to end with an empty line and HTTP 1.1 requires a `Host` header.

Add an empty line and eiher change the HTTP version to 1.0

    client.print("GET /channels/421932/feeds.json?api_key=");
    client.print(apiKey);
    client.println("&results=2 HTTP/1.0");
    client.println(); // empty line

or add the `Host` header

    client.print("GET /channels/421932/feeds.json?api_key=");
    client.print(apiKey);
    client.println("&results=2 HTTP/1.1");
    client.print("Host:");
    client.println(host);
    client.println(); // empty line


message:
problem using #define to substitute functions

This might be more a general programming question, but I am using the Arduino compiler, and I've created my own ISR driven version of millis(), which I simply call myMillis(). So let's say I'd like to use this addition to a working project. Rather than do a global search and replace, I got the idea to simply put this define near the top of the program...

    #define millis myMillis

    uint32_t myMillis()
      { // my code ...
      }

So when I compile, every instance of millis() does indeed compile as if I did a global search and replace. I like that, because it means I don't have to make the change permanent, and can easily comment out my defines to compare program operation.

My question is, if I do as I just explained, what if, for whatever reason, there is some place within the project where I actually WANT to call the original version. A simple example might be if I wanted to occasionally output a message via serial.println(), comparing the returned value of millis() and myMillis(). I think there is a way to specify such an exception to my #define MACRO, but I'm not sure how.

body:
There is no way to suppress define substitution. You could use #undef and then #define again in required section.

Name the define MILLIS and use this name in code, except where you want the original millis() function.


body:
Not related to your problem, but it is worth noting that your define only exists in your sketch (known as a *translation unit*). Other translation units (the core, libraries, etc) never get to see it.

To make everything see  it youould have to place the define in a location that everything sees, such as Arduino.h in the core, for it to affect anything other than your sketch.

Once you have replaced millis there is no way to unreplace it. You could, though, make use of the scope limiting I talk about above to make a separate translation unit (maybe a small library) with a single function in it that calls millis. As long as that never sees the define it will still see the original function name.


message:
Import library in Arduino IDE

I'm trying to use an HX711 load cell amplifier with my NodeMCU 0.9. I've found [this library][1] on Github and, following [this guide][2], I tried to use it.

Unfortunately I keep getting this error:

    sketch/HX711.cpp:2:19: fatal error: HX711.h: No such file or directory
     #include <HX711.h>

I suppose that there's some problem with C++ but I don't understand what is.

Here's the initial code:

    #include <ESP8266WiFi.h>
    #include "HX711.h"

Here's the folder structure:

    Samples
      |-- nodemcu_test
            |--nodemcu_test.ino
            |--HX711.cpp
            |--HX711.h

[*Original question*][3]

  [1]: https://github.com/bogde/HX711
  [2]: https://arduino.stackexchange.com/questions/13017/how-to-add-h-file-in-library
  [3]: https://iot.stackexchange.com/questions/2734/import-library-in-arduino-ide?noredirect=1#comment5470_2734

body:
You want to import a **library** not an example.

    Arduino Folder
     |-- libraries
      |--HX711
       |--HX711.cpp
       |--HX711.h

ex:

    C:\Program Files (x86)\arduino-1.8.5-windows\arduino-1.8.5\libraries\HX711

Put the files in a folder called HX711 to have everything nice and tidy.

I use the standalone version of arduino ide, if you have it installed I suspect the folder would be under

    My Documents\Arduino\libraries\

According to the [documentation][1].

You should put the nodemcu_test.ino in your sketchbook folder as I would generally avoid putting non-library files in the libraries folder. If you do want to keep the _examples_ for a specific library close to the library create a subfolder:

    Arduino Folder
     |-- libraries
      |--HX711
       |-- examples
        |--nodemcu_test.ino
       |--HX711.cpp
       |--HX711.h

As Juraj pointed out, this has the additional advantage of them being accessable in the examples menu.

If you want the libraries close to your sketch you are actually working on, follow the guide and put the library files in your sketchbook folder for your project. I would not advise for the following reasons:

I read that in newer IDEs 1.8.X you would need to put the files in a `/src/subfolder`. For me it did work without that, but the main caveat remained:

    #include <HX711.h>

means to look in the library folder as mentioned above.

If you want to put the files somewhere else, you have to use

    #include "HX711.h"

and specify the path (or in this example it was located where my .ino was). But now I also need to change

    #include <HX711.h>

to

    #include "HX711.h"

in the HX711.cpp file. What a hassle!

So my takeaway message would be: Stick with `Arduino\libraries\`.

  [1]: https://www.arduino.cc/en/hacking/libraries


message:
Steppers only vibrate, not rotate with I2C

The goal of my project is to be able to control two steppers with 4 buttons. Steppers are connected to Adafruit Motor shield(the older one) which is stacked on Arduino UNO, buttons are connected to Arduino NANO. I'm using I2C between the two Arduinos. However, if I push a button, the steppers won't rotate, only vibrate, but if I'm using only Arduino UNO with the motor shield stacked on it, button connected directly to the motor shield, it's working well.
Arduino UNO is Master Reader, while NANO is Slave Writer. There is a [fritzing image of the circuit.][1]
I don't know where's the problem, if it's in the circuit, if it's because of my battery(i bought it like 10 minutes ago) or the code. Any help is apreciated.

Master code:

    #include <Wire.h>
    #include <AFMotor.h>
    //define steppers
    AF_Stepper motor1(48, 2);
    AF_Stepper motor2(48, 1);

    //define variables
    int x = 0;
    int y = 0;

    void setup()
    {
      Wire.begin(5); //begin i2c communication
      Wire.onReceive(receiveEvent);
      motor1.setSpeed(200);  // 10 rpm
      motor2.setSpeed(200);  // 10 rpm

      motor1.release();
      motor2.release();
      delay(1000);
    }

    void loop()
    {
      delay(500); // wait 0.5 second
    }

    void receiveEvent(int howMany)
    {
        //read x,y from slave
        x = Wire.read();
        y = Wire.read();

        if (x == 1) //stepper1 rotate forward
        {
          motor1.step(100, FORWARD, SINGLE);
        }
        else if (x == 2) //stepper1 rotate backward
        {
          motor1.step(100, BACKWARD, SINGLE);
        }
         else if (y == 1) //stepper2 rotate forward
        {
          motor2.step(100, BACKWARD, SINGLE);
        }
         else if (y == 2) //stepper2 rotate backward
        {
          motor2.step(100, BACKWARD, SINGLE);
        }
    }

Slave code:

    #include <Wire.h>

    //define buttons
    const int button1 = 2;
    const int button2 = 3;
    const int button3 = 8;
    const int button4 = 7;

    //define state of buttons
    int buttonState1 = 0;
    int buttonState2 = 0;
    int buttonState3 = 0;
    int buttonState4 = 0;

    //define variables
    int x = 0;
    int y = 0;

    void setup()
    {
       //start i2c communication
       Wire.begin();
    }

    void loop()
    {
      //read state of buttons
      buttonState1 = digitalRead(button1);
      buttonState2 = digitalRead(button2);
      buttonState3 = digitalRead(button3);
      buttonState4 = digitalRead(button4);

        //if button1 is pressed,send x to master
        if(buttonState1 == HIGH){
          x = 1;
          Wire.beginTransmission(5);
          Wire.write(x);
          Wire.endTransmission();
        }
        //if button2 is pressed,send x to master
        else if(buttonState2 == HIGH)
        {
          x = 2;
          Wire.beginTransmission(5);
          Wire.write(x);
          Wire.endTransmission();
        }
        //if button3 is pressed,send y to master
        if(buttonState3 == HIGH){
          y = 1;
          Wire.beginTransmission(5);
          Wire.write(y);
          Wire.endTransmission();
        }
        //if button4 is pressed,send y to master
        else if(buttonState4 == HIGH)
        {
          y = 2;
          Wire.beginTransmission(5);
          Wire.write(y);
          Wire.endTransmission();
        }
    }

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

body:
In **both** master and slave, you have `x` and `y` declared in the broadest scope possible. Different devices, shouldn't matter. But `x` and `y` usual mean coordinates, which is not what you are trying to say - properly named variables help with understanding and maintenance.

I think your biggest issue, and one that confuses your attempts to debug, is the underlying logic.

 - You have 4 independent buttons, but prioritise one button over the
   other. What happens if both buttons are pressed together?
 - You have 2 independent motors but prioritise one after the other.
 - Your slave uses repeating code.
 - You use your slave as both a writer and  decider. In this case, your
   writer is making the decisions over which motor to move and which
   direction.
 - Your master only makes one move at a time - but you have two motors and 4 buttons, so you should be able to move both motors in one loop.
 - Your handler expects the number of bytes to be read but you don't use that to control your reading.
 - Your consecutive reading does not differentiate on where the data comes from. `x` could be filled with any of the button presses, and so could `y`.
 - If the event handler is doing the work, why have a blocking `delay` in the code?

Effectively, you are taking a random read and expecting the device to do something deterministic. Hence your jittering.

To help you debug your device, you can first clean up your code.

 - reconfigure your slave to send a single response each loop. You only need 4 bits, where each bit represents whether buttons 1-4 are pressed. Only 1 variable to be written.
 - Use your master to decipher the input. This is where you can put the safety in (e.g. if both 1&2 are pressed/HIGH then ignore). This also reduces the possibility that your code is sending a forward then backwards signal.
 - Use your master to determine how many bytes have to be read and use this properly.

You will find your code cleaner, easier to read and easier to debug. Perhaps you will also see a way to directly slave the NANO to the UNO without i2C in the middle, simplifying your set up even more.

EDIT (additional information):

 - You can use the built in functions (see [Arduino function reference][1] under "Bits and Bytes") such as BitWrite/BitSet/BitClear and BitRead to set/clear the relevant bits on the variable you create (e.g. `Byte ButtonStates`). Note the use of `Byte` instead of `Int`
 - You can then use the slave to write the information and the master to read the information (`Wire.write` and `Wire.read`), you then know that each byte is complete and reflects what you intend.

  [1]: https://www.arduino.cc/reference/en/#functions


message:
nodemcu EEPROM corrupting

#### Platform

- Hardware:     [nodemcu amica ESP8266MOD]
- Core Version:   [nodemcu-master-21-modules-2018-03-17-17-09-10]
- Development Env:  [Arduino IDE|]
- Operating System:  [Windows|]

### Settings in IDE

- Module:     |Nodemcu]
- Flash Mode:   [qio|dio|other]?
- Flash Size:   [1MB]
- lwip Variant:   [v2 Lower Memory]
- Reset Method:  [nodemcu]
- Flash Frequency: [40Mhz]
- CPU Frequency:  [80Mhz]
- Upload Using:  [SERIAL]
- Upload Speed:   [115200] (serial upload only)

### Problem Description
hi, in my code i did a simple thing. i get the data from jSon object and write them to the EEPROM. once i write them to eeprom i can read the relevant data from that writing function ``handleFinishWizard()``  (i have put reading functions here n there to find where is the problem) .When i write data and finish it i can read the data.once its over when the program moved to the loop, eeprom data are corrupted and it doesnt display anything. i attached the output in debug message. whats the problem here?

### [MCVE] Sketch
code in github [CODE LINK](https://github.com/namila007/mediot-hardware/blob/dev_print/main/main.ino)

### Debug Messages

    ```
    add 1
    aid 1
    station: c0:ee:fb:ed:3b:0e join, AID = 1
    value on EEPROM ADD:
    OnePlus 3T
    test123@abc
    test.com

    value on EEPROM ADD:
    OnePlus 3T
    test123@abc
    test.com

    value on EEPROM ADD:
    OnePlus 3T
    test123@abc
    test.com

    value on EEPROM ADD:
    OnePlus 3T
    test123@abc
    test.com

    value on EEPROM ADD:
    OnePlus 3T
    test123@abc
    test.com

    value on EEPROM saveBefore:
    ⸮?

    ⸮?

    value on EEPROM saveBefore:
    ⸮?

    ⸮?

    value on EEPROM saveBefore:
    ⸮?

    ⸮?

    value on EEPROM saveBefore:
    ⸮?

    ⸮?

    value on EEPROM saveBefore:
    ⸮?

    ⸮?

    value on EEPROM save:

    value on EEPROM save:

    value on EEPROM save:

```

body:
Look at this code:

    void setupCredentials(const char *ssid, const char *password,
                          const char *link) {
      int addr = 0;

      EEPROM.begin(512);
      addr = sizeof(int);
      EEPROM.put(addr, ssid);
      delay(10);
      addr += sizeof(st_ssid);
      EEPROM.put(addr, password);
      delay(10);
      addr += sizeof(st_password);
      EEPROM.put(addr, link);
      delay(10);
      EEPROM.commit();

You are calling `EEPROM.put(addr, ssid)` with `ssid` being a `const char*`. A pointer to some memory location. Notice that you only give it a start address and a pointer, not the length of your data.

Have a look at the implementation of the [`put` function][1]:

      template<typename T>
      const T &put(int const address, const T &t) {
        if (address < 0 || address + sizeof(T) > _size)
          return t;
        if (memcmp(_data + address, (const uint8_t*)&t, sizeof(T)) != 0) {
          _dirty = true;
          memcpy(_data + address, (const uint8_t*)&t, sizeof(T));
        }

        return t;
    }

What it essentially does is copy your given object `const T &t` into its internal `_data `buffer. The size of the data saved is determined by `sizeof(T)`.

In your example `t = ssid`, `T = const char*` and `sizeof(T) = sizeof(char*) = 4` and `addr= sizeof(int) = 4`.

What you are doing here is not to save the string that `ssid` points to in memory but the **pointer value** of `ssid`. After you leave the function the data pointed to by `ssid` will be de-allocated at some point and the memory will be overwritten by something else.

When you do a print directly in the function you are retrieving the pointer value of `ssid` 3 times and print that value. At that point the data is still there and everything is okay. Then if you print it again after leaving the function you get garbage because the local data is gone after the function call `handleSetup` is left.

What you want here is to not use a `const char*` in your second argument to a  `EEPROM.put(address, object)` call but a `char [20]`, for example. This way the `put` will work correctly.

Example:

    // Assume EEPROM.begin() was called already
    void EEPROM_SaveSSID(const int address, const char* str) {
     char ssid_buf[20];
     strncpy(ssid_buf, sizeof(ssid_buf) - 1, str);
     EEPROM.put<char[20]>(address, ssid_buf[0]); //sizeof(ssid_buf) = 20
     //don't forget to EEPROM.commit(); and EEPROM.end()
    }

    /* read SSID into a pre-allocated buffer */
    void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
     EEPROM.get(address, ssid_buf); //sizeof(ssid_buf) = 20
    }

If you do not like the semantics of these C++-templates auto-determining the size of read/write calls, you can always use bytewise `read` and `write` calls:

    void EEPROM_SaveSSID(const int address, const char* str) {
     for(size_t i = 0; i < strlen(str)) {
      EEPROM.write((int)(address + i), str[i]);
     }
    }

    /* always read 20 bytes starting from given address into buffer */
    void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
     for(size_t i = 0; i < sizeof(ssid_buf); i++) {
      ssid_buf[i] = EEPROM.read((int)(address + i));
     }
    }

See "EEPROM" (actually: Flash-emulated EEPROM) implementation code at https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM.

  [1]: https://github.com/esp8266/Arduino/blob/master/libraries/EEPROM/EEPROM.h


message:
Arduino resets variable every loop

im new to arduino and have a problem currently with my project on sun tracking. The problem is that every loop it resets my variable back to 1 or whatever i set it. I have 4 photodiodes working properly but using only 2 on one axis. Code example:

    void loop(){
        int stop1 = 1;
        senzor read1  //this is just code example
        senzor read2
        senzor read3
        senzor read4
        if (senzor1>senzor2){stop1=senzor1 - senzor2}
        if (senzor2>senzor1){stop1= senzor2 - senzor1}
        if (stop<5){stop motors}
    }

this is simple example code and the problem is that it doesn't stop, it keeps looking for light (successfuly) and doesn't stop. Sorry for bad English if any and thanky in advance.

body:
If you mean the variable stop1, it's true every loop it's set to 1.

If you don't want this, make it global, set it in setup (and change in loop when needed).

E.g.

    int stop1 = 0;

    void setup()
    {
        stop1 = 1;
    }

    void loop()
    {
        // Use stop and/or change it
    }


message:
4x4 matrix keypad - Multiple inputs cause extra readings

I have the following matrix keypad - [![enter image description here][1]][1]

I am using this as a sort of controller with my Arduino (Mega2560) but I can't get real multiple inputs to work. I am able to have say two individual keys pressed at a time but after that they overlap with eachother. (Using the Keypad library also).

Here is an illustration of the issue:

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

If I press the 3 blue buttons and use the getKeys function it thinks that the red one is also pressed. This works when any three or more buttons are pressed that produce a square.

  [1]: https://i.stack.imgur.com/NBAWw.jpg
  [2]: https://i.stack.imgur.com/GWR52.jpg

body:
I have a [post about keypad matrices](http://www.gammon.com.au/forum/?id=14175) which discusses this issue. The issue with keypads is, that if you don't install diodes, if three keys are pressed the current finds its way around those three keys and it looks like a fourth is pressed.

[![Ghosting issue][1]][1]

If you install diodes, like this, the issue goes away:

[![Keypad with diodes][2]][2]

It can be a little tedious to do, but I managed it the other day with surface mounted diodes.

[![Keypad with surface-mounted diodes][3]][3]

The above board is different from yours, mine is one with soft switches which I could lift off to get at the board.

Yours looks like it might be almost impossible to cut the tracks and install the diodes. Without them you can press two keys at once without issues. Perhaps that is enough. :)

  [1]: https://i.stack.imgur.com/oKznR.png
  [2]: https://i.stack.imgur.com/7GbUd.png
  [3]: https://i.stack.imgur.com/WBblL.jpg


message:
RF transmitter with external 8-12v power not working properly

So I have this pair of transmitter and receiver
[![enter image description here][1]][1]

RPI is powered by USB from laptop
Transmitter is connected to Attiny85 being interfaced from RPI at 3v3
Receiver is connected to Arduino at 5v

If I have transmitter VCC connected to RPI 5v, data pin to Attiny85 running at 3.3v and all of them having same ground - all works fine, but obviously range is not great.
At this point same ground connects: transmitter, Attiny, RPI.

So I've tried using external power supply for transmitter.

I have power brick with DC output running at 12v
[![enter image description here][2]][2]
DC output positive goes to VCC, negative to common ground.
At this point same ground connects: transmitter, Attiny, RPI, power brick.
This doesn't work at all, receive nothing.

I have YwRobot breadboard power, which is broken and now supplies 8v on 5v pins
[![enter image description here][3]][3]

I've connected same power brick DC output to YwRobot DC in, positive 5v from board (actually pushing 8v) goes to VCC, negative from board goes to common ground.
At this point same ground connects: transmitter, Attiny, RPI, YwRobot.
This setup transmits data some times, still worse results than connecting VCC to RPI 5v.

Am I missing something? Does external power supply has to be something specific? I've thought as long as grounds are connected any power supply can be used on transmitter.

**Update:**
This 433MHz transmitter with PCB integrated antenna from my thermostat (powered by 2xAA) has no problem penetrating 3 walls and floor in my house. Sorry for my ignorance, but I need to achieve similar form factor and performance. 2.4GHz modules also require a lot of pins limiting what else can be done with Attiny85.
[![enter image description here][4]][4]

**Update:**
Attiny is using [manchester][5] and software serial (part of Arduino IDE) on [attiny core][6].
RPI is using [serial][7], not sure which version, installed using `sudo apt-get install python-serial`

  [1]: https://i.stack.imgur.com/QKLDs.png
  [2]: https://i.stack.imgur.com/MDp5f.png
  [3]: https://i.stack.imgur.com/vnnr0.png
  [4]: https://i.stack.imgur.com/7SZsC.jpg
  [5]: https://github.com/mchr3k/arduino-libs-manchester
  [6]: https://github.com/damellis/attiny
  [7]: https://pythonhosted.org/pyserial/

body:
Those 433MHz modules are tricky. I got the best results with 3V3 on the receiver, and 5V on transmitter. You should add an external antenna.

While it would be prudent to remove the little loop antenna, you don’t need to. I got an okay signal at 25 meters with line-of-sight. Metal, or brick will block the signal even at a meter or so - there’s no penetration. Consider a 2.4GHz module for high penetration at low range, or a LoRa module for high range (up to 10km).

A 433MHz antenna I’ve used with good results (can be cut for any frequency really)
[![Ant1][1]][1]

Use the same material for both antenna and radials - copper is good - and optionally stiffen the radials with bicycle spokes on the _inside_ ... make sure there is no electrical contact between the radials and the spokes; tape or heatshrink tube. I found coax cable to suck hard for this application, so I recommend using shielded headphone wire or something similar... just connect the shield to 0V/GND.

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

As for your breakout power module, I’ve had the same issue. Those modules are dangerous, avoid them. Use 7805 and LM1117 instead. Or just one 5V source (your powerbank?) and a TO-92 LM317 set to 3V3 output (max 100mA). Tiny 3V step-down converters like this can supply 800mA.
https://m.banggood.com/5V-To-3_3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-800MA-p-933674.html
( you can find them a lot cheaper )


message:
Arduino cannot sync

I have seen many of these problems and followed all the instructions i can find, i made sure the com was the correct one, i made sure th e drivers were installed. I cannot upload my sketch...anyone else have any ideas, ive been working on this forever trying to figure it out...

    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load
    --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.elf" "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.eep" "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.elf" "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.hex" Multiple libraries were found for "LiquidCrystal.h"  Used: C:\Users\reneg\Documents\Arduino\libraries\LiquidCrystal  Not used: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal Using library LiquidCrystal at version 1.0.5 in folder: C:\Users\reneg\Documents\Arduino\libraries\LiquidCrystal  Sketch uses 1900 bytes (5%) of program storage space. Maximum is 32256 bytes. Global variables use 59 bytes (2%) of dynamic memory, leaving 1989 bytes for local variables. Maximum is 2048 bytes. C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p
    -carduino -PCOM1 -b115200 -D -Uflash:w:C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM1
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x24

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body: Ok figured it out.......had to change the board type/////


message:
Can i send sensor data from arduino to cloud without sending it via PC

I am trying to build a GPS tracker. I need to send the data from GPS sensor on the arduino uno board to cloud directly i.e. without sending it via PC or mobile.
Is it possible and if yes, HOW?

body:
To connect to the cloud directly while the tracker is on the move, you'll need to use GSM & GPRS technology, ie. a SIM card to make a 3G/4G connection to the Internet. GSM gets you connected, GPRS does the Internet traffic. Using WiFi to connect to a router won't work since you'll soon get too far from the router.

I suggest initially investigating the SIM908 and SIM800L (there are others).

Here are 2 projects which both use the SIM908 (GSM, GPRS **AND** GPS):

[Geolocation Tracker (GPRS + GPS) with SIM908 over Arduino and Raspberry Pi][1]

[Where is my car? Realtime GPS+GPRS Tracking of Vehicles Using Arduino][2]

The cheaper SIM800 is also popular GPRS/GSM module (no GPS capability, but you already have that?):

[QUICKSTART SIM800 (SIM800L) WITH ARDUINO][3]

This technology is moving quickly, so you may find better options, for instance see:

[Difference between SIM908 vs SIM808 modules][4]

Hope this helps,
Regards, Geoff

  [1]: https://www.cooking-hacks.com/documentation/tutorials/geolocation-tracker-gprs-gps-geoposition-sim908-arduino-raspberry-pi/
  [2]: https://www.cooking-hacks.com/projects/arduino-realtime-gps-gprs-vehicle-tracking
  [3]: http://www.ayomaonline.com/programming/quickstart-sim800-sim800l-with-arduino/
  [4]: http://www.raviyp.com/embedded/212-difference-between-sim908-vs-sim808-modules


body:
Not with a UNO alone, the UNO obviously needs internet connection either via a LAN shield, a Wi-Fi unit (ESP8266) or a GSM unit.
Since you are GPS tracking then a GSM unit is most suited.

Particle Electron GPS receiver (Location plotted on Google Map)
https://www.brianmoreau.com/projects/particle-electron-gps-receiver/particle-electron-gps-receiver.php


body:
Arduino UNO is a micro controller without any internet communication. In order to send data to the cloud, you need to have an internet connection (meaning TCP/IP stack).

In regards with your project, there are 2 major solutions:

 1. Store all data locally on EEPROM (if not too much data because there is only 1KB on the Arduino Uno) or an external flash memory (there are some modules and libraries for this). When the Arduino is connected, you send over all the data to the cloud.
 2. Send the data while data are collected.

In both case, you need an internet connection that could be managed by a wifi module or a GPRS module depending on your needs.

For the wifi module, the ESP8266 is a popular and cheap choice. You will find a lot of documentation on Google.

For the GSM/GPRS module, I suggest the SIM800L which is cheap and easy to use (there is a HTTP/S stack embedded on the module).


message:
Unable to parse my JSON Data in Arduino IDE

i want to get my thingSpeak channel data into arduino by performing GET request every things works fine.Further i used Arduinojson lib to parse the JSON but i am getting failed every time when i try to parse it.I used arduinojson assistant to calculate the parsing program but still i am getting error.
Below is my JSON and Failure message that i got every time in serial monitor.

    {"channel":{"id":421932,"name":"remote_car","description":"Nothing up to this point !","latitude":"0.0","longitude":"0.0","field1":"MOTOR ONE","field2":"MOTOR TWO","field3":"MOTOR THREE","field4":"MOTOR FOUR","created_at":"2018-02-07T17:32:09Z","updated_at":"2018-03-17T07:08:49Z","last_entry_id":7},"feeds":[{"created_at":"2018-03-17T06:53:48Z","entry_id":4,"field1":"0"},{"created_at":"2018-03-17T06:59:22Z","entry_id":5,"field1":"0"},{"created_at":"2018-03-17T07:03:59Z","entry_id":6,"field1":"2"},{"created_at":"2018-03-17T07:08:49Z","entry_id":7,"field1":"1"}]}

    Parse Failed...

this is my arduino code(i used arduino plus esp8266 to get my thinkSpeak channel data).

    #include "WiFiEsp.h"
    #include <ArduinoJson.h>
    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(2,3); // RX, TX
    #endif
    char ssid[] = "M T G";            // your network SSID (name)
    char pass[] = "androidGUII";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status
    // Initialize the Ethernet client object
    WiFiEspClient client;
    static const char* host = "api.thingspeak.com";
    static const char* apiKey = "H359MYV0P0KFG2VS";
    const unsigned long HTTP_TIMEOUT = 10000;

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

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

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }
      // you're connected now, so print out the data
      Serial.println("You're connected to the network");
    //  printWifiStatus();
      Serial.println();
    }

    void loop()
    {
          const int httpPort = 80;
        if (!client.connect(host, httpPort)) {
            Serial.println("connection failed");
            return;
        }

     client.print("GET /channels/421932/fields/1.json?api_key=");
    client.print(apiKey);
    client.println("&results=4 HTTP/1.1");
    client.print("Host:");
    client.println(host);
    client.println();
      while (client.available() == 0);
      while (!skipResponseHeaders());  // wait till something comes in; you may want to add a timeout here
    while (client.available()) {                         // Now receive the data
        String line = client.readStringUntil('\n');
        if ( line.indexOf('{',0) >= 0 ) {                  // Ignore data that is not likely to be JSON formatted, so must contain a '{'
          Serial.println(line);                            // Show the text received
          parseData(line);
         }
      }
      client.stop();
      delay(10000);
    }

    void parseData(String data){
         const size_t bufferSize = JSON_ARRAY_SIZE(4) + JSON_OBJECT_SIZE(2) + 4*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(12) + 520;
         DynamicJsonBuffer jsonBuffer(bufferSize);
         const char* json = data.c_str();
         JsonObject& root = jsonBuffer.parseObject(json);
          if(!root.success()){
            Serial.println("Parse Failed...");
          }
         JsonObject& channel = root["channel"];
    long channel_id = channel["id"]; // 421932
    const char* channel_name = channel["name"]; // "remote_car"
    const char* channel_description = channel["description"]; // "Nothing up to this point !"
      Serial.println(channel_name);
      Serial.println(channel_description);
    }

    bool skipResponseHeaders() {
      char endOfHeaders[] = "\r\n\r\n"; // HTTP headers end with an empty line
      client.setTimeout(HTTP_TIMEOUT);
      bool ok = client.find(endOfHeaders);
      if (!ok) { Serial.println("No response or invalid response!"); }
      return ok;
    }

Any one have any idea how i am getting parsing failed message.
Any help would be appreciated.

body:
It is a memory allocation failure. Your Arduino Uno has 2KB ob RAM and I found out, via a binary search on the size of the `StaticJsonBuffer<size>` object, that for this specific 566 byte long JSON string you need a JSON buffer of at least 785 bytes to parse it.

Use this minimal sketch to test the size:

    #include <Arduino.h>
    #include <avr/pgmspace.h>
    #include <ArduinoJson.h>

    #define stringToParse  \
      "{\"channel\":{\"id\":421932,\"name\":\"remote_car\",\"description\":\"Nothing up to this point !\",\"latitude\":\"0.0\",\"longitude\":\"0.0\",\"field1\":\"MOTOR ONE\",\"field2\":\"MOTOR TWO\",\"field3\":\"MOTOR THREE\",\"field4\":\"MOTOR FOUR\",\"created_at\":\"2018-02-07T17:32:09Z\",\"updated_at\":\"2018-03-17T07:08:49Z\",\"last_entry_id\":7},\"feeds\":[{\"created_at\":\"2018-03-17T06:53:48Z\",\"entry_id\":4,\"field1\":\"0\"},{\"created_at\":\"2018-03-17T06:59:22Z\",\"entry_id\":5,\"field1\":\"0\"},{\"created_at\":\"2018-03-17T07:03:59Z\",\"entry_id\":6,\"field1\":\"2\"},{\"created_at\":\"2018-03-17T07:08:49Z\",\"entry_id\":7,\"field1\":\"1\"}]}"

    StaticJsonBuffer<785> jsonBuffer;
    void parseData(const __FlashStringHelper* json){
     //const size_t bufferSize = JSON_ARRAY_SIZE(4) + JSON_OBJECT_SIZE(2) + 4*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(12) + 520;
     //DynamicJsonBuffer jsonBuffer(bufferSize);
     //const char* json = data.c_str();
     JsonObject& root = jsonBuffer.parseObject(json);
     if(!root.success()){
      Serial.println("Parse Failed...");
      return;
     }
     JsonObject& channel = root["channel"];
     long channel_id = channel["id"]; // 421932
     const char* channel_name = channel["name"]; // "remote_car"
     const char* channel_description = channel["description"]; // "Nothing up to this point !"
     Serial.print("Channel name: "); Serial.println(channel_name);
     Serial.print("Channel description: "); Serial.println(channel_description);
     Serial.print("Channel id: ");
     Serial.println(channel_id);
    }

    void setup() {
     Serial.begin(9600);
     //We use the F() macro to create a flash string helper
     //this way, that huge JSON string is held in FLASH and not in precious RAM..
     parseData(F(stringToParse));
    }

    void loop() { }

If you decrease the buffer size by even 1 byte, parsing will fail.

Since you are using a `DynamicJsonBuffer` initially, your memory allocation will surely fail, since the heap can be really fragmented due to your other libraries (`WiFiEspClient`) and you are not able to find a continous 785 byte fragment on the heap. If the libraries tries to allocate memory object-wise (that is, not a continious segment), you might still get an out-of-memory error because

1. the heap induces overhead per allocated object because of house-keeping information
2. you fragment your heap over time, essentially leaving holes in it; this causes big allocations to fail because no continous segment could be found, although maybe in sum there is enough memory free
3. other libraries / part of your program is also using the heap and you are actually out-of-memory no matter what your allocation strategy is

You have various options:

* decrease the length of JSON string received by the Uno for it to be able to parse it.
   * For example, instead of huge JSON string have it receive a binary-formatted message with the information being as compactly packet in there as possible. You don't need to send `"id\":421932`, instead just make a field "id" in your packet format for a 32-bit integer. That decreases it from 11 bytes to 4 bytes.
* use `StaticJsonBuffer` with fixed maximum size instead of `DynamicJsonBuffer` to make sure you can *always* parse the longest message (that is, if you have enough RAM free)
* program the ESP8266 directly.

Really, your ESP8266 has about ~40KByte of user-usable RAM at startup and is at least an order of magnitude more powerful than your Uno. I wouldn't bother strapping a Arduino Uno to a mighty ESP8266 just for it to do JSON parsing.

Depending on what ESP8266 you have (ESP8266-01, ESP12F, NodeMCU board, ..) you should start looking for tutorials for programming it using the Arduino-ESP8266 framework.


message:
Wemos: relay shield doesn't work on top of the stack

I connected a **SHT30 shield** to a **Wemos D1 mini** (one on top of the other) to measure temperatures.

**Wemos D1 mini (2.3.0):** [![Wemos D1 mini][1]][1]
**SHT30 shield:** [![SHT30 shield][2]][2]

It works great but when I added a relay on the top of the stack it doesn't work anymore.

**Relay shield:** [![Realy shield][3]][3]

Maybe there are a conflict with their pins. So these are their schematics:

[![Wemos D1 mini schematic][4]][4]
[![SHT30 shield schematic][5]][5]
[![Relay shield schematic][6]][6]

This is the solution that I made but I don't know why this works instead of inserting the relay shield on top of the SHT30 shield:
[![My solution][7]][7]

  [1]: https://i.stack.imgur.com/UWT6Y.jpg
  [2]: https://i.stack.imgur.com/rirJs.jpg
  [3]: https://i.stack.imgur.com/wH0d9.jpg
  [4]: https://i.stack.imgur.com/tx5RB.png
  [5]: https://i.stack.imgur.com/COLCF.png
  [6]: https://i.stack.imgur.com/PxXcN.png
  [7]: https://i.stack.imgur.com/21kwe.png

body:
Yes, there is a pin conflict.  The relay uses D1, however D1 is (as you can see from looking at the schematics) part of the I2C connection for the SHT30.

You will have to find some way of modifying the relay shield to use a pin that's not part of I2C.


message:
avr_g++ compiler error: expected primary-expression before '.' token (C code in .ino)

The compiler is complaining about a macro defined in mjson.h

    Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

    #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                               ^

The code compiles and links ok on Windows 7 platform running Visual Studio and Ubuntu running gcc.

The full build errors are:

    Arduino: 1.8.5 (Windows 7), Board: "Arduino/Genuino Uno"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path AppData\Local\Temp\arduino_build_106446 -warnings=all -build-cache AppData\Local\Temp\arduino_cache_49629 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose Documents\Arduino\test_microjson\test_microjson.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path AppData\Local\Temp\arduino_build_106446 -warnings=all -build-cache AppData\Local\Temp\arduino_cache_49629 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose Documents\Arduino\test_microjson\test_microjson.ino
    Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "Documents\Arduino\libraries\microjson\mjson.c" -o "nul"
    Generating function prototypes...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "AppData\Local\Temp\arduino_build_106446\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "AppData\Local\Temp\arduino_build_106446\preproc\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -Wall -Wextra -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp.o"
    In file included from Documents\Arduino\test_microjson\test_microjson.ino:7:0:

    Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

     #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                                ^

    Documents\Arduino\test_microjson\test_microjson.ino:31:29: note: in expansion of macro 'STRUCTOBJECT'

       { "start_pin", t_integer, STRUCTOBJECT(lights_t, start_pin) },

                                 ^

    Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

     #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                                ^

    Documents\Arduino\test_microjson\test_microjson.ino:32:27: note: in expansion of macro 'STRUCTOBJECT'

       { "end_pin", t_integer, STRUCTOBJECT(lights_t, end_pin) },

                               ^

    Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

     #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                                ^

    Documents\Arduino\test_microjson\test_microjson.ino:33:30: note: in expansion of macro 'STRUCTOBJECT'

       { "colour_red", t_integer, STRUCTOBJECT(lights_t, colour_red) },

                                  ^

    Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

     #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                                ^

    Documents\Arduino\test_microjson\test_microjson.ino:34:32: note: in expansion of macro 'STRUCTOBJECT'

       { "colour_green", t_integer, STRUCTOBJECT(lights_t, colour_green) },

                                    ^

    Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

     #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                                ^

    Documents\Arduino\test_microjson\test_microjson.ino:35:31: note: in expansion of macro 'STRUCTOBJECT'

       { "colour_blue", t_integer, STRUCTOBJECT(lights_t, colour_blue) },

                                   ^

    test_microjson:40: error: expected primary-expression before '.' token

       { "type", t_string, .addr.string = thenode.type, .len = sizeof(thenode.type) },

                           ^

    In file included from Documents\Arduino\test_microjson\test_microjson.ino:7:0:

    Documents\Arduino\libraries\microjson/mjson.h:137:2: error: expected primary-expression before '.' token

      .addr.array.element_type = t_structobject, \

      ^

    Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

       { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                              ^

    Documents\Arduino\libraries\microjson/mjson.h:138:2: error: expected primary-expression before '.' token

      .addr.array.arr.objects.subtype = e, \

      ^

    Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

       { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                              ^

    Documents\Arduino\libraries\microjson/mjson.h:139:2: error: expected primary-expression before '.' token

      .addr.array.arr.objects.base = (char*)a, \

      ^

    Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

       { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                              ^

    Documents\Arduino\libraries\microjson/mjson.h:140:2: error: expected primary-expression before '.' token

      .addr.array.arr.objects.stride = sizeof(a[0]), \

      ^

    Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

       { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                              ^

    Documents\Arduino\libraries\microjson/mjson.h:141:2: error: expected primary-expression before '.' token

      .addr.array.count = n, \

      ^

    Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

       { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                              ^

    Documents\Arduino\libraries\microjson/mjson.h:142:2: error: expected primary-expression before '.' token

      .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))

      ^

    Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

       { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                              ^

    Using library microjson in folder: Documents\Arduino\libraries\microjson (legacy)
    exit status 1
    expected primary-expression before '.' token

test_microjson.ino:

    #include <stdlib.h>
    #include <stdbool.h>

    #include <stddef.h>  // offsetof - used in STRUCTOBJECT macro

    #include <mjson.h>

    #define MAX_SECTIONS 6  // we support up to six different sections on strip

    // in json sections is an array of these light options
    typedef struct light_section {
      int start_pin;
      int end_pin;
      int colour_red;
      int colour_green;
      int colour_blue;
    }lights_t;

    typedef struct node {
      char type[20];
      lights_t thelight[MAX_SECTIONS];
    } node_t;

    node_t thenode;

    static int num_sections;

    const struct json_attr_t section_attrs[] = {
      { "start_pin", t_integer, STRUCTOBJECT(lights_t, start_pin) },
      { "end_pin", t_integer, STRUCTOBJECT(lights_t, end_pin) },
      { "colour_red", t_integer, STRUCTOBJECT(lights_t, colour_red) },
      { "colour_green", t_integer, STRUCTOBJECT(lights_t, colour_green) },
      { "colour_blue", t_integer, STRUCTOBJECT(lights_t, colour_blue) },
      { NULL },
    };

    static const struct json_attr_t json_attrs[] = {
      { "type", t_string, .addr.string = thenode.type, .len = sizeof(thenode.type) },
      { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },
      { NULL },
    };

    void setup() {

      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      // this check is only needed on the Leonardo:
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // start the Ethernet connection:
      Serial.println("microjson test");

      static const char *s =
        "{ \"type\": \"section\", \"sections\": [{ \"start_pin\": 0, \"end_pin\": 71, \"colour_red\": 0, \"colour_green\": 255, \"colour_blue\": 0 }, { \"start_pin\": 216, \"end_pin\": 287, \"colour_red\": 255, \"colour_green\": 0, \"colour_blue\": 0 }] }";

      int status = json_read_object(s, json_attrs, NULL);

      if (status != 0)
        Serial.println(json_error_string(status));

      Serial.print("found ");
      Serial.print(num_sections);
      Serial.print(" sections");

      Serial.print("type=");
      Serial.println(thenode.type);

      //printf("type=%s\n", thenode.type);
      for (int i = 0; i < num_sections; ++i) {
        Serial.print("section [");
        Serial.print(i);
        Serial.print("]: start_pin=");
        Serial.print(thenode.thelight[i].start_pin);
        Serial.print(", end_pin=");
        Serial.print(thenode.thelight[i].end_pin);
        Serial.print(", red=");
        Serial.print(thenode.thelight[i].colour_red);
        Serial.print(", green=");
        Serial.print(thenode.thelight[i].colour_green);
        Serial.print(", blue=");
        Serial.println(thenode.thelight[i].colour_blue);
      }
    }

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

    }

And the offending macro in mjson.h STRUCTOBJECT.  And also STRUCTARRAY.  Here they are:

     * Use the following macros to declare template initializers for structobject
     * arrays.  Writing the equivalents out by hand is error-prone.
     *
     * STRUCTOBJECT takes a structure name s, and a fieldname f in s.
     *
     * STRUCTARRAY takes the name of a structure array, a pointer to a an
     * initializer defining the subobject type, and the address of an integer to
     * store the length in.
     */
    #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)
    #define STRUCTARRAY(a, e, n) \
     .addr.array.element_type = t_structobject, \
     .addr.array.arr.objects.subtype = e, \
     .addr.array.arr.objects.base = (char*)a, \
     .addr.array.arr.objects.stride = sizeof(a[0]), \
     .addr.array.count = n, \
     .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))

How can I fix this to get it to compile using Arduino avr-g++ ?

mjson.h is from microjson library.  I can provide more details of that if required.

mjson.h header:

    /* Structures for JSON parsing using only fixed-extent memory
     *
     * This file is Copyright (c) 2014 by Eric S. Raymond.
     * BSD terms apply: see the file COPYING in the distribution root for details.
     */

    #include <stdbool.h>
    #include <ctype.h>
    #include <stdio.h>
    #include <sys/types.h>

    #define NITEMS(x) (int)(sizeof(x)/sizeof(x[0]))

    typedef enum {t_integer, t_uinteger, t_real,
           t_string, t_boolean, t_character,
           t_time,
           t_object, t_structobject, t_array,
           t_check, t_ignore}
        json_type;

    struct json_enum_t {
        char *name;
        int  value;
    };

    struct json_array_t {
        json_type element_type;
        union {
       struct {
         const struct json_attr_t *subtype;
         char *base;
         size_t stride;
       } objects;
       struct {
         char **ptrs;
         char *store;
         int storelen;
       } strings;
       struct {
         int *store;
       } integers;
       struct {
         unsigned int *store;
       } uintegers;
       struct {
         double *store;
       } reals;
       struct {
         bool *store;
       } booleans;
        } arr;
        int *count, maxlen;
    };

    struct json_attr_t {
        char *attribute;
        json_type type;

     union {
       int *integer;
       unsigned int *uinteger;
       double *real;
       char *string;
       bool *boolean;
       char *character;
       struct json_array_t array;
       size_t offset;
        } addr;

     union {
       int integer;
       unsigned int uinteger;
       double real;
       bool boolean;
       char character;
       char *check;
        } dflt;

     size_t len;
        const struct json_enum_t *map;
        bool nodefault;
    };

    #define JSON_ATTR_MAX 31 /* max chars in JSON attribute name */
    #define JSON_VAL_MAX 512 /* max chars in JSON value part */

    #ifdef __cplusplus
    extern "C" {
    #endif
    int json_read_object(const char *, const struct json_attr_t *,
           /*@null@*/const char **);
    int json_read_array(const char *, const struct json_array_t *,
          /*@null@*/const char **);
    const /*@observer@*/char *json_error_string(int);

    void json_enable_debug(int, FILE *);
    #ifdef __cplusplus
    }
    #endif

    #define JSON_ERR_OBSTART 1 /* non-WS when expecting object start */
    #define JSON_ERR_ATTRSTART 2 /* non-WS when expecting attrib start */
    #define JSON_ERR_BADATTR 3 /* unknown attribute name */
    #define JSON_ERR_ATTRLEN 4 /* attribute name too long */
    #define JSON_ERR_NOARRAY 5 /* saw [ when not expecting array */
    #define JSON_ERR_NOBRAK  6 /* array element specified, but no [ */
    #define JSON_ERR_STRLONG 7 /* string value too long */
    #define JSON_ERR_TOKLONG 8 /* token value too long */
    #define JSON_ERR_BADTRAIL 9 /* garbage while expecting comma or } or ] */
    #define JSON_ERR_ARRAYSTART 10 /* didn't find expected array start */
    #define JSON_ERR_OBJARR  11 /* error while parsing object array */
    #define JSON_ERR_SUBTOOLONG 12 /* too many array elements */
    #define JSON_ERR_BADSUBTRAIL 13 /* garbage while expecting array comma */
    #define JSON_ERR_SUBTYPE 14 /* unsupported array element type */
    #define JSON_ERR_BADSTRING 15 /* error while string parsing */
    #define JSON_ERR_CHECKFAIL 16 /* check attribute not matched */
    #define JSON_ERR_NOPARSTR 17 /* can't support strings in parallel arrays */
    #define JSON_ERR_BADENUM 18 /* invalid enumerated value */
    #define JSON_ERR_QNONSTRING 19 /* saw quoted value when expecting nonstring */
    #define JSON_ERR_NONQSTRING 19 /* didn't see quoted value when expecting string */
    #define JSON_ERR_MISC  20 /* other data conversion error */
    #define JSON_ERR_BADNUM  21 /* error while parsing a numerical argument */
    #define JSON_ERR_NULLPTR 22 /* unexpected null value or attribute pointer */

    /*
     * Use the following macros to declare template initializers for structobject
     * arrays.  Writing the equivalents out by hand is error-prone.
     *
     * STRUCTOBJECT takes a structure name s, and a fieldname f in s.
     *
     * STRUCTARRAY takes the name of a structure array, a pointer to a an
     * initializer defining the subobject type, and the address of an integer to
     * store the length in.
     */
    #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)
    #define STRUCTARRAY(a, e, n) \
     .addr.array.element_type = t_structobject, \
     .addr.array.arr.objects.subtype = e, \
     .addr.array.arr.objects.base = (char*)a, \
     .addr.array.arr.objects.stride = sizeof(a[0]), \
     .addr.array.count = n, \
     .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))

    /* json.h ends here */

body:
.ino is compiled as C++. your test is C code. put the C code in a .c file and the declaration in .h file and include the .h in .ino

I created a test.c, copied the content of your main.c into it and renamed the main function to test().

Then I created a test.h with

    #ifndef test_h
    #define test_h

    extern "C" void test(char * buff);

    #endif

and in ino setup() I call `test();`

it compiles. It runs. Output:

    2 sections
    type=section
    section [0]: start_pin=  0, end_pin= 71, red=  0, green=255, blue=  0
    section [1]: start_pin=216, end_pin=287, red=255, green= 53, blue=  0

in ino

    void setup()
    {
      Serial.begin(115200);
      char buff[700];
      test(buff);
      Serial.print(buff);
    }
in .c

    void test(char* buff) {

      static const char *s =
          "{ \"type\": \"section\", \"sections\": [{ \"start_pin\": 0, \"end_pin\": 71, \"colour_red\": 0, \"colour_green\": 255, \"colour_blue\": 0 }, { \"start_pin\": 216, \"end_pin\": 287, \"colour_red\": 255, \"colour_green\": 0, \"colour_blue\": 0 }] }";

      int status = json_read_object(s, json_attrs, NULL);

      if (status != 0) {
        sprintf(buff, json_error_string(status));
        return;
      }

      int pos = sprintf(buff, "%d sections\n", num_sections);

      pos += sprintf(buff + pos, "type=%s\n", thenode.type);
      for (int i = 0; i < num_sections; ++i) {
        pos +=
            sprintf(buff + pos,
                "section [%d]: start_pin==, end_pin==, red==, green==, blue==\n",
                i, thenode.thelight[i].start_pin, thenode.thelight[i].end_pin,
                thenode.thelight[i].colour_red, thenode.thelight[i].colour_green,
                thenode.thelight[i].colour_blue);
      }
    }


message:
ESP8266 Wifi.setOutputPower - original/default value?

I'm working on dynamically adjusting the ESP8266 WiFi power using the following function, such that it's as low as possible, yet sufficiently reliable:

    WiFi.setOutputPower(x)

I've been trying unsuccessfully to find out what the original/default value is before that function is called? There is no function WiFi.getOutputPower(). I know the range of values is 0 to 20.5, but I'm curious to know what it is initially? I guess it could depend on the particular Arduino? I have the following: ESPduino, Wemos D1R2/D1R1/D1R1 mini, NodeMCU, Yun sheild.

I plan to use iwconfig & iwlist on a Pi3 to measure the RSSI, but I'd like to know the baseline if possible.

The best similar idea is expressed in here: : https://arduino.stackexchange.com/questions/45351/how-to-optimise-tx-power-for-esp8266/

Thanks in advance ;-)
Geoff

body:
I was looking for the same answer. I found this link: https://gitlab.com/painlessMesh/painlessMesh/issues/51

Someone dug deeper into the code and found it's set to the max value on init


message:
Turn off the second builtin Nodemcu 0.9 led

I'm making a low energy consumption device so I'd like to turn off all the led when I'm idle.

Unfortunately the nodemcu turn on a blue led while I'm idle (during `delay(ms)`)

Here is my code:

    #define LED    16

    void setup() {
      initialSetup();
      //Turn off the built-in led
      digitalWrite(LED, HIGH);
    }

    void loop() {
      //Here I do everything
      doStuff();
      //GO TO SLEEP
      delay(3600000);
    }

The led that turn on during delay is the one near to D0 pin.

The led that I can control and so turn off (pin #16 -> D0) is near the 5v pin.

It's possible to completely turn off all led to consume less?

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

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

body:
See this link which shows your second LED exactly (the image is for v1.0, I have v0.9 and the code below works just the same in this situation):

'Onboard LEDs? NodeMCU's got two!':

 https://lowvoltage.github.io/2017/07/09/Onboard-LEDs-NodeMCU-Got-Two

Quote:

> ESP-12 LED Blink:
>
>      void setup() {
>             pinMode(2, OUTPUT);     //Initialize GPIO2 pin as an output
>      }
>
>      void loop() {
>        digitalWrite(2, LOW);   // Turn the LED on by making the voltage LOW
>        delay(1000);            // Wait for a second
>        digitalWrite(2, HIGH);  // Turn the LED off by making the voltage HIGH
>        delay(2000);            // Wait for two seconds
>      }

Or write it like this (ie. using 'D4' rather than '2'):

> ESP-12 LED Blink:
>
>      void setup() {
>             pinMode(**D4**, OUTPUT);     //Initialize GPIO2 pin as an output
>      }
>
>      void loop() {
>        digitalWrite(**D4**, LOW);   // Turn the LED on by making the voltage LOW
>        delay(1000);            // Wait for a second
>        digitalWrite(**D4**, HIGH);  // Turn the LED off by making the voltage HIGH
>        delay(2000);            // Wait for two seconds
>      }

Regards, Geoff


message:
Use Mac for memory & processing

I understand that each model of Arduino has limited cpu, ram, etc.

However, I have this very powerful Mac that it’s hooked up to.

Am i able to use my Mac for expensive computation and just pass results to my arduino in real-time?

Basically arduino takes in sensor data - passes it to Mac. Mac computes and returns an output to arduino.

body:
[This blog][1] describes the author's open-source, cross-platform library in C to talk to an Arduino via serial. The library is available on [GitHub][2]. A C project on your Mac can use it to communicate with your Arduino. You'll probably want to create a simple command protocol to keep the two in sync, as serial is pretty "barefoot" by itself, being just a stream of bytes with no markers, packets, or check-sums unless you impose such structures on your data, yourself. It probably doesn't need to be very complex, depending what your application needs.

I have found similar projects in Python and in Java for the Mac/Windows/Linux/<whatever> side; there's plenty of work already done for you.

  [1]: http://todbot.com/blog/2013/04/29/arduino-serial-updated/
  [2]: https://github.com/todbot/arduino-serial/


message:
ATmega328 is not recognized by software

I installed the required drivers for the board. But I cannot still upload a program to the board. It says that

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : stk500v2
avrdude: usbdev_open(): did not find any USB device "usb" (0x03eb:0x2104)

avrdude done.  Thank you.

An error occurred while uploading the sketch

body:
Can be many causes since you did not provide more info (like what circuit, what application). But in general:

- Wrong software installation
- Try another similar chip/device, maybe this one is broken
- Is it recognized by USB at all?
- Bad USB cable
- Did you select the right board in the IDE (Arduino IDE?)

Possible solution:

- Reinstall IDE
- Change chip
- Change Arduino
- Use different cable