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

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

#include <Wire.h>

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

#define PWR_MGMT_1 0x6B
#define PWR_MGMT_2 0x6C

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

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

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

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

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

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

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

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

```

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

```
#include <Wire.h>

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

#define PWR_MGMT_1 0x6B
#define PWR_MGMT_2 0x6C

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

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

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

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

}

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

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

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

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

```

\`

# Answer
> 1 votes
When ever you start looking at multiples of an object you should think of classes and structures to do things.

If you wrote a class:

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

    // Class destructor
    ~MPU6050()
    {}

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

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

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

private:
    byte m_Address;
};

```

You could then have any number of sensors by going:

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

```

To access the data or functions in them:

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

```

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

---
Tags: arduino-uno, sensors, i2c, mpu6050
---


# Question
Title: Multiple HC-SR04 with one 5v 7805 regulator
I am working on a autonomous track vehicle. I have mounted

3 HC-SR04 sensors 1 Sharp infrared distance sensor 3 infrared led distance sensors

1 Arduino Mega 2560 1 H-bridge Board HG7881

I am trying to use 7.5 v 1700 mAh Nicd battery (also tried 11.1 Lipo 2200 mAh) For all sensors power (5v) I developed 5v regulator using 7805 which is connected directly from battery as input. The output 5v is going to power distribution board (used from quadcopter extra board) which provides 5v to every sensor.

The real problem starts here when I am not getting correct or nothing in reading from Ultrasonic sensors and my vehicle starts behaving abnormal. I checked that sensor reading is either 0 or wrong. I used both simple and with NewPing library.

I checked when using 7.2v battery the output from 5v regulator is 3.72v.

Now my question is if the power is below 5v, does sensors starts behaving like this? How can we supply voltage so every sensor will receive full 5v to work properly?

My vehicle will not work until sensors provide correct distance reading. I worked successfully with one sensor but with number of these, tired working since many days.

# Answer
> 1 votes
You really could benefit from a DC/DC switching power supply. For instance you are wasting about 20% of the power of the 7.2V battery and something like 50% of the power of the 11.1V battery.

That said, could it be that you are triggering the 3 ultrasonic HC-SR04 too closely together? If you don't wait for the sound to die out from the 1st sensor the 2nd sensor could give unexpected results. Same goes for the 3rd sensor.

# Answer
> 0 votes
Your 7805 regulator isn't working, it should have a output of 5v, 3.72v is way off. 2-4% diff from 5V is the normal specification. https://www.fairchildsemi.com/datasheets/LM/LM7805.pdf

Vin should be between 7-20volt even if the datasheet indicate that you can have as low as 5volt in.

Causes could be:

* Wrong design
* Low battery voltage
* Faulty component
* Faulty connection

---
Tags: arduino-mega, power, battery, hc-sr04
---


# Question
Title: How to read data from Arduino with Raspberry Pi via I2C?
I have connected a Raspberry Pi 2 model B to an Arduino Uno via Bi-Directional Level shifter, from this BLOG:

```
Raspberry pi    GND    ----------   GND     Arduino
                3.3v   ----------   5v
                SCL    ----------   A5
                SDA    ----------   A4

```

I hope my I2C connection is correct.

And my Arduino is connected to an 8-Channel relay board.

Now I have written code in which I can control the relay board with the Raspberry Pi. For example, if I Press '1', relay 1 goes high.

Now I want to send data back from the Arduino to the Raspberry Pi in order to cross-check if relay 1 is high or not. If relay 1 is high then it should send some data back to the Raspberry Pi.

My Raspberry Pi code is:

```
import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    # bus.write_byte_data(address, 0, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    # number = bus.read_byte_data(address, 1)
    return number

while True:
    var = input("")
    if not var:
        continue
    writeNumber(var)
    number = readNumber()

```

My Arduino code:

```
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
#define RELAY1 9

int number = 0;
int state = 0;

void setup() {
    pinMode(RELAY1, OUTPUT);
    Serial.begin(9600); // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);
    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
       number = Wire.read();
       Serial.print("data received: ");
       Serial.println(number);
        if (number == 1) {
            if (state == 0){
                digitalWrite(RELAY1, HIGH); // set the LED on
                state = 1;
            } else {
                digitalWrite(RELAY1, LOW); // set the LED off
                state = 0;
            }
        }
    }
}

// callback for sending data
void sendData(){
    Wire.write(number);
}

```

Now if I type 1, and due to some loose connection relay 1 doesn't go high, I want the Arduino to take data from the relay board and send it to the Raspberry Pi every time.

It will be great if someone can explain also that how it works.

Hope I was able to explain the problem. I have done lots of research but was not able to find some answer.

I am a beginner in Python so please help me.

Thanks in advance.

# Answer
You might want to graduate to the pigpio library for the Pi side of this.

Here is where you can find examples of how it works.

here is a fun one that is like Wireshark - will show you the I2C traffic:

https://github.com/joan2937/pigpio/tree/master/EXAMPLES/C/I2C\_SNIFFER

Here is the FAQ about I2C
> 1 votes

# Answer
*Character '1' is not number 1. Try "number == '1'. – Mikael Patel Mar 9 '16 at 11:34*
> 0 votes

---
Tags: arduino-uno, i2c, python, raspberrypi
---


# Question
Title: I have just done this same code but not getting exact time as per Indian timezone...What thing should I add to get exact time?
```
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

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

// The TinyGPS++ object
TinyGPSPlus gps;

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

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

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

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

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

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

```

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

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

---
Tags: arduino-mega
---


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

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

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

**Edit** : the Arduino code :

```
#include <SPI.h>

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

volatile char bytes_received = 0;

void setup()
{

  SPCR |= bit(SPE);

  pinMode(MISO, OUTPUT);

  SPI.attachInterrupt();

  SPDR = sendingBuffer[bytes_received];

}

ISR(SPI_STC_vect)
{

  if (++bytes_received == 5)
  {

    bytes_received = 0;

  }

  SPDR = sendingBuffer[bytes_received];

}

void loop()
{

  //

}

```

Also, the C code on the RPi :

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

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

int main(void)
{

   wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED);

   while (1)
   {

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

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

      wiringPiSPIDataRW(SPI_CHANNEL, buf, 5);

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

      sleep(1);

   }

   return 1;

}

```

# Answer
> 2 votes
The maximum speed for Arduino as a slave is F\_CPU/4, so it's 4Mbps. When the Arduino is the master it can work at F\_CPU/2, so it's 8Mbps

---
Tags: arduino-uno, spi, speed
---


# Question
Title: Arduino + SIM808: How to get only the JSON object response without the header?
I have been successfully getting the response from my web server. The problem is I get the whole package with header and content/body:

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

1501644397698.2585

```

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

This is the code which sends and prints the response:

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

```

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

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

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

```

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

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

---
Tags: arduino-uno
---


title: Problem reading from GPS

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

GPS module: RoyalTek 4216

CODE:

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

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

```

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

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

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

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

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

```

And then called it:

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

```

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

Here is why I said it won't compile:

```
    k=localTime.hours;

    int i=0;
    long k;

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

```

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

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

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

```

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

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

```

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

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

# Answer
> 1 votes
So you don't know how to read the time from a GPS? Is that the problem?

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

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

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

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

---
Tags: arduino-mega
---


title: MCP23S17 library crashes

text:
# Question
Title: MCP23S17 library crashes
I have a rather voluminous sketch with a heap of source and header files.

Now I'm facing the problem, that controlling the MCP23S17 on my board fails in different ways within this sketch. This is rather awkward, because when I modify the sample sketch taken from this library to my needs, the port expander can be accessed and controlled without any problem.

what happens within my own sketch? If I initialise SPI myself before using any of the library methods, everything of my sketch and hardware but the port expander works flawlessly. I.e. all hardware does what it is intended to, only the pins of the port expander do nothing.

If I remove all SPI commands I inserted there to initialise SPI according to my needs, the code will fail during the first call to MCP23S17::pinMode(…). Fail means: The CPU crashes. It hangs inside this routine and keepalive-LED stops blinking, serial output is severed. As I don't have any means of debugging besides Serial.print(), I narrowed it down to the call of

```
_spi->transfer(cmd);

```

within

```
void MCP23S17::writeRegister(uint8_t addr)

```

So something from my other code must interfer with this call, somehow, so the CPU comes to a halt. What the heck do I have to look for?

Additional information:

* Portexpander chip select is tied to Pin 7 of Arduino Uno.
* Portexpander address i 0
* Other device connected to SPI: display
* Other notable devices: RTC (on I2C), lot of 1-wire devices.

**Addendum** following Majenko's suggestions, I reduced my code to reach functionality in this issue. I did not succeed. So I decided to post two antagonistic sketches, one crashing and one working. **Spoiler: I found my coding flaw myself five minutes ago, I'm going to post it as answer later, but decided to go on writing this addendum as I had intended**

Here comes the .ino-file of the failed sketch:

```
#include <SPI.h>
#include <MCP23S17.h>
#include "spin.h"

void setup() {
    Serial.begin(9600);
    Actors::setup();
    Serial.println("setup finished");
}

void loop() {
    Actors::service();
}

```

part of this are two further files, from which I removed everything possible: spin.h:

```
#ifndef _INC_SPIN
#define _INC_SPIN

#include <MCP23S17.h>

class Actors
{
    private:
    static const uint8_t PexSSPin;
    protected:
    static MCP23S17 portExp;

    public:
    static void setup();
    static void service();

};
#endif

```

and spin.cpp:

```
#include "spin.h"

const uint8_t Actors::PexSSPin=7;
MCP23S17 Actors::portExp(&SPI, Actors::PexSSPin, 0);

void Actors::setup()
{
    Serial.print(F("Ac:se#"));
    Serial.print(".");
    portExp.pinMode(2, INPUT);  // not used. INPUT mode prevents damage due to accidental shorting
    Serial.print(".");
    portExp.pinMode(3, INPUT);  // not used. INPUT mode prevents damago due to accidental shorting
    Serial.print(".");

    Serial.print(F("Ac:se!"));
}

void Actors::service()
{
    Serial.print(F("Ac:sv#"));
    Serial.print(F("Ac:sv!"));
}

```

As noted in my first part of the question this code comes to a halt during the first call to the pinMode() method of the portexpander. There's no serial output after the first pinMode call and the actors weren't working either (when there was useful code left).

On the contrary here comes a working sketch with the same library controlling the same port expander on the same hardware.

```
#include <MCP23S17.h>
#include <Arduino.h>

#ifdef __PIC32MX__
// chipKIT uses the DSPI library instead of the SPI library as it's better
#include <DSPI.h>
DSPI0 SPI;
#else
// Everytying else uses the SPI library
#include <SPI.h>

#endif

const uint8_t chipSelect = 7;

MCP23S17 Bank1(&SPI, chipSelect, 0);
uint16_t data;

void setup() {
    Serial.begin(9600);
    Bank1.begin();
    Bank1.pinMode(8, OUTPUT);
    Bank1.pinMode(9, OUTPUT);
    Bank1.pinMode(10, OUTPUT);
    Bank1.pinMode(11, OUTPUT);
    Bank1.pinMode(12, OUTPUT);
    Bank1.pinMode(13, OUTPUT);
    Bank1.pinMode(14, OUTPUT);
    Bank1.pinMode(15, OUTPUT);

    // Bank2.pinMode(15, INPUT_PULLUP);
}

void loop() {
    if (data==0)
    {
        data = 0xffff;
    }
    else
    {
        data = 0x0000;
    }
        Bank1.writePort(data);
    delay(2000);
    Serial.println(data);
}

```

# Answer
So here is what I found five minutes ago.

**I forgot to call MCP23S17::begin()**

Simple that is.

Before that, I tried to rule out a whole lot of other things. It never came to my mind, that I could have missed such a vital initalisation.

What did I do to get to this point?

* removed every other library using SPI
* removed every code using I2C
* removed every code using 1wire
* removed every code using Interrupts
* threw away 9 out of 10 files
* removed 9 out of 10 calls for functions which seemed irrelevant for this problem.

None of these measures did anything to solve the problem. Only when I had my code reduced to the minimum, so I could dare to post it here, the single line caught my attention. So this Q&A is not really a technical or coding riddle but more a didactic play on how one can fool himself and what to do to locate errors.

But in the end I only found the culprit by strictly following Majenko's advice to remove everything until the code started to work again.
> 1 votes

---
Tags: arduino-uno, spi, io-expander
---


title: ATmega328p hangs on USART RX interrupt

text:
# Question
Title: ATmega328p hangs on USART RX interrupt
I was able to use USART without interrupt driven and it worked perfectly! However, when I tried adding interrupt on `USART_RX_vect`, the program does not work as expected anymore.

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

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

I appreciate any help. Thank you.

```
#ifndef F_CPU
#define F_CPU 1000000UL
#endif

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

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

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

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

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

```

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

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

```

Status: Program does not work.

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

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

# Answer
> 2 votes
Just replace `IRS` (Internal Revenue Service) with `ISR` (Interrupt Service Routine).

# Answer
> 3 votes
I suspect if you were a fly you would see your LED flashing very very rapidly.

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

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

---
Tags: interrupt, atmega328, avr, isr
---


title: Video streaming by ESP32

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

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

---
Tags: esp32
---


# Question
Title: More missed messages with longer cables with nRF24L01+?
I am using nRF24L01+ 2.4 GHz transceiver.

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

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

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

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

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

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

# Answer
> 2 votes
the Antenna is interfering with the signals because of its proximity to the point on the bread board where you are connecting the wires, as Majenko said.

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

So, to cure interference:

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

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

---
Tags: arduino-uno, nrf24l01+, wires
---


# Question
Title: Unexpected results and hard crash when modifying and addressing arrays & variables within a struct
I'm trying to use a 2D array inside a struct on my arduino to store sensor readings. I'm having two main problems:

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

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

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

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

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

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

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

//serial print function

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

```

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

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

```

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

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

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

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

# Answer
> 2 votes
You are not specifying a size for your `readings` array:

```
unsigned int readings[][28];

```

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

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

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

```

Or, for dynamic allocation:

```
unsigned int readings[][28];

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

```

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

---
Tags: array, struct
---


title: Format error with ESP8266 compile

text:
# Question
Title: Format error with ESP8266 compile
I get this error when I try to compile and upload the code for the ESP826612E

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

```

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

Anyone has solutions?

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

```
$ sudo apt-get install libc6-i386

```
> 0 votes

---
Tags: arduino-ide, esp8266, core-libraries
---


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

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

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

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

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

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

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

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

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

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

---
Tags: power, usb
---


# Question
Title: How can I know if I can stack some shield on another shield?
Yesterday I tried to stack a motor shield on a servo motor shield already stacked on my Arduino Uno.

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

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

Here are the two shields I use.

wiki : https://www.dfrobot.com/wiki/index.php/Digital\_Servo\_Shield\_for\_Arduino\_SKU:DRI0027

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

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

# Answer
> 4 votes
First you have to compare the pinouts of the two shields. If the shields use completely different pins then yes, you can use them together.

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

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

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

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

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

---
Tags: arduino-uno, shields, servo, arduino-motor-shield, stepper
---


title: Writing on a SdCard

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

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

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

Here, my results on 1Hz sinus with a zoom on the "break":

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

Hope you can help me guys !

# Answer
Possibilities:

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

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

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

---
Tags: sd-card
---


title: Arduino IDE missing libread.s0.6

text:
# Question
Title: Arduino IDE missing libread.s0.6
I just recently installed the ESP8266 libraries on the arduino IDE using the boards manager, the code compiles fine with the ESP, but when the board is changed to UNO, i get this error,

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

```

Any solution to this?

# Answer
So install it?

```
$ sudo apt-get install libreadline6

```

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

```
$ sudo apt-get install libreadline6:i386

```
> 1 votes

---
Tags: arduino-ide, avrdude, core-libraries
---


# Question
Title: MAX7219 powered on via digital pin set to HIGH is not working good (I < 25mA)
I'm using 7-segment 8-digits MAX7219 eBuy module in my battery-supplied ATMega168P project to output some readings. MAX7219 in powerdown mode draws ~150uA (as stated in the datasheet) which is too much for me, because the rest of the circuit draws less than 1uA is sleep mode. So I decided to power off Vcc line for MAX7219 before entering sleep, and power it on just after wakeup.

Current draw for the software-dimmed display module is only 15..19 mA in my case, which is far less than 40mA pin maximum for ATMega168P, so **I connect display Vcc line to one of digital pins and power it on at setup():**

```
void setup()
{
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
}

```

However, display module **works only 1..3 seconds** after starting, then switches off. I checked display Vcc — 4.9V, but the display is off. (I turned off enterng to sleep mode for a while)

This display module doesn't have capacitors C3 and C4 between Vcc and GND (but there's a placeholder for it), recommended in some sources. I solder two capacitors of 100nF and 4,7uF in parallel. It helps only a little: after 1..2 seconds of normal working display shows only digit #0 and in **much higher** brightness than I set (see the photo).

I may only suggest my cheap multimeter is wrong and the display draws much more, but I dont know how to check it. Rset is 10k on this module, btw.

1. Why does it happen?
2. Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

EDIT: If the display is powered directly by controller Vcc it works correctly as expected. It's current draw is 15..20mA.

# Answer
> 3 votes
After some research I eventually solved my problem, so here's the answer.

> 1. Why does it happen?

This LED display draws much more current than I measured on Vcc line between Arduino and display because of **ghost powering** via signal lines (`DIN, LOAD, CLK`). The display (although slightly dimmed) can even run without Vcc line connected! Real current draw was about 30-40 mA with peaks up to 100 mA.

> 2. Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

Yes, by limiting display current draw.

For an unknown reason these cheap MAX7219-driven LED boards has very small current control resistor `RSet` of 10 kOhm, resulting in huge `Iseg` ~= 40 mA. Replacing it by something like 62k will limit per-segment current to ~10 mA.

This is what the datasheet says:

And this is how it can be done:

Works perfectly! Now I can power off LED display completely, so it consumes no current when the device is sleeping.

**NOTE**: it's important to properly re-initialize MAX7219 after power on!

In the colorized table above one could find display current draw for different software-set intensity settings in case of using RSet = 62k. GND line values (blue column) seems to be correct as they well correspond with overall device's current draw (the most correct measurement, I suppose).

# Answer
> 0 votes
Using a led display in a low current application is an oxymoron. An LCD display is more appropriate.

With that said, you can switch the the 7219 from the high side and turn the pins into input mode to avoid ghost powering.

Od mode works but pull up has to be switched as well.

---
Tags: arduino-pro-mini, max7219
---


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

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

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

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

```

And here is how you could use it:

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

```

---
Tags: serial, c++, print
---


# Question
Title: How do I connect a LED strip to a Multiwii SE 2.5?
https://www.m.nu/neopixel/mini-skinny-neopixel-digital-rgb-led-strip-60-led-m-black-pcb-1m

I just purchased this led-strip that I plan to use with my Multiwii SE 2.5.

I power the Multiwii itself via a power distribution board where I connect a 3s LiPo battery. Now I wonder how I would wire my LED strip in order to use it with my Multiwii. I have a few smaller LiPo batteries if I need to power the LED itself (not via the 3s LiPo that powers the Multiwii) but the best solution would of course be to power them together.

I appreciate all help I can get.

# Answer
The led strips I've used with my Naze32 have three connection, +5VDC, GND and DATA. I'm not familiar with your FC but based on the image you provided it looks like you would use one of the two I2C ports. As long as you don't try to run too many LEDs (I've maxed out my FC with 32 LEDs no problem) the +5VDC connection should be able to power the LEDs. Obviously connect LED GND to the FC GND. You'll need to check the docs for you FC to confirm but it would make the most sense to me to connect the FC SDA to the LED DATA. The FC SCL would not be used.

NOTE: If your PDB has a +5VDC output you'd be better off using that one to power the LEDs.

In the picture with the Arduino one of the leads is providing +5VDC. I've read the suggestion for LED strips to place a capacitor across the +5VDC and GND to make it more stable but I don't and I've not had any issues. FYI, the lead to the Arduino is for GND and DATA (being driven by one of the Arduino Digital I/O Pins.
> 1 votes

---
Tags: led, rgb-led
---


# Question
Title: ESP8266 connecting keypad and lcd display
I have ESP8266 type -

I have added a keypad

With a standard lcd display.

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

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

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

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

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

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

---
Tags: esp8266, lcd
---


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

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

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

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

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

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

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

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

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

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

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

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

```

# Answer
> 1 votes
Well, you never call `blink`, so leds never get a chance to light up.

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

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

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

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

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

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

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

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

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

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

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

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

}

```

---
Tags: arduino-uno, programming, led, wires, piezo
---


title: Arduino Micro disappears on osX 10.11.6

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

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

Suggestions?

Thanks!

# Answer
> 0 votes
Found it. It was a weird timing thing, and I had to hit reset as the sketch was uploading. Seems to be fine now.

---
Tags: serial, usb, arduino-micro, osx
---


# Question
Title: How to develop or edit an Arduino library?
I'm not sure if I should split this question in two. I had to edit some libraries and I plan to make some myself but didn't try yet.

Editing a library seems very laborious comared to editing a sketch.

I have to use an external editor and then compile on the Arduino IDE with the help of a test sketch.

I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.

The libraries used to be on %home%/Arduino/libraries/etc. but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries and it seems these packages might get updated so maybe it is not a good idea to edit them there but I am not sure.

What about GitHub and conflicts? I clone the library and edit it but then I have two versions and you can't choose one of them. So I have to delete the original from the arduino instalation or wherever it is to avoid the conflict.

I also wish to post the progress to GitHub and maybe receive collaboration there. Do you have any hint about the clone process or something to avoid any trouble with it?

And what about the .h/.o? Arduino precompile the headers on startup so if I edit a .h I have to find and delete the .o or restart the IDE.

How do you do all of this? Is there any trick that helps?

Thank you.

# Answer
There is one component of your question that remains unanswered:

> I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.
>
> Any good editor if Arduino IDE is not an option? Why is not an option?

The rest of your questions already have good answers so I'll limit myself to explaining how the Arduino IDE 1.6.5-r4 and newer can be used to edit libraries:

Copy the library you want to modify to {sketchbook folder}/libraries or create a new folder at that location if you're writing a library from scratch. You can find the location of {sketchbook folder} at **File \> Preferences \> Sketchbook location**.

Create a file that matches the folder name that contains the source files with the .ino extension. For example:

```
{sketchbook folder}
|_libraries
  |_FooBar
    |_FooBar.ino
    |_FooBar.h
    |_FooBar.cpp

```

or:

```
{sketchbook folder}
|_libraries
  |_FooBar
    |_library.properties
    |_src
      |_src.ino
      |_FooBar.h
      |_FooBar.cpp

```

This dummy .ino file is necessary in order to open the library source files in the Arduino IDE but will not actually be used as part of the library. You can leave it blank. I like to use this file as a "to-do" list for my development work. I add this filename to .git/info/exclude so that it will not be tracked as part of the repository. It's also possible to use this file as a sketch to test the library with. Just remember to use the local file include style:

```
#include "FooBar.h"

```

Note that you will only be able to edit the files that are in the same folder as the .ino file via the Arduino IDE. Luckily most Arduino libraries place all their source files in a single folder so this is not much of a limitation. If you wanted to edit a library that has source files in multiple folders you could always put a dummy .ino file in each folder and open them in separate IDE windows.

Add a file named .development to the library root folder. This is necessary because normally the Arduino IDE does not allow saving to the library folders or the examples folder to prevent accidental modification of the example sketches. Using Windows Explorer (and possibly others), you will find that you are not allowed to create files that start with a dot. You can create the .development file using a text editor or the command line. The contents of the file don't matter, only the presence of the file. Note that you should not publish the .development file to repositories that will be included in the Arduino IDE Library Manager as the file will cause the library to be skipped by the job that fetches releases. I also add this filename to .git/info/exclude.

If the library does not already contain one, add a library.properties file to the library root folder. You can find the correct format of this file in the Arduino Library Specification:

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format

Now the structure of the example libraries above would look like this:

```
{sketchbook folder}
|_libraries
  |_FooBar
    |_.development
    |_FooBar.ino
    |_FooBar.h
    |_FooBar.cpp
    |_library.properties

```

or:

```
{sketchbook folder}
|_libraries
  |_FooBar
    |_.development
    |_library.properties
    |_src
      |_src.ino
      |_FooBar.h
      |_FooBar.cpp

```

Restart the Arduino IDE if it's running.

After doing this, when you open any of the source files of the library with the Arduino IDE, all source files in the folder will be opened and you can edit and save them as you would a sketch.
> 2 votes

# Answer
> I'm not accepting any answer because they are only focused on versioning/git/github fork-\>edit-\>share and I am very interested on all the things that I have to do to make the development.

---

I will run through the basics of making a library. It's really quite simple, and they persist through upgrades to the IDE.

Let's imagine I have a useful function (or lots of functions) that I want to use in lots of sketches. For example, something that blinks an LED:

```
void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

```

And some test code:

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

---

## Make a library

To turn that into a library we need three steps:

1. Make a folder for the library. This should be placed inside the **libraries** folder **in your sketchbook folder**. This folder:

In my case: `/home/nick/sketchbook/libraries`. It does **not** go into anywhere associated with the IDE download.

> but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries

No, **not** there.

I will call my library `blinkLED`. So I make that folder, which is now: `/home/nick/sketchbook/libraries/blinkLED`

---

2. Make a function prototype for any functions your library is going to "expose" to the end-user, and put that into a .h file, like this:

**blinkLED.h**

```
#include <Arduino.h>

void blinkLED (const byte which, const int times);

```

**Important**: You must include `<Arduino.h>` as in the example, or you will get compile errors.

---

3. Put the C++ code into a .cpp file, like this:

**blinkLED.cpp**

```
#include <blinkLED.h>

void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

```

**Important**: You must include the .h file created in step 2, as in the example, or you will get compile errors.

---

That's it! Restart the IDE now so it notices the new folder with the library in it.

Now our test sketch can just use the new library.

```
#include <blinkLED.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

---

## Testing

For testing I just keep the library files open in a separate text editor (I am using Geany these days, but whatever your favourite editor is).

You can make changes to the library source and save them. You **do not** need to restart the IDE if you do this. It will always pick up the latest version.

In the IDE you alter your calling code, upload and test. It is really quite fast and simple.

---

## Git

Once you have put a bit of work into your library you probably want to put it under source control. Using a terminal/command window, navigate to the library folder and put it into a Git repository:

```
git init
git add *.cpp
git add *.h
git commit -m "Initial commit"

```
> 4 votes

# Answer
I am going to split my answer into 2 parts

**1. Editing an Arduino library:**

It **doesn't** matter how you edit your library, you can do it in notepad for all I care. It just doesn't matter.

**2. Version Control:**

Git is a version control software used to track software/code changes and ensure that people don't screw up the files by adding code that's not tested.

If you want to contribute to a certain library here is what you need to do

Step 1: create a github.com account since most people host it there

Step 2: **fork** the required library, this basically creates a clone of the library in your account.

Step 3: **clone** the forked repo from your account to your computer. So now you have the files on your computer to mess around

Step 4: create a **branch** a branch is your personal workspace to mess around as you wish. The advantage of have a branch is that if you screw up. You could always go to the main branch (master) and start over :)

Step 5: once you are done editing and testing and are sure the file is perfect, you **commit** your changes and then you create \**pull request \** with the original author so that he can review your work and if he is happy will accept your change and merge it to master.

Note: read about adding remote to your git repo and fetching from remote repo, once you understand these basics you will understand the power of git :)
> 1 votes

# Answer
This is the common process for all open source projects, not just arduino (example using github svn)

**1. Fork a project**

When you fork a project, you create a separate "project" of your own from the original project on the SVN.

**2. Clone your project**

Clone your fork down to your local directory so you can make changes and use it.

```
git clone https://github.com/<your-repo>/<project>

```

**3. Push changes up**

Push your changes up to your repo regularly. At this point your changes are not affecting the original project in any way.

```
git push -u origin <branch>

```

**4. Pull updates from the original project**

The original author(s) can make changes and improve his/her code. You can make sure your fork is up-to-date by pulling/merging those updates into your fork.

```
git pull https://github.com/<original-author>/<repo> <branch>

```

Some time there will be conflicts, which are normal since your changes and the author's may collide. You'll be prompted to fix the conflicts before committing your changes.

```
<<<<<<< HEAD
    # this portion is your code at the current HEAD
=======
    # this portion is the one from the original branch master
>>>>>>> master

```

You'll have to fix the conflict manually by either accepting your change and deleting the master's or deleting your change, and get rid of the marks before committing to your svn.

**4. Creat a pull request**

After using your supercharged version of the project for a while, you think it might be useful for others. To contribute, you create a pull request to the original author. It works similar to you pulling in his changes, just he will review your changes then merge in.

All the while, others can do all these with your project too!

To edit the project/make changes, you can use any editor to open your local project, code away, save it and commit. It is not ideal to use Arduino IDE since it is an environment to run the code (but otherwise possible).
> 1 votes

---
Tags: library
---


title: can someone please fix this code

text:
# Question
Title: can someone please fix this code
there is something wrong with this code logic and i can't put my hand on it so if any one can fix i would really appreciate it Basically the code is used to receive couple of char from Bluetooth or serial monitor combine them together in an array then print this array then search for ":" in this array and atoi them into two different integer IE (50:90) will be (50) and (90) in two different integer that are then used to control the direction and the speed of a motor

```
//motor a
int enA = 9;
int in1 = 8;
int in2 = 7;

//motor b
int in3 = 5;
int in4 = 4;
int enB = 3;
char data[32]; // Allocate some space for the string
char inChar; // Where to store the character read
byte index = 0; // Index into array; where to store the character

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(enA , OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
  pinMode(enB, OUTPUT);
  Serial.println("\n String conversion testing");
}

void loop() {

if(index < 31) // One less than the size of the array
      {for( int i = 0; i < sizeof(data);  ++i )
          data[i] = (char)0;

          inChar = Serial.read(); // Read a character

          data[index] = inChar; // Store it
          index++; // Increment where to write next
          for( int i = 0; i < sizeof(data);  ++i )
          Serial.println (data);

      }
    char* command = strchr (data, ":");
    if (command !=0)
    {
      *command = 0;
      int direc = atoi (data);
      ++command;
      int speeds = atoi (command);
      Serial.println(speeds);
      Serial.println(direc);
     int s;
     s = map(speeds, 0, 100, 0, 255);
    if (direc >= 85 &&direc <=100 ){//odam
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
    }

      else if (direc >=260 && direc <=280){  //reverse
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
      }

     else if (direc >=350 && direc <=360 | direc <=10 && direc >=0){ // RIGHT
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
     }

      else if (direc >=170 && direc <=190){ // LEFT
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
      }

      else if (direc >=120 && direc <=150){ //FORWARD LEFT
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
      }

      else if (direc >=30 && direc <=60){ // FORWARD RIGHT
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
      }

     else if (direc >=210 && direc <=259){ // BACKWARD LEFT
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
     }

     else if (direc >=300 && direc <=340){ // BACKWARD RIGHT
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
     }

      else{ //If bluetooth module receives any value not listed above, both motors turn off
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,0);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,0);
      }
    }
  }

```

# Answer
```
      inChar = Serial.read(); // Read a character

      data[index] = inChar; // Store it

```

The above is almost certainly not going to work as expected. You need to check if there is serial data available before reading it. (ie. call `Serial.available()`).

I have a page about reading from serial that might help you with that.

For example, your loop might look like this:

```
void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

```

Notice that the `Serial.read` is only done if `Serial.available` is true?
> 0 votes

---
Tags: serial, c++
---


title: Sensor for turning rail direction

text:
# Question
Title: Sensor for turning rail direction
I am trying to control an actuator carrying a carriage made from stepper motor. My problem is that after the carriage reach certain height, I want it to delay for several minutes and change direction to move the other way around.

Any suggestion on what sensor to use? I tried to use EndStop switch like the one in 3D printer but I haven't found any luck as it simply cuts the electronic connections once the carriage hits it.

# Answer
> 0 votes
If you are using a microprocessor, specifically an Arduino, then what you need to do is send the signal from the 'switch' (as defined by Mark Smith) into a digital input port and then let the Arduino make the electronics pause before reversing. From you post it sounds like (and I am probably wrong) you have put the switch in between the power source and the actuator.

(Diagram by Majenko)

---
Tags: sensors, arduino-motor-shield, stepper
---


title: Preprocessing problem

text:
# Question
Title: Preprocessing problem
I've a little problem, I'm trying to create a library with processor variables for tune it.

So in `.ino` I declared my preprocessor var, but preprocessor variables appear not defined in my library. (Notice that I've create a folder `test/test.h` in `libraries` directory of Arduino IDE)

Some code to reproduce the problem :

**test.ino** :

```
#define TEST

#include "test.h"

void setup() {}
void loop() {}

```

**test.h** (edited, reverse error message, this is solution)

```
#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

```

If I compile it, I fall on `#error "NOT DEFINED"`.

Somebody with an idea ?

Have a good day

# Answer
The code is working properly. You have mixed up your error messages. The code should be:

```
#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

```

UPDATE: The question was edited after the time of this answer to correct the mixed up error messages.
> 0 votes

# Answer
Please, start by reading the Writing a Library for Arduino Tutorial. That will solve your question.
> 0 votes

---
Tags: c++, library, c, compile, c-preprocessor
---


# Question
Title: getting " .error: failed sending 1116 bytes warning: espcomm_send_command: didn't receive command response"
I'm getting error while uploading sketch into nodemcu ch340g as shown below

I have tried these things to rectify the error
1) Changed usb cable
2) changed the port
3) flashed the firmware with nodemcu\_float\_0.9.6-dev\_20150704.bin by esptool.py
4) flashed with nodemcu flasher
But no change at all and it is showing same error only what can i do now

# Answer
> 3) flashed the firmware with nodemcu\_float\_0.9.6-dev\_20150704.bin by esptool.py

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

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

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

---
Tags: nodemcu, flash
---


title: LM35 readings are erratic

text:
# Question
Title: LM35 readings are erratic
My son just did the Love-o-meter project in the Arduino Start Kit. However, the sensor readings of the LM35 temperature control vary widely. Below is a sample. What could be wrong?

```
Sensor Value: 217, Volts: 1.06, degrees C: 105.96
Sensor Value: 587, Volts: 2.87, degrees C: 286.62
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 320, Volts: 1.56, degrees C: 156.25
Sensor Value: 445, Volts: 2.17, degrees C: 217.29
Sensor Value: 141, Volts: 0.69, degrees C: 68.85
Sensor Value: 510, Volts: 2.49, degrees C: 249.02
Sensor Value: 247, Volts: 1.21, degrees C: 120.61
Sensor Value: 168, Volts: 0.82, degrees C: 82.03
Sensor Value: 595, Volts: 2.91, degrees C: 290.53
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 206, Volts: 1.01, degrees C: 100.59
Sensor Value: 606, Volts: 2.96, degrees C: 295.90
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 290, Volts: 1.42, degrees C: 141.60
Sensor Value: 487, Volts: 2.38, degrees C: 237.79

```

Here's the code:

```
const int sensorPin = A0;
const float baselineTemp = 25.0;

void setup(){
  Serial.begin(9600); // open a serial port
  for(int pinNumber = 2; pinNumber<5; pinNumber++){
    pinMode(pinNumber,OUTPUT);
    digitalWrite(pinNumber, LOW);
  }
}

void loop(){
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);
  // convert the ADC reading to voltage
  float voltage = (sensorVal/1024.0) * 5.0;
  Serial.print(", Volts: ");
  Serial.print(voltage);
  Serial.print(", degrees C: ");
  // convert the voltage to temperature in degrees
  float temperature = (voltage) * 100;
  Serial.println(temperature);

  if(temperature < baselineTemp){
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+2 &&
    temperature < baselineTemp+4){
    digitalWrite(1, HIGH);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+4 &&
    temperature < baselineTemp+6){
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+6){
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
  }
  delay(1);
}

```

The GND is connected to the left most connector in the LM35, the A0 to the middle, and the power to the right most connector.

# Answer
> 1 votes
I've had a look round and spotted this:

https://electronics.stackexchange.com/questions/117970/why-is-my-analog-temp-sensors-signal-so-unstable

In summary it says that the fault maybe that the Arduino's 5V isn't stable enough, so you need to decouple it. For once it seems that running from batteries may have been a better idea.

I've also seen posts saying there should be a 500Ohm resistor between the Ground of the LM35 and Ground. Apparently it says 499Ohm on the datasheet.

And as a final resort I saw said that the 'Data Direction Register' influenced the analog pins. If it was set to digital output this could lead to unstable readings for the ADC. Basically it implied you needed to set the analog pin's to `pinMode (A0, output)`. **But I really don't think this will work**

---
Tags: sensors, lm35
---


# Question
Title: Arduino Pro Mini maximal and recommended current per pin
In Arduino Pro Mini (3.3V) specs indicated the maximal and recommended current per pin, 40mA and 20mA respectively. Does these values means *input* current (i.e. safe input current Arduino can handle) or *output* current?

# Answer
It is the amount of current the pin can *source* or *sink* when in OUTPUT mode.

That is, the amount of current that can flow from the pin to ground, or can flow from VCC into the pin.

You can understand it better if you learn how a GPIO pin works.
> 4 votes

# Answer
In datasheet, paragraph 32.1 is stated:

```
DC Current per I/O Pin 40.0mA

```

See comments below about the implication. (I will not delete this questions because of the useful comments below from Majenko and Milliways, unless downvoted).

See:
> 0 votes

# Answer
> Does these values means input current (i.e. safe input current Arduino can handle) or output current?

Depending on your definition of input.

The numbers are the max current that an output pin can provide , either flowing in or out of the pin.

The max current you can force into or out of an input pin is mostly determined by the clamp diodes. Typical a few ma.
> 0 votes

---
Tags: arduino-nano, voltage-level, current
---


# Question
Title: is it possible to program an arduino with usb/ttl adapter
i want to upload sketch into arduino uno using usb/ttl adapter.i tried searching for it, but found about programming arduino using another. can anyone help me.

# Answer
> 6 votes
The Arduino onboard USB to serial is connected to D0 (Rx) and D1 (Tx).

And without a USB connected to the Arduino you can use a USB/TTL adapter connected to D0 and D1 like this;

```
Arduino  - USB/TTL
Tx       - Rx
Rx       - Tx

```

And to get the Arduino inte "programming" mode:

* Automatic way, if the USB/TTL have CTS, connect it to Arduinos reset pin.
* Manual way, press the reset button when the Arduino IDE starts to upload the code.

# Answer
> 1 votes
The Uno is normally programmed by its on-board USB adapter.

The Pro Mini does not have an on-board adapter, and is normally programmed with an external USB/serial adapter. This should also be possible with Uno.

---
Tags: arduino-uno, programmer
---


# Question
Title: Using all ten capacitive touch inputs on the ESP32
I am using a Wemos Pro ESP32 development board and would like to be able to use all ten of the available capacitive touch inputs. I am able to get readings from nine of them but not T1. Here is the pin diagram for the board I have.

*Running this code on my board produces no difference in reading for T1...*

```
#define numTouchPins 10
byte touchPins[] = { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9 };
byte touch[10] = {};

void setup() {
    Serial.begin(115200);
    delay(1000);
}

void loop() {
    for( byte pin = 0; pin < numTouchPins; ++ pin ) {
        touch[pin] = touchRead( touchPins[pin] );
    }
    for( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print( "\t" );
    }
    Serial.println();
}

```

So the reason for this is that T1 is on GPIO0 which is also connected to a button labeled 0 on the board. Now I realise this is needed in order to select between the ROM serial bootloader mode and the normal execution mode... But, **is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?** Is there something I can write in the Arduino setup() method that would make this pin behave like the other touch pins?

# Answer
> 1 votes
> is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?

You already are. However it will make no difference since that pin is connected to external hardware - namely the button and a pullup resistor.

You cannot have touch inputs connected to anything else. The only way to get the touch to work on that input is to physically remove the pullup resistor and even maybe the button. Touch inputs are "touchy" about what else is connected since even a button that's not connected to anything else can effect the capacitance on the pin.

---
Tags: sensors, arduino-ide, pins, port-mapping, esp32
---


title: Humidity sensor for wet environment

text:
# Question
Title: Humidity sensor for wet environment
I've had a bit of experience with DHT11/DHT22 sensors in a greenhouse environment, and believe that when they get wet they stop working altogether.

Are there any low cost humidity sensors that I can hook up to an Arduino that don't suffer from this problem, or is there a way to protect these sensors from damage when near water? (I'm not talking about immersing them in water - but do expect condensation to get sprayed with water and/or get condensation on them from time-to-time).

Am I correct that the SHTxx sensors are able to withstand this kind of abuse, and that these sensors are about 5-10 times the cost of DHT sensors? (I did not want to spend that much, but if it's the only possibility I might consider it).

# Answer
> 2 votes
**2022 UPDATE**: After ~5 years since I wrote this answer, I'd like to mention that I don't like BME280 anymore, because of its (1) inaccuracy and (2) requirement to make some non-trivial computations to get real values from sensor's data. If you already got a BME280 and your project requires only approximate values of temperature/humidity, it will work, go ahead. Otherwise, consider using **SHT3x**!

See also this, this, and especially this one.

Original answer:

---

I'd consider using **Bosch BME280** digital sensor. Although it's a bit expensive, it has very good sensitivity, precision and *amazingly* fast response for humidity changes (for ex. in my project it detects dry human hand lying in 2" away within a 1-2 seconds).

So its features make possible to put it into an enclosure to avoid direct water contact with water spays and it'll still be very responsive for greenhouse needs, I suppose. Datasheet warns:

> Liquids shall not come into direct contact with the device.

Also, I'd use electronic-friendly protective acrylic lacquer (Plasticote 70 for instance) and put two layers to sensor's PCB, avoiding small black tiny vent hole on the chip itself:

**UPD**: Here's DHT11 with cover removed:

It *might be* the easiest and cheapest solution to cover all internal contacts and IC (avoiding humidity sensor's stripes) of DHT11 with Plasticote 70.

---
Tags: sensors
---


# Question
Title: How to burn the bootloader onto a bare chip without using an Arduino board
How do I burn the UNO bootloader onto ATMEGA328P-PU without using an Arduino Uno board. That is burn directly from my PC or Android device??

I've tried nothing, I don't know a thing about microcontrollers ☺

# Answer
The short answer is, you need a **AVR programmer**

It is a tutorial on the Arduino website:

https://www.arduino.cc/en/Main/Standalone

And the section *Bootloading your chips OPTIONAL* will answer the question.
> 1 votes

---
Tags: arduino-uno, bootloader
---


# Question
Title: LinkNode D1 Serial stops working when using pinMode
The following code works. I get an output in the console every second of "Hello" and then the `analogValue` of the photoresistor.

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

int lightSensorPin = A0;
int analogValue = 0;

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

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

```

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

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

int lightSensorPin = A0;
int analogValue = 0;

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

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

```

Any idea what might be going on?

# Answer
> 1 votes
Move **int greenLedPin = D1;** and **int redLedPin = D3;** to another pin, because D1 and D3 is Tx and Rx.

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

---
Tags: esp8266
---


# Question
Title: Duplicate libraries while compiling for ESP32 in the Arduino IDE
I have just added the ESP32 toolchain to the Arduino IDE (v1.8.0) on Windows 10. To get the IDE to allow me to select ESP32 chips I had to place the Espressif folder in "D:\Program Files(x86)\Arduino\hardware" (Yes my C drive is called D, its a long story)

I managed to compile and run Blink and after several minutes of celebration I tried the ESP32 Example Wifi-\>WifiScan. It failed to compile because

```
WARNING: Category '' in library OneWire is not valid. Setting to 'Uncategorized'
In file included from D:\Program Files (x86)\Arduino\libraries\WiFi\src\utility\spi_drv.cpp:21:0:

D:\Program Files (x86)\Arduino\libraries\SPI/SPI.h:16:26: fatal error: avr/pgmspace.h: No such file or directory

compilation terminated.

Multiple libraries were found for "WiFi.h"
 Used: D:\Program Files (x86)\Arduino\libraries\WiFi
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\WiFi
Multiple libraries were found for "SPI.h"
 Used: D:\Program Files (x86)\Arduino\libraries\SPI
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\SPI
exit status 1
Error compiling for board ESP32 Dev Module.

```

If I am reading this correctly, there are a couple of duplicate libraries, Arduino versions and ESP32 versions and the IDE picked the Arduino versions.

Is there a way of telling the IDE to prefer the ESP32 libraries rather than Arduino ones? I suspect all I need to do is change the order of the -I and -L commands, but I don't have a clue how, or if that's the right thing to do.

# Answer
`#include "filename.h"` will look in the sketch folder

`#include <filename.h>` will look in the path, defined in *File* | *Preferences*, edit **preferences.txt**, search for sketchbook.path
> 1 votes

# Answer
The problem is that you have incorrectly installed the ESP32 hardware package. If you look at the official installation instructions:

https://github.com/espressif/arduino-esp32/blob/master/README.md#installation-instructions

you'll see that the architecture folder should be named **esp32**, not **ESP32** as you have named your folder.

When multiple libraries contain a header file of the same name, one of the factors the Arduino IDE uses to decide which gets precedence is architecture matching. The architecture of the selected board is determined by the name of the architecture folder of the hardware package of that board. So because you named your architecture folder **ESP32**, that's the architecture value of the selected board. The architecture of the library is determined by the `architectures` property value found in the library.properties file of the library. In this case that value is set to `esp32`:

```
architectures=esp32

```

So because the architecture value of the library in the ESP32 hardware package doesn't match the architecture of the selected board, the SPI library found in the Arduino IDE installation folder is used instead.

If you rename the architecture folder to **esp32** the correct library will be used.

A few other notes:

For some reason you have put a copy of the SPI library at D:\Program Files (x86)\Arduino\libraries\SPI. This makes no sense because that library is architecture specific. Each hardware package has its own version of the SPI library bundled.

In addition to using the incorrect architecture folder name in your installation of the ESP32 hardware package, you installed it to the Arduino IDE installation folder instead of the sketchbook folder, as recommended in the instructions.

You seem to have a bad habit of messing with your Arduino IDE installation folder. You should never modify or add files to the Arduino IDE installation folder. The reason is that all changes you make to that location will be lost anytime you upgrade to a new version of the Arduino IDE and it also makes troubleshooting more difficult since you are working with a non-standard installation. Instead you should always install libraries and hardware packages to the sketchbook folder where they will persist through IDE updates. I recommend you to move any customized files out of the Arduino IDE installation folder and then reinstall the IDE to make sure you are working with a stock installation.
> 0 votes

---
Tags: arduino-ide, compiler, esp32
---


# Question
Title: Connecting Arduino to PC through Slimline SATA instead of USB?
I removed the DVD-RW from my laptop and want to use the new area as an IO port instead. There is an Arduino Nano with me which can fit into the emptied out drive space and there are some easy to connect IO headers with me.

The only (major) problem is how can i connect the Arduino to the slimline SATA port of the DVD drive. There are some SATA to USB converters available in the market, but will they work? (as i am trying to connect it the other way around)

Is there any possible way to connect the Arduino to the SATA port, and even if i would be able to connect it, would i be able to use it as a regular Arduino as if it were connected to a USB port?

# Answer
> 1 votes
No, there is no way of connecting an Arduino to a SATA port. You require USB or UART. SATA is a specific dedicated port, whereas USB is, as the name suggests, *Universal*. So USB can become SATA but SATA can never become USB.

---
Tags: serial, arduino-nano, usb, convert
---