title: RGB Not displaying Red when using LCD

text:
# Question
Title: RGB Not displaying Red when using LCD
I was testing my RGB (common anode) on its own playing with colours and got the red, green to work as desired.

However, when I connected my LCD board to my Arduino Uno as well as the RGB (using the same code prior and same output pins so I know the code isn't the issue) the RGB no longer displays red.

I assume it has something to do with the fluctuating voltage/current after I've put in the LCD but I cant work out how to resolve it. When its meant to be red it's just nothing, doesn't light up, green however still works.

```
#include <LiquidCrystal.h>
#define COMMON_ANODE
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int SelectCounter = 0;
int hours = 0; // start hours
int minutes = 0; //start min
int seconds = 5; //start seconds
int redPin = A1;
int greenPin = 2;
int bluePin = 3;
int digitposition = 0;
int readkey;
int speaker = A5;
int buttonPin = A4;
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;

void setup() {
pinMode(speaker, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {
noTone(speaker);
setColor(0, 0, 255); // red

....... }

void trigger() {
  lcd.clear(); // clears the screen and buffer
 lcd.setCursor(6,0);
 lcd.println("MUM:      ");
 lcd.setCursor(4, 1); // set timer position on lcd for end.
 lcd.println("WAKE UP!    ");
 tone(speaker, 10);
 setColor(0, 255, 0);  // green
 delay(500);
 digitalWrite(A1, HIGH);
 digitalWrite(2, HIGH);
 digitalWrite(3, HIGH);
 noTone(speaker);
 delay(500);
 lcd.display();
 }

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
   red = 255 - red;
   green = 255 - green;
   blue = 255 - blue;
 #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

```

# Answer
Only the pins with a ~ next to it are PWM pins. The pin connected to the red led, pin A1, does not support PWM, so analogWrite will not have the desired effect.
> 1 votes

---
Tags: arduino-uno, lcd, rgb-led
---


# Question
Title: Problem with a seven segment display. The segments blink then turn off
I can't figure it out what is the problem with my circuit, the segments turning on for sec and then they are turning off for good.

I tried to connect to GND instead of the 5 V but then, nothing happened.

My code:

```
void setup() {
  for (int pin = 2 ; pin < 9 ; pin++){ // setup pins 2 – 8 to be output
    pinMode(pin, OUTPUT);
  }

  for (int pin = 2 ; pin < 9 ; pin++){ // turn on pins 2 - 8
    digitalWrite(pin, HIGH);
  }
}

void loop(){}

```

Working simulation demo

# Answer
> 5 votes
The first thing to understand is how to connect the 7 segment display to your Arduino. The common anode pin connects directly to 5VDC. Each "segment" connects to the Arduino through a current limiting resistor (1k ohm is a good value to start with).

To turn a segment on, you supply a ground to it (through the resistor of course). Change: digitalWrite(pin, HIGH) to: digitalWrite(pin, LOW) in your sketch to turn on the segments.

I'm sure there are plenty of tutorials on the internet showing one resistor on the common anode input, but that is not the correct way to drive the display. Think about what happens when you display the number 1 VS the number 8. Changing the number of segments drawing power from the single resistor will vary the intensity of the display. The number 1 will be far brighter than the number 8.

# Answer
> 1 votes
With foregood you mean broken probably.

I don't see any resistor in your circuit, probably the LEDs are broken.

I'm afraid you have to use a new segment LED, and follow:

Arduino Example

Especially read this fragment:

Current-limiting Resistors

> Don't forget that the display uses LEDs, so you should use current-limiting resistors in series with the digit pins. 330 ohms is a safe value if you're unsure. If you use current-limiting resistors on the segment pins instead, then open up the SevSeg.h file and set RESISTORS\_ON\_SEGMENTS to 1 for optimal brightness.

---
Tags: 7-segment
---


title: Burn hex with optiLoader

text:
# Question
Title: Burn hex with optiLoader
Can optiLoader be used to burn custom hex?

For example, there's hex representation stored in optiLoader.ino in `image_328`, if that value is replaced with content of my pre-compiled hex, should that work right out of the box or some additional tweaking is needed?

**EDIT**

Discussion about the same topic on arduino forum as well.

# Answer
Yes, it should work provided that your desired target image is stored in the same form, with correct metadata, and that **it is small enough to fit in the programmer device**.

The storage format of the payload-to-program could be made more optimal by a factor of almost two; however, for the original purpose of injecting compact Arduino-style bootloaders that is scarcely needed, and would have made preparing payloads more complicated.
> 1 votes

---
Tags: arduino-ide, atmega328, bootloader, avr
---


# Question
Title: How to measure CO2, Ammonia and Detect Smoke using MQ135?
---

Setup Info:

MQ135 + Arduino+16x2LCD+ESP8266+ThinkSpeak.

Hi All, I have just bought a MQ135 . I started arduino basics with LED blinking , interfacing and then started with my real project. e I have seen in the data sheet of MQ135 that it can measure Ammonia, Sulfide,CO2 and Benze steam. It can also be used to detect smoke and alert.

But in the Arduino uno Serial monitor, I can see only one value 408.

Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

Also, my friend suggested to calibrate this sensor for which I found really good material and started with 24 Hours on test after dumping a code to read data from it. Now I read 1836 which was 1795 , about half an hour back.

Kindly reply and let me know what info or input is required from My side. This is my first of my many uno projects to come.

Regards, Sillicon https://forum.arduino.cc/index.php?topic=535401.msg3649205#msg3649205

# Answer
> Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

This sensor does not differentiate between the various gases that it is sensitive to.
> 1 votes

---
Tags: arduino-uno, esp8266, sensors
---


# Question
Title: How can i get rid of the error "cannot convert 'String' to 'const char*'"
I want to get this code to recognise different commands and be able to parse the rest of the command, fore example I send "/sleep 5", and it will sleep for 5 seconds. However, I keep on getting this error "cannot convert 'String' to 'const char\*'". here is my code:

```
#define maxCommandLength 64

String commands[] = {"/test", "/say", "/reset", "/sleep"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Power on.");
}
char serial[maxCommandLength];
boolean valid;
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Clearing command buffer(char 'serial'");
  for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
    serial[i] = ' ';
  }
  if (Serial.available()) {
    Serial.readBytesUntil(' ', serial, maxCommandLength);
  }
  if (serial[0] == '/') { //if it is a command
    Serial.print("Command recieved. \nCommand class:");
    Serial.println(serial);
    //test if command is valid
    for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
      valid = strcmp(serial,commands[i]);
      if(valid){
        break;
      }
    }
    //execution of command
    Serial.readBytesUntil(' ', serial, maxCommandLength);
    //.......
  }
}

```

# Answer
> 1 votes
there is no reason for command to be a String array. Instead make it a `const char**`:

```
const char** commands = {"/test", "/say", "/reset", "/sleep"};

```

# Answer
> 1 votes
You can call the `.c_str()` method of `String` class returning (temporary) `const char *` representation of underlying string, in your case:

```
valid = strcmp(serial,commands[i].c_str());
//                               ^^^^^^^^

```

should work. Just make sure you don't keep the returned `const char *` around longer than necessary because by spec it is no guaranteed to remain valid.

---
Tags: arduino-uno, data-type, compilation-errors
---


title: What is RSR 09TI chip?

text:
# Question
Title: 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?

# Answer
> 1 votes
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 it's U1, and is an LM358.

---
Tags: arduino-uno
---


title: Using time function in arduino

text:
# Question
Title: 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

# Answer
> 1 votes
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.

---
Tags: millis
---


title: Uploading sketch problem

text:
# Question
Title: Uploading sketch problem
I just plugged my arduino and click upload, it shows this error:

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

Sketch uses 948 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

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

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
> 0 votes
either you are already using the serial port or you just didn't select the port from the arduino "Tools\>port" you can always check your device's communication port using the device manager.

# Answer
> 0 votes
In the Arduino IDE check for the available ports. Be sure that the COM Port on Windows or ACMO port on Linux based OS is selected.

If the problem continues then check if the port is allowed in Windows and Linux.

---
Tags: sketch, uploading
---


title: Parse long CSV file with esp8266

text:
# Question
Title: Parse long CSV file with esp8266
I'm trying to write a code for nodeMCU (esp8266 based board) to continuously calculate distance between GPS location and geographical coordinates written in a CSV file in SD. Originally I thought the best way to do it was to parse the file, save the longitudes and latitudes in two arrays at startup and, then, calculate continuously distances between arrays and coordinates taken from GPS. If distance is less than a value, an output warns me. There is only a "little" problem: the file contains 5500 coordinates and, so, it is impossible to allocate two arrays containing 5500 floats inside ram memory. Now I have thought two alternatives: 1) save the two arrays in flash memory that is, I know, a lot slower but also bigger 2) parse and calculate distance line by line continuously: in a loop I'll take the first line from SD, parse it, calculate distance between it and GPS location and, then do the same thing for second, third,... line. It requires the continuous access to SD and parsing but I don't have to use flash memory. What is the best option in your opinion? Have you got alternatives or suggestions? Thank you!!

# Answer
Instead od the SD card you can use the esp8266 file system SPIFFS. It uses the flash of the esp8266, which is connected at 40MHz as Quad I/O on newer systems.

To use SPIFFS you create a folder named `data` in your esp8266 sketch folder. You put the files in that folder and then you use the SPIFFS upload plugin.

In runtime use the SPIFFS library. It is similar to SD library.
> 0 votes

---
Tags: esp8266, sd-card, gps, nodemcu
---


# Question
Title: Modbus RTU controller monitoring with arduino and RS485 module
I'm a medium user in Arduino. I baught a pHmeter controller with RS485 output (MODBUS RTU protocol). I want to get pH value read by the controller over RS485 module and Arduino. According the controller's manufacturer, we should operate as bellow: Sent by computer : 00 03 00 00 00 01 85 DB Return from controller : 00 03 02 02 AE 05 58.

```

#include SoftwareSerial.h

#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 3   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);
  delay(2000);
  digitalWrite(SSerialTxControl, RS485Transmit);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x03);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x01);
   RS485Serial.write((byte)0x85);
   RS485Serial.write((byte)0xDB);
   Serial.println(" ");

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

}
void loop()
{

  if (RS485Serial.available())
  {
    byteSend = RS485Serial.read();   // Read the byte
    Serial.print(byteSend, HEX);
    Serial.print(" ");
  }
}

```

I tried this following sketch who does not work. I would like to know if it is the good way to send request to the controller?

# Answer
To send series of bytes over Serial or any other Stream (Print) implementation use the "write buffer" method `size_t write(const uint8_t *buffer, size_t size)`

For the case in question:

```
byte request[] = {0, 0x03, 0, 0, 0, 0x01, 0x85, 0xDB};
RS485Serial.write(request, sizeof(request));

```

If someone is curios about the Modbus RTU request bytes. They are:

* station address
* function - 0x03 Read Multiple Holding Registers
* register address - 2 bytes
* number of registers to read - 2 bytes
* checksum - 2 bytes

The response:

* station address return
* function or error code
* data length
* data - length bytes
* checksum - 2 bytes
> 3 votes

---
Tags: arduino-uno, rs485, modbus
---


# Question
Title: 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:

# Answer
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.
> 1 votes

---
Tags: arduino-uno
---


title: OVF in serial monitor instead of data

text:
# Question
Title: OVF in serial monitor instead of data
I am currently working with two Arduinos and I'm trying to synchronize them. I want to get data from four LIS3DH accelerometers. The LIS3DH accelerometers are connected to the Arduino using I2C interface. I have managed to get the Arduinos to synchronize using SPI but when I get the third set of data it keeps on showing OVF rather than the values. My code is below can someone please help me out?

Thanks

```
// SPI Master
#include <Wire.h>
#include <SPI.h>
#include "SPI_anything.h"
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>

//#define LIS3DH_CLK 13
//#define LIS3DH_MISO 12
//#define LIS3DH_MOSI 11
//#define LIS3DH_CS  10

// I2C
Adafruit_LIS3DH lisch1 = Adafruit_LIS3DH();
Adafruit_LIS3DH lisch2 = Adafruit_LIS3DH();
// Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();
struct event3;

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using
// programming port to program the Zero!
#define Serial SerialUSB
#endif

void setup() {
#ifndef ESP8266
  while (!Serial)
    ; // will pause Zero, Leonardo, etc until serial console opens
#endif

  Serial.begin(9600);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  Serial.println("LIS3DH test!");

  if (!lisch1.begin(0x19)) { // change this to 0x19 for alternative i2c address
                             // - Voltage SDO

    Serial.println("Couldnt start");
    while (1)
      ;
  }
  Serial.println("LIS3DH1 found!");
  if (!lisch2.begin(0x18)) { // change this to 0x18 for alternative i2c address
                             // - Ground SDO
    Serial.println("Couldnt start");
    while (1)
      ;
  }
  Serial.println("LIS3DH2 found!");

  lisch1.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!
  lisch2.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

  Serial.print("Range = ");
  Serial.print(2 << lisch1.getRange());
  Serial.print("Range = ");
  Serial.print(2 << lisch2.getRange());
  Serial.println("G");
}

void loop() {

  lisch1.read(); // get X Y and Z data at once

  /* Or....get a new sensor event, normalized */
  sensors_event_t event;

  lisch1.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print(" \t ");
  Serial.print(event.acceleration.x);
  Serial.print(" \t ");
  Serial.print(event.acceleration.y);
  Serial.print(" \t ");
  Serial.print(event.acceleration.z);

  lisch2.read(); // get X Y and Z data at once
  lisch2.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print(" \t ");
  Serial.print(event.acceleration.x);
  Serial.print(" \t ");
  Serial.print(event.acceleration.y);
  Serial.print(" \t ");
  Serial.print(event.acceleration.z);

  struct event;

  SPI_readAnything(event);
  //  sensors_event_t event;

  //  lisch3.getEvent(&event);
  Serial.print(" \t "); Serial.print(float2s(event.acceleration.x,6);
  Serial.print(" \t "); Serial.print(event.acceleration.y);
  Serial.print(" \t "); Serial.print(event.acceleration.z);
  Serial.println ();

  delay(500);
}

/ SPI Slave

#include <Wire.h>
#include <SPI.h>
#include "SPI_anything.h"
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>

#define LIS3DH_CLK 13
#define LIS3DH_MISO 12
#define LIS3DH_MOSI 11
#define LIS3DH_CS 10

    // I2C
    Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using
// programming port to program the Zero!
#define Serial SerialUSB
#endif

void setup() {
#ifndef ESP8266
  while (!Serial)
    ; // will pause Zero, Leonardo, etc until serial console opens
#endif

  Serial.begin(9600); // start serial for output

  SPI.begin();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

  Serial.println("LIS3DH3 test!");

  if (!lisch3.begin(0x19)) { // change this to 0x19 for alternative i2c address
                             // - Voltage SDO

    Serial.println("Couldnt start");
    while (1)
      ;
  }
  Serial.println("LIS3DH3 found!");

  lisch3.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

  Serial.print("Range = ");
  Serial.print(2 << lisch3.getRange());

  Serial.println("G");
}

void loop() {

  lisch3.read(); // get X Y and Z data at once

  /* Or....get a new sensor event, normalized */
  sensors_event_t event;

  lisch3.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print(" \t ");
  Serial.print(event.acceleration.x);
  Serial.print(" \t ");
  Serial.print(event.acceleration.y);
  Serial.print(" \t ");
  Serial.print(event.acceleration.z);
  Serial.println();

  digitalWrite(SS, LOW); // SS is pin 10
  SPI_writeAnything(event);
  digitalWrite(SS, HIGH);
  //  delay (1000);  // for testing

  delay(100);
}

```

# Answer
OVF means overflow, you probably exceeded the range of the data type you're using. Try /1000; /10000000000 etc to your variable until you don't get the OVF or use a datatype with a bigger range.
> 1 votes

---
Tags: arduino-uno, i2c, spi, accelerometer
---


title: analog read only once a time

text:
# Question
Title: 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

# Answer
> 1 votes
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.

# Answer
> 0 votes
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.

---
Tags: arduino-uno, analogread
---


# Question
Title: Using SD shield for extra external memory?
I am an Arduino beginner and I am planning to make a musical instrument with it. I want to add record and playback functionalities into the instrument.

I figure I will have to store lots of data to meet this feature, but the Arduino I'm using (Uno/Nano) probably won't have enough memory to hold lots of songs.

My question is, is using an SD card with an SD shield a good way to expand memory? If not, what should I use to do so?

Thanks

# Answer
> 2 votes
There are different options:

* SD shield: much memory (GB's), however keep in mind that it will take time to retrieve the data from the SD card. Also you can retrieve 512 bytes every time (which also means it costs 512 precious bytes of arduino SRAM).
* External SRAM: There are external SRAM ICs, like 23LC1024 or 24K256. These are much faster and offer 128 or 32 KB. There are many others too, these are most 'common'. These are much faster than SD cards, you can get 1, 2 or more bytes per time. But it's not the same as Arduino SRAM, e.g. you cannot really store variables, so you have to copy data to internal SRAM to be used.

So first, check how much you need, and more important: what is the latency you can live with.

# Answer
> 1 votes
Since you are working just with instructions on how to play audio, not the audio itself, you effectively have very small amounts of data (comparatively).

You can store that data in a file on SD card and read it back simply enough (there's plenty of examples for reading from and writing to SD).

You don't need the whole song in memory all the time - you only care about the note you're playing (or recording) at any one instance in time, so you don't need lots of memory.

How you format the data is entirely up to you, but I would suggest following the MIDI standard which will allow you to work with other tools to create and edit the files as well as the Arduino. You can also then export your music simply to other applications, such as MuseScore, Finale, Sibelius, Ardour, etc.

---
Tags: arduino-uno, arduino-nano, sd-card, memory
---


# Question
Title: 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");
}

```

# Answer
> 1 votes
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

```

---
Tags: arduino-uno, esp8266, http, thingspeak
---


title: Motor shield leaves no pins accessible

text:
# Question
Title: Motor shield leaves no pins accessible
I just bought a motor shield for my UNO, in the pic below:

Plugging it into the uno leaves no pins accessible on the board. I’d like to use it to build a robot car, but there’s nowhere to plug in the ultrasonic sensors. Do I need to solder some pins to the row at the top of the pic, or to the through-board holes on the right labelled A0-5?

# Answer
> 4 votes
According to tutorial, the shield uses almost all D pins. Free are pins 2 and 13. If servo is not used the pins 9 and 10 are free too. The pin 2 has the extra hole to solder a wire or a single pin header.

All analog pins are free and the shield enables to solder headers for them with additional header rows for 5V and ground for every A pin.

You can use analog pins as digital pins to connect the ultrasonic sensor.

Connection of I2C devices is possible on A4 and A5 pins.

The shield doesn't alow to stack a next shield, because it heats up.

# Answer
> 1 votes
yes. you can solder pin headers or contact wires directly to the shield. if use pinheaders it is easier to use the pins for other purposes. In the case of using ultrasonic sensor you should have to use digital pins along with the 5v and ground pins of the shield.

# Answer
> 1 votes
You can use a "Screw shield" between the motor shield and the Uno to make access to the unused pins easier.

---
Tags: arduino-uno, motor, arduino-motor-shield
---


# Question
Title: 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.

# Answer
> 3 votes
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.

# Answer
> 1 votes
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.

---
Tags: programming
---


# Question
Title: 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();
    }
}

```

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

```
> 0 votes

---
Tags: arduino-uno, i2c, button, stepper
---


title: C++ vs. The Arduino Language?

text:
# Question
Title: C++ vs. The Arduino Language?
What are the advantages of each language when using the Arduino?

I'm thinking this is a good general question, but I'll add a bit about why I'm asking if anyone wants to give me a tip.

I'm experienced in preprocessed languages like JavaScript, PHP, and have fiddled with languages like Java and Visual Basic. In other words I know programming techniques and both classical and prototypal object orientation, but nothing about communicating directly with hardware.

I'm making an octocopter, and am thinking that an object oriented approach will be the easiest. (The software will have very many features...) However I have never written in C++.

Since this is a Q&A site that's supposed to help others, only the general question presented at the beginning is of much importance, but I'd appreciate any comments on my situation.

# Answer
My personal experience as professor (programming, mechatronics) is that if you have previous programming experience and you are aware of concepts as OOP, it is better to go for C/C++. The arduino language is really great for beginners, but have some limitations (e.g. you must have all your files in the same folder). And it is basically a simplification of C/C++ (you can practically copy&paste arduino code to a C/C++ file, and it will work). Also it makes sense that you can go and use a full well known IDE as eclipse:

http://playground.arduino.cc/Code/Eclipse

Initially it is required a bit more of setup and configuration of your dev environment, but IMHO it is worth it for programmers with experience in any other language.

In any case, it won't harm you to start using the arduino language and the arduino IDE for a few days to get familiar with the arduino hardware and then move to C/C++ with Eclipse for really developing your project.
> 66 votes

# Answer
**In theory...**
There isn't really an Arduino language as such. It's really just C++ with some domain-specific libraries. These add on various features, such as functions you can call to control the hardware. If you didn't have those functions, you'd need to fiddle directly with special registers to control everything. That's how embedded programming is usually done. It's fast, but it can be quite hard to learn and understand.

In addition to the functions, the libraries add alternative names for some types. For example, `boolean` and `byte` are not in the C++ standard. However, they are directly equivalent to `bool` and `unsigned char`.

All of these things mean you can probably port general C++ code directly to Arduino without difficulty. However, going back the other way may require some minor editing.

But note that not all features of modern C++ versions are available on all Arduino platforms. In some cases, they aren't realistically possible, such as `std::thread` on an 8-bit microcontroller. Others simply haven't been made available, such as `std::array`.

**In practice...**
Having said all of that, programming for Arduino isn't exactly the same as general C++ programming. A lot of the differences are common to all embedded programming though (such as limited memory and processing power).

It's also worth noting that if you're using the official Arduino IDE then there are all sorts of annoying quirks and limitations on how you setup your code. There are workarounds in all cases (as far as I'm aware), but they are sometimes quite frustrating.

For full flexibility, use a third-party IDE (such as Eclipse) with a plug-in to support Arduino. That should give you all the advantages of C++, along with the Arduino libraries.
> 53 votes

# Answer
> What are the advantages of C++ vs the Arduino language when using Arduino? I'm experienced in preprocessed languages like JavaScript, PHP, and have fiddled with languages like Java and Visual Basic.

First, the Arduino compiler/IDE accepts C and C++ as-is. In fact many of the libraries are written in C++. Much of the underlying system is not object oriented, but it could be.

Thus, "The arduino language" is C++ or C.

C++ is not garbage collected. It does manage variables in scope - if you write:

```
int led = 13;

void blinkTimes(int value)
{
   int i;

   for(i=0;i<value;i++)
   {
      digitalWrite(led, HIGH);
      delay(1000);
      digitalWrite(led, LOW);
      delay(1000);
   }
}

```

Then you'll find that `led` and `i` don't grow or leak, no matter how many times you call `blinkTimes`.

If `i` were a class, it would similarly be disposed of once the function ended. So as long as you aren't using `new` or similar memory allocation functions to create new objects, then you won't have to worry about leaks.

You may still run out of memory, if you create huge classes and use a lot of them in deeply nested functions, but in general you aren't going to run into trouble until you start dealing with `new` and `free` functions.

If you are using `new`, then you'll have to call `delete` at appropriate times. C++, and by extension Arduino, has no automatic garbage collection, you have to explicitly manage your own memory.
> 28 votes

# Answer
--- Update 170412
I wrote my original answer three years ago from the perspective of there existing a distinct "Arduino C++". The language used in the IDE *is* standard C++, because it is implemented by the GNU C++ compiler. "Apparent" differences creep in because the IDE will do some pre-processing to help newcomers to the language avoid a couple of 'gotcha's, by filling in some #includes, f/ex. But you can - and I do - write correct C++ to it and get just what you expect to get.
--- end update

Do limit your use of C++ language features to those whose implementation you fully understand. There are some features that compile to more resource-intensive code than is obvious from reading the source code. The optionally generated .lss (merged source and assembly) listing can give you some good insight into what the C++ compiler did when you weren't looking.

To your question about memory: C++ does not garbage-collect. Stack-based languages like C and C++ do allocate temporary storage on the stack for automatic variables at function entry, which then gets released when the function returns, but this is not true garbage-collection. Objects created in heap- or global memory live until you explicitly delete them. Make sure you know where, when, and for how long different kinds of objects will be created. You really don't want your code `new`-ing and `delete`-ing objects willy-nilly. They will be built in heap memory, fragmenting it and causing it to grow up into the stack. That's when your code - and your nice 'copter - will crash.

C does less for you so it can do less **to** you. It's not a bad choice. C with a few of C++'s features can be an even better choice, given you choose the extra features judiciously.C++, if those are your two choices:

\[Original answer\] \- C++ is a standardized language. It is widely deployed in many environments including embedded systems and therefore is more thoroughly tested than the very-like-C++ language that is "Arduino". This is especially important for mission-critical / safety-critical applications such as you are planning. Crashed code means a crashed 'copter and even if it doesn't hurt someone, it **will** break your expensive machine.

* Being standard, C++ is portable. Need to upgrade your processor? Everything but silicon-specific code will port to the new one. Need to change your toolset, development system, host OS? C++ will be supported everywhere. Though Arduino IDE will run anywhere Java is supported, it is the only tool that uses Arduino C++ and it is a very limited tool. If you want to use Eclipse, the AVR tools, go barefoot on the command-line, develop within Emacs, or whatever other environment you prefer, standard C++ will be supported.
* The Arduino IDE does things behind your back - specifically, it #includes .h files when it thinks you need them. Even if it is correct, you really want to write, or at least see and understand, everything the compiler is going to see. Programming languages aren't made for computers (computers eat bits for breakfast); they're made for people, specifically the people who follow you on the project, the most important of whom may be ... you!, when 6 months after you wrote a module, you have to come back to enhance it, or more likely, fix it. You really want to be able to see everything the compiler sees.
> 17 votes

# Answer
The Arduino language *is* C++, but it is very different from most C++ varieties. The Arduino language has a lot of abstraction built in, especially in the hardware interfaces, which makes it very simple to use. If you have a background in Java, C and C++ should be very similar.

The main differences between Arduino and C++ are in the memory storage. Usually a modern computer has more than 2GB of RAM, while the Arduino Uno has 2kB (1 million times less). The Arduino also uses 8-bit instructions in stead of the 32 bit ones a computer uses. This will mainly affect the amount of information you can store in a variable.

If you are very new to the Arduino world, you should look up a tutorial, as there are many good ones out there.
> 15 votes

# Answer
In my experience, it is best to avoid **new** and **delete** when running on machines with limited memory.

* The memory management itself uses valuable program and RAM space
* ISR vectors are set at compile tme. It is difficult (impossible?) for a class instance to claim an ISR at run time
* Generally you will know at compile time what class instances you need - e.g. 3 button debouncers, a display driver and a 2-line display driver
* Memory management introduces unknown delays when you use new or delete.

There may be cases where it is justified to use dynamic instance construction and destruction, but I suspect they are rare.
> 12 votes

# Answer
As mentioned in several answers, if you are programing an embedded system in general you should avoid **new** unless you are managing your own memory heap and you really know what your object life cycles will be. Static allocation or stack variables are much safer. That said, one common trick to manage things like variable length buffers allocated for the duration of a function is to have an automatic variable (on the stack) that is an object that calls **new** in its constructor, and then put the **delete** in the destructor so when the object goes out of scope the buffer is released back to the heap. Again, this is usually of limited use in little micros but it is a nice pattern to remember.
> 9 votes

# Answer
In addition to the comments above, I would like to further stress the problems with working RAM that you have on Arduino boards, particularly with the Uno (and others that share the same microcontroller). I recently wrote a simple Space Invaders game running on a 32x32 LED matrix and repeatedly ran into problems caused by low memory.

The Uno only has 2048 bytes of RAM. The library for my matrix took over 3/4 of that leaving me with around 400 bytes for the game. As it is my intention to "upgrade" the project at some point to run multiple games with the same program base on the more powerful Due, I designed the code with OO principals and a lot of class inheritance. (The game class was inherited with virtual update and draw calls, the game entities were all inherited).

I pretty much ran out of memory just adding the invaders. I tried to save memory by bit-fielding their member variables but ran out again when adding the shield objects. After a bit more scraping I ran out adding the bombs/bullets. At this point I scoured the code and removed all "virtual" tags (all my class prototypes are built from a Visual Assist snippet and destructors are all virtual automatically). This halved my memory usage instantly, freeing enough to be able to complete the code.

Long story short, the end result is C++ code that doesn't really use any C++ features. You might be as well just sticking to C and being very aware of your memory usage. You get no help if you exceed the 2KB - particularly if you are using any dynamic allocation, the code just stops working and you are left scratching your head for a while until you consider the possibility of memory overflow.

PS - Bit fielding variables is bad. Very bad. Apart from adding processing overhead, I lost track of the number of times I'd add a new state to the game but the code wouldn't run and I couldn't understand why. My state variable was not wide enough to hold the new state value so I was getting some unexpected state.
> 8 votes

# Answer
## Arduino *is* C and C++ (it is a mix of the two, linked together); there is no "Arduino" programming language

**The Arduino language *is* C++** (albeit usually implemented in a style more like "C with classes," which is actually fairly common in the embedded systems microcontroller world). **End of story.** Enough with people thinking it's a different language already! It uses the g++ compiler.

## Proof:

**Enable verbose output during compilation in the Preferences and upload and you'll learn a lot just reading those lines.**

## Here's some additional insight:

### My own words:

**Arduino code *is* C++.** The Arduino core functions are simply a set of C++ classes and libraries you can use. It is built and compiled using the GNU gcc/g++ compiler. Your `setup()` and `loop()` functions are simply placed into the mandatory (meaning: required by both C and C++ in order to even be considered a valid program) `main()` function (right here actually--notice the file is `main.cpp`, which is a C++ source file) automatically for you and there is some extra preprocessing done to make sure it is a valid C++ program (ex: scanning for all function prototypes \[aka: declarations\] for you so you can use a function even though its prototype comes later in your `.ino` file). Much of Arduino is written in C, however, and therefore requires the `# extern "C" {}` braces around it to prevent C++ from "name-mangling" (also known as "name decorating/name decoration") function calls to C functions implemented by AVR-libc, which is the C implementation for the ATmega328 and other AVR-architecture microcontrollers.

### Arduino's words:

> "Can I program the Arduino board in C?
> In fact, you already are; the Arduino language is merely a set of C/C++ functions that can be called from your code. Your sketch undergoes minor changes (e.g. automatic generation of function prototypes) and then is passed directly to a C/C++ compiler (avr-g++). All standard C and C++ constructs supported by avr-g++ should work in Arduino. For more details, see the page on the Arduino build process."

Source: https://support.arduino.cc/hc/en-us/articles/360018448219-Can-I-program-the-Arduino-board-in-C-

## When to use the Arduino library vs pure C or C++?

So, use the Arduino language where it simplifies things, and write your own functions where you need more specialization. I do recommend getting away from the IDE quickly though for writing code--just use it for compilation. Set the IDE preferences to use "External Editor." Then use a professional source code editor/IDE such as Sublime Text 3, Atom, Visual Studio Code, or Eclipse CDT to write your code. You can then click back to the Arduino IDE to compile and upload. If you go with Eclipse, there are ways to do that in Eclipse (see the other answers here, and see the Arduino playground Eclipse article here too) so consider using those techniques too.

## Update: Eclipse setup

See my answer here and my document here: Eclipse setup instructions on a new Linux (or other OS) computer. I wrote a detailed PDF to describe setup.
> 6 votes

---
Tags: c++, arduino-ide
---


# Question
Title: Shield board with holes, do I need to solder?
I have a motor shield. I can put it on top of my arduino Mega and works perfect.

However, since the shield plugs in on top of the arduino board, I don't have access to 5V and GND from Arduino Mega.

I just have holes on the board with 5V and GND. (look at image)

Do I have to solder a cable there to have access to 5V and GND? or there is another easier way?

# Answer
Since there are two grounds, a 2-pin terminal block of the type already on the board may fit. Or, since the shield doesn't obscure the far end of the Mega (the end with the high numbered I/Os), you could pick up 5V and Gnd there. The ends of the double-row female header have respectively, 2 each 5V and Gnd connectors. You would pick those up with breadboard wires, though it is admittedly less secure.
> 4 votes

# Answer
You can also use a Mega Screw Shield if you don't want to solder wires
> 1 votes

---
Tags: arduino-mega, shields, arduino-motor-shield
---


title: Not sure if my Arduino Uno is damaged

text:
# Question
Title: Not sure if my Arduino Uno is damaged
When I plug the USB cable to my Arduino and try to upload a sketch I get thtis error:

```
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1411": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

```

when I go to Tools \> ports I can't find the USB port. The Arduino still working and green ligh is on, so what is the problem exactly?

# Answer
> 2 votes
Have heard of similar problems with Mac. Not a Mac user myself. Sometimes the Arduino can somehow trigger a current fault in the USB of Mac's and will need to be shut down and rebooted for it to work again.

Try rebooting your Mac.

If you have a cheap chinese Arduino you might need other drivers for it. Check what chip you have closest to the usb connector.

# Answer
> -1 votes
I was also facing this type of issue. But it has resolved itself now. I go to `Tool` \>\> Select `Port` after Select `USB modem` its work fine.

---
Tags: arduino-uno
---


title: Import library in Arduino IDE

text:
# Question
Title: 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 on Github and, following this guide, 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*

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

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\`.
> 2 votes

---
Tags: c++, library, nodemcu
---


# Question
Title: Having problems registering my SIM800 with the network
I have a SIM808, connected via hardware serial to an Arduino Mega. Communication between the Arduino and the SIM808 is fine. However, the quality of the signal is listed as 0 all the time. (AT+CSQ)

I've checked, and there is definitely 2G (and 3G) signal. Power is fine. SIM is unlocked, and works in other M2M equipment.

The network status lights blink rapidly (ie searching for a network) for about 5 seconds. Then it takes one long blink, then goes back to blinking rapidly.

The module is picking up the names of the available networks, yet does not seem to be able to register.

I'm using a prepaid data SIM card from Vodacom (South Africa).

# Answer
> 1 votes
I think you are not giving it enough power, SIM800 module needs 5v/2A stable power source in order to register to network. Try to use a desktop computer power supply it has 5v/2A output wire (refer to colors).

# Answer
> 0 votes
Actually the SIM800 should not be supplied with more than 4.4 V according to the datasheet. I would be interested to know how this problem was resolved.

I have a similar problem. I cannot get the SIM800 to connect to Three or the O2 network even though both SIMs work in my mobile phone.

In my case the SIM800 is connected directly to two 18650 Li-Ion batteries in parallel so I don't think it is lack of power. Perhaps a big capacitor would help. I will give it a try. Failing that it might just have a much less adequate antenna and needs to be out in the open.

---
Tags: arduino-mega, gsm
---


title: nodemcu EEPROM corrupting

text:
# Question
Title: 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

### Debug Messages

<pre><code>```
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:
</code></pre>

\`\`\`

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

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

---
Tags: programming, arduino-ide, nodemcu, eeprom
---


title: Arduino resets variable every loop

text:
# Question
Title: 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.

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

```
> 1 votes

---
Tags: variables
---


# Question
Title: 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. 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();
    }
}

```

# Answer
> 0 votes
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 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.

---
Tags: arduino-uno, arduino-nano, i2c, button, stepper
---


# Question
Title: 4x4 matrix keypad - Multiple inputs cause extra readings
I have the following matrix keypad -

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:

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.

# Answer
> 3 votes
I have a post about keypad matrices 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.

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

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

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

---
Tags: arduino-mega, digital, input
---


# Question
Title: How to directly solder wires to protoshield to connect them to Arduino pins
I bought an assembled Arduino Uno protoshield version 5, similar to this:

I bought it because I would like to solder wires from Arduino IOs, and I was quite disappointed with the impossibility to do so, since the solder points are already taken by the female headers, which are not connected to anything (there are not tracks coming from then to other islands, which I find quite dumb).

I am considering to remove (by desoldering) the headers, so I can access the holes for soldering wires (instead of plugging them to headers), but before doing so, I ask:

> Is there a good way to solder wires so they are electrically connected to the Arduino IO pins?

# Answer
> 5 votes
For the signals, get some AWG30 wire and solder them underneath to the female header pads. For power, get some AWG22 or AWG24 wire and solder them to the top of the male header pads.

# Answer
> 2 votes
Other boards bring the header pins to prototype area pins, as I do here http://www.crossroadsfencing.com/BobuinoRev17/UnoScrewSheild2016.jpg

# Answer
> 1 votes
It looks like you are missing the solder-less breadboard piece for your shield. The shield I bought came with one, and some 2 sided sticky "foam tape" to affix it to the circuit board.

If you use the shield with the solder-less breadboard, then it would be not be feasible to stack another shield on top of it because of the height of the components and jumper wires plugged into it.

I tested my shield and found the same thing you did, the header pins are not connected to any of the connection points on the board. That is dumb indeed.

As CrossRoads mentioned in his answer, there are other options, such as screw terminal shields. They sell them for $2.43 USD on aliexpress.com Screw Terminal Shield.

---
Tags: shields, prototype
---


title: Arduino cannot sync

text:
# Question
Title: 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.

```

# Answer
> 1 votes
Ok figured it out.......had to change the board type/////

---
Tags: arduino-mega
---


# Question
Title: 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.

# Answer
> 0 votes
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.

---
Tags: arduino-uno, esp8266, json, thingspeak
---


# Question
Title: 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):**  **SHT30 shield:**

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

**Relay shield:**

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

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:

# Answer
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.
> 4 votes

---
Tags: pins, relay, nodemcu, temperature-sensor
---


# Question
Title: RF transmitter with external 8-12v power not working properly
So I have this pair of transmitter and receiver

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

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.

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

# Answer
> 1 votes
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)

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.

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 )

---
Tags: power, rf
---