# Question
Title: How to compile Arduino ESP8266/32 on CI/CD (CLI shell cmd) platform?
Like make for not ESP Arduino target, is there a CLI command like **esptool.py** to upload in the hardware ?

I've seen **makeEspArduino** but seems to be not trivial ?

What about **espressif ESP32** component ?

Is **Visual Micro** Arduino CLI (Command Line Interface) tool mature ?

# Answer
> 1 votes
Easiest answer: Use PlatformIO. (Yes this answer is technically an advertisement, but it *is* the correct solution here.).

*Why not the others?*

* `makeEspArduino` is dependent on GNU `make`, hard to make modification to, hard to get support for when something goes wrong
* Visual Micro Arduino is Visual Studio extension, thus native to Windows

*Why PlatformIO?*

On the other hand, PIO is just a framework written in python2, runs on Windows, Mac & Linux alike and supports tons of boards and frameworks. Not only is it OS-agnostic but it also IDE agnostic. It exports project files for Eclipse, Visual Studio Code, CLion, Visual Studio, Sublime, Atom and other IDEs. The Arduino IDE will always be only a (bad) syntax highlighter.

Support boards (479 of them) range from Arduino Unos to ESP8266/ESP32 over to STM32 and nRF boards. It's also possible to compile one firmware for different environments (board), so with a well-written firmware, PIO can generate firmwares for multiple boards and frameworks alike. Frameworks include Arduino cores, ESP-IDF, STM32HAL and more.

To create a new project, you'd do

```
user@somefolder/$ pio init --board=nodemcuv2 --ide=vscode

```

To compile from CLI, you just have to execute the `run` target:

```
user@somefolder/$ pio run

```

To upload you'd just

```
user@somefolder/$ pio run -t upload

```

With optional `--upload-port=/dev/ttyUSB0` or alike. Updating wirelessly over ArduinoOTA is also supported.

Video: https://www.youtube.com/watch?v=EIkGTwLOD7o

Documentation: http://docs.platformio.org/en/latest/

---
Tags: esp8266, esp32, command-line
---


# Question
Title: Connect BotBoarduino with servos and Ultrasonic sensor HC-SR04
I am new to Arduino and I am making a Walking Quadruped using BotBoarduino as microcontroller. I want to install an Ultrasonic Sensor HC-SR04 so that it will stop when an obstacle is detected. I have connected the sensor to Arduino UNO. RX-TX of both the boards are cross-connected. Now I have written this code for UNO:

```
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  Serial.println(distance);

  delay(200);
}

```

And I am doing this on BotBoarduino:

```
int byteRead;

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

void loop() {
  while (Serial.available())
  {
    byteRead = Serial.read();
  }

  if(byteRead >= 10)
  {
    walk();
  }
  else
  {
    stand();
  }
}

```

Whenever distance = 10 or above, let it walk. Else stop.

But it's not working. It's not stopping on obstacles. Sensor is doing its work perfectly, but I think Botboarduino is not getting the values.

Any idea guyz?

# Answer
You have a misconception, how the Serial interface works.

The Serial interface is basically a stream of bytes (and sometimes start/stop and parity bits, which you normally don't care about) without any structure. This has to be implemented by you.

Also you have to understand, that you don't and cannot know, when a specific byte actually is being send. The fact that you typed a complete string into the serial monitor (or send a string via one call for `Serial.println()`) does NOT mean, that they are transmitted as a complete packet. The bytes of the string are send one after another and there may be a short delay between two arbitrary bytes. So with your reading `while()` loop, you are reading bytes until there is a delay long enough for the microcontroller to notice or until the message is send complete. You cannot know, which is the case for this very specific transaction. Also it seems odd, that you are only using the last read byte in your code, since the variable `byteRead` is overwritten on every `while()` loop cycle.

Then there is the format, in which you can send data through Serial.

1. **Binary data:** Since it is a byte stream, you can directly use the binary values of the bytes to reflect the data. This is easy and good for cases, in which only one value of the size of one byte is transfered every time. So there is no need to distinguish between different parts of the message. In this case you have to use `Serial.write()` on your sending end. This will write binary data. (You will not be able to see the values in your serial monitor, since it is displaying only ASCII-encoded characters).
2. **ASCII-encoded data string:** You are using `Serial.println()`, which sends an ASCII-encoded string representing the data followed by a NEWLINE character ('\n'). In case of the value `10` you are currently sending 3 bytes: '1', '0', '\n'. In this method, you are using a delimiter character (in this case '\n') to mark the end of a message. On the receiving end you have to read all bytes into a buffer, until you are receiving the delimiter character. Then you can process the message as a whole. In your case you would convert the ASCII-encoded string into an integer variable (for example with the function `atoi()`)

To exactly explain, what is happening with your code: As Chad wrote in his comment, you are trying to use the binary value of a byte, that is an ASCII-encoded character. When looking at an ASCII table, you can see, that there is no printable character with a binary value under 10. So, since you send only printable characters with `Serial.println()`, There will never be a value, that is under 10.

So now you have 2 options:

1. Send the variable as binary data in one (!!!) byte (since you are not using distances as big as 255cm the value can fit in there; just make sure, that the byte variable does not roll over) and use every read byte on the receiving end for your code.
2. Send the variable as ASCII-encoded data with `Serial.println()` and do the correct processing of the resulting message on the receiving end. Refer to the Serial examples in the Arduino IDE for this. You can directly integrate their code into yours.
> 0 votes

---
Tags: c
---


# Question
Title: serial communication between arduino to 89c51 with gsm
I need to connect the 89c51 with Arduino UNO but same time I need to connect 89c51 microcontroller with Arduino without using serial reception and transmission pins of UNO b'coz that pins already engage with GSM module. plz, suggest me the program solution to serially receive data from 89c51 and send the message to gsm module.

# Answer
The Arduino Uno only has one (hardware) serial port. Since you need two, you have in principle two solutions:

* Use a software serial, this will work only for low speed transmissions. You can download this as a library.
* Use an Arduino (or other microcontroller) which has more than one hardware serial port, like the Arduino Mega which has 4.
> 2 votes

---
Tags: arduino-uno, serial
---


title: Linking Mulitiple Arduino's

text:
# Question
Title: Linking Mulitiple Arduino's
I have a project in which several Arduinos will be running independent programs. I would like to use an Arduino Mega as the main controller. It will receive input from a variety of switches, as well as data input from 2 Arduino Unos and 3 Arduino Nanos.

Each Nano will run a basic collection of switches and LED displays.

Each Arduino Uno will be connected to a 2 axis joystick and will have several button inputs from the joystick, as well as several 7 segment Led displays and several LED indicator displays.

The Mega would need to gather information of at least 16 bytes from each slave at highest possible speed, and be able to transfer at least 16 bytes to each slave at the same rate. I would also need the clock signal for all devices to default to the Mega.

What would be the best way to begin setting up the program logic to get these boards to interact in a smooth manner without a lot of lag in communication between boards?

Also, what would be the limitations on speed with this sort of com setup between the boards?

If more setup or function information is needed I can add description, just didn't want this post to be overly lengthy.

# Answer
> 4 votes
Why do you need so many Arduinos, Nanos and a Mega? You want to read/control 2 joysticks, some switches and some LED. If you do this using a multi-processor environment then you are adding a significant overhead to the processing and the development time which you can probably do without.

So, could you connect everything to a Mega, do you have enough IO pins? If not would the use of GPIO expander ICs, I2C devices, etc help solve this issue.

Connecting the joysticks via interrupts will allow a more responsive system, can you do this?

Is an Arduino even the best platform for this? What about an ESP32 or PI?

You want to minimise the comms overhead, so a star network would be better than a ring.
Serial is going to be the lowest programming overhead solution, but by far the slowest. Using WIFI via an ESP8266 is going to be the simpelist and you can hand off some of the processing to the ESP.

---
Tags: arduino-uno, arduino-mega, arduino-nano
---


# Question
Title: How to control 6 servo motors with an Arduino Mega board?
I am trying to make autonomous hexapod with an Arduino Mega board. I have followed tripod mechanism of hexapod movement. First I could control simultaneously legs (0, 2, 4) and (1, 3, 5) separately but whenever I tried to combine both i.e control 6 legs at a time I could not see any movement in the hexapod. Even in the IDE I am not getting any error.

I have connected the legs (0 to 5) to signal pins (2 to 7) respectively. I have connected a common +5v voltage and common ground voltage to individual legs using a breadboard. Can anyone give me a proper solution to overcome this issue and further would like to know how to control multiple servos and source code for it?

Here is my Arduino source code for controlling 6 servo motors.

```
#include <Servo.h>
Servo myservo[6];
int f=0;// create servo object to control a servo
//[0] -tibia , [1] -femur , [2] -coxa motors
void setup() {
  myservo[0].attach(2);
  myservo[1].attach(3);
  myservo[2].attach(4);
  myservo[3].attach(5);
  myservo[4].attach(6);
  myservo[5].attach(7);
}

void loop() {
  //alternatively making hexapod stand at its place
  //f is just flag variable to make it stop
  if(f==0) {
    myservo[0].write(130);
    myservo[2].write(130);
    myservo[4].write(90);
    myservo[1].write(130);
    myservo[3].write(90);
    myservo[5].write(0);
    f=1;
  }
}

```

Note the values that are added above are calculated separately for individual legs to mount legs on ground.

# Answer
The Arduino Mega can handle at most 40mA on the I/O pins, and 200mA on the 5V/GND pins. Six servos will draw far more current than the max of 200mA. You could try hooking up the servo power to a separate power source and the data pins to the Arduino. Hope this helps!
> 2 votes

# Answer
in the odd case that you are actually powering your (small?) servo's directly through the arduino : you'll need an external power source for your servo's.
> 1 votes

---
Tags: arduino-mega, arduino-ide
---


# Question
Title: Help with my project on motors using the Arduino Board
I was given the task of being able to drive two motors in the forward direction, able to drive two motors in the reverse direction, and they must be able to drive each motor independently. I was wondering if anyone can give me directions, advice, or tips on the coding for this task. All I know is that: if(switchState == HIGH){ digitalWrite(motorPin, HIGH); } else{ digitalWrite(motorPin, LOW); } } I know this code makes the motor turn on and off with the high and low, but what type of code do I use to make it work at a certain speed, and to move independently?

# Answer
> 1 votes
you can use PWM function of digital pins (analogWrite())to control the motor speeds as desired.

---
Tags: arduino-uno
---


# Question
Title: Why is Arduino Pro Mini not powering this LED?
First off, I'm very new to Arduinos and electronics in general, so feel free to explain like I'm 5.

As a bit of background to this question, the project is simply using a Pro Mini to run a servo, with a button to turn it on and off, and an led to indicate when it's on. To make sure I was getting the button right, I built the circuit on a breadboard with just the button and LED. The button was supposed to switch the LED on and off. It did not.

I removed the button from the equation and **just tried to power the LED with the Mini. No go.**

It's a **blue LED**, so the **resistor (100)** was chosen **assuming a forward voltage of 3.3V and current of .02A**. **I've tested the resistor and LED combo** with JUST the battery pack, and it lights up bright like it should.

I have a **9V battery running into RAW** (I've also tried a 6V pack). I had **pin 2 as an output with digitalWrite(HIGH)**, running into the resistor, then into the LED (+, long end), and then back to a ground pin. I've tried other ground pins on the board to make sure it's not that. **I've switched pin 2 to analogWrite(255)**, still nothing. **I have tried connecting it to VCC** instead. Nothing.

However, **writing HIGH to the onboard LED works fine**, so I can see that the sketch is indeed running.

**I've verified the LED polarity. I have tried a different Pro Mini**. Nothing. It's a **Pro Mini 328P** according to the stamp on the back, which **Google says runs at 5V and 16 MHz**.

Please tell me what stupid mistake I am making so I can stop wanting to rip my hair out. Thank you.

# Answer
> 1 votes
This was my mistake. I had attached the Arduino to the breadboard by pushing in the provided pin strips, and then putting the mini on top of those, assuming that since the pin was through the hole and looked to be touching, a connection was made. It wasn't.

Rather than continue to mess around with fiddly connections, I just took the plunge and soldered the entire thing to a circuit board. The LED and the button work perfectly as expected, and now I just need to attach the servo.

---
Tags: led, arduino-pro-mini, arduino-mini
---


# Question
Title: Change RF Receiver Frequency by Antenna Length
This may be a very stupid question, but I have got me one of those cheap 433 MHz RF modules for the Arduino. I'm wondering if I can vary the receiver's frequency by simply changing the length of the antenna? Or does the circuit limit the frequency band to 433 MHz?

Thanks in advance.

# Answer
No, changing the antenna length will only change the resonant frequency of the antenna circuit. That is, it will affect the sensitivity of the receiver, but won't actually change the frequency that the receiver "listens" to.
> 5 votes

---
Tags: rf
---


title: Sending dynamic data to webserver

text:
# Question
Title: Sending dynamic data to webserver
I am trying to send data to a php file via http GET method.

I am able to send static data but I am unable to send dynamic data.

```
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(9, 10);

char inchar;
int ledPin = 13;
int sensorPin = A0;
int sensorValue = 0;

boolean gs = true;
boolean es = true;
boolean ss = false;

void setup()
{
  gprsSerial.begin(9600);
  gprsSerial.println("AT+CNMI = 2,2,0,0");
  Serial.begin(9600);
}
void loop()
{
   currentMillis = millis();
   if(gprsSerial.available()>0)
  {
    inchar = gprsSerial.read();
    if (inchar == '#')
    {
      delay(10);
      inchar = gprsSerial.read();
      if (inchar == '1')
      {
        Serial.println("System Enabled");
        ss = true;
        snd_msg(0);
      }
      else if (inchar == '0')
      {
        Serial.println("System Disabled");
        ss = false;
        snd_msg(1);
      }
      delay(10);
      inchar = gprsSerial.read();
      if (inchar == '1')
      {
        Serial.println("Geofence Enabled");
        gs = true;
        snd_msg(2);
      }
      else if (inchar == '0')
      {
        Serial.println("Geofence Disabled");
        gs = false;
        snd_msg(3);
      }
      delay(10);
    }
  }
    gprs();
    delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}
 void snd_msg(int a)
{
  gprsSerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  gprsSerial.println("AT+CMGS=\"+918148090646\"\r"); // Replace x with mobile number
  delay(1000);
  if ( a == 0)
  {
    gprsSerial.println("System Enabled");
  }
  else if ( a == 1)
  {
    gprsSerial.println("System Disabled");
  }
  else if ( a == 2)
  {
    gprsSerial.println("Geofence Enabled");
  }
  else if ( a == 3)
  {
    gprsSerial.println("Geofence Disabled");
  }
  delay(100);
   gprsSerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  gprsSerial.println("AT+CNMI = 2,2,0,0");
  delay(1000);
}
void vibra_sensor()
{
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  for(int i = 0; i < 5; i++)
  {
  if (sensorValue > 500)
  {
    es = true;
    break;
  }
  else
    es = false;
  delay(500);
  }
  delay(1000);
}
void gprs()
{
  vibra_sensor();
  Serial.println("Config SIM900...");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // attach or detach from GPRS service
  gprsSerial.println("AT+CGATT?");
  delay(100);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(2000);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"www\"");
  delay(2000);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=1,1");
  delay(2000);
  toSerial();
  // initialize http service
  gprsSerial.println("AT+HTTPINIT");
   delay(6000);
   toSerial();

   // set http param value
 **gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=ON\"");**
   delay(5000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(1000);
   toSerial();

   gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
   gprsSerial.println("AT+CNMI = 2,2,0,0");
  delay(1000);
}

```

**What I've Tried**

1.) Saving URL in a string

```
String URL = "adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=";
    URL += ss;
    gprsSerial.println("AT+HTTPPARA=\"URL\",\"+URL\"");

```

Doesn't Work

2.)Attaching values using print statement

```
gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=");
gprsSerial.println(ss+"\"");

```

3.)Entering value directly in URL

```
gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="+ss+"\");

```

**Error**

```
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

```

I'm using an arduino uno and a sim 900a GSM module.

**QUESTION**

How do I send dynamic values for **gfence, sstatus, estatus**?

I am also using a messaging service, the code is included. **The help I need is in the gprs() function.**

The data I need to send is,

gfence from gs

sstatus from ss

estatus from es

# Answer
> 1 votes
You should split it up:

```
gprsSerial.print(F("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="));
gprsSerial.print(ss);
gprsSerial.println(F("\""));

```

Note the use of `print` on each part up until the *last* part which is the only one that uses `println` in order to terminate the line.

Also note the use of the `F()` macro to reduce the wastage of RAM that string constants cause.

---
Tags: arduino-uno, gsm, web-server
---


title: Replace Wire library with TinyWireM

text:
# Question
Title: Replace Wire library with TinyWireM
I want to integrate Pololu's vl53l0x Time of Flight distance sensor into a project of mine. They created a library to interface with the vl53l0x over I2C, which works great on my Uno. The only problem is that Wire.h doesn't work on the ATtiny85.

TinyWireM is a replacement library for Wire that I think would be compatible. My question is this: how can I go about replacing all the calls to the Wire library with calls to the TinyWireM library? Is it as simple as replacing all instances of Wire with TinyWireM? Is there anything else I need to do to make the library ATtiny85 compatible?

Thanks!

# Answer
In fact, there would be nothing to do now I guess, as TinyWireM is now included tiny boards packages.

If you just include Wire as usual, it should work as on an UNO. Except for setting a different clock, if I remember well, it is fixed to 400kHz.
> 1 votes

# Answer
I can't guarantee it will work, but it is probably possible to just modify the library. You can find the source code for that ToF sensor library here:

https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp

The first step is to find the reference to *Wire.h* (line 7 in that file) and change it to *TinyWireM.h*. After that, you would need to find the functions that call the *Wire* library and replace them with the appropriate *TinyWireM* functions instead. Those begin at line 284 (`Wire.beginTransmission(address);`). You can find the source code for TinyWireM here (which should tell you all of the functions in the library):

https://github.com/adafruit/TinyWireM/blob/master/TinyWireM.cpp

So `Wire.beginTransmission(address);` would become `TinyWireM.beginTransmission(address);` and `Wire.write(reg);` would become `TinyWireM.send(reg);`

I'm not sure if that's all of the solution, but I think that's a good start.
> 1 votes

---
Tags: sensors, library, attiny, wire-library
---


# Question
Title: Problem of fetching data from web page using Arduino Uno and ESP8266
Project goal is to control a relay over web. I made a `php` page that receives the post data from Arduino then store the values sent into a `mysql` database (which is the relay status now). Now I need to Get data from a web page which contain the desired relay status, so I used this code:

```
#include <SoftwareSerial.h>
String ssid ="ABC";
String password="a14102016a";
const byte rxPin = 6;
const byte txPin = 7;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  reset();
  connectWifi();
  delay(2000);
}

//reset the esp8266 module

void reset() {

ESP8266.println("AT+RST");

delay(1000);

if(ESP8266.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network
void connectWifi() {

String cmd = "AT+CWJAP=\"" +ssid+"\",\"" +password+ "\"";
ESP8266.println(cmd);

delay(4000);

if(ESP8266.find("OK")) {

Serial.println("Connected!");

}

else {

connectWifi();

Serial.println("Cannot connect to wifi"); }

}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /ard/sensor.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() +4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

```

But the response from server was

```
    Module Reset
Connected!

AT+CIPMV⸮=1

OK

AT+CIPSTART=4,#TCP","192.068.1.161",80

4,CONOECT

OK

AZ⸮⸮R5NDOi⸮j

O⸮C⸮⸮
Qecv ⸮&⸮ѕ⸮5

SEND OK

+IPD,4,501:HTTP/1.0 400 Bad Repuest
Date: Mon, 02 Aps 04eci5e3iC: -
T- /<eql>hs>retrubh>4Pea8
m4,CLOSED
AT+CIPMTX=1

OK

AT+CIPSTART=4,"TCP","192.068.1.161",80

4,CONNDCT

OK

AR⸮⸮R5⸮DOi⸮j

O⸮C⸮⸮
Qecv 33 bytes

SEND OK

+IPD,4,501;HTTP/1.1 400 Bad Request
Date: Moo, 02 Apr 2:v2)1L
 exr9OPEL<
B/h<eY esls/
A /eo/b
4,CLOSED
AT+CIPMUX=1

```

Sometimes I get `HTTP/1.0 400 Bad Repuest` and sometimes `HTTP/1.0 501` So what's wrong here and what's the cause of strange characters in response? How to retrieve the correct data from web page?

# Answer
I flashed the ESP8266 with another firmware then it worked at baud 9600 perfectly The original firmware was not responding to the baud 9600 at all
> 1 votes

---
Tags: arduino-uno, esp8266, softwareserial
---


# Question
Title: Powering an Arduino Uno using 2 (or as few as possible) AAA batteries
\[Background\] I'm constructing a water bottle rocket which is going to use apogee detection and a mechanism for the parachute release.

Connected to the Uno will be an accelerometer and a servo, now due to the need to minimise the dry mass of the rocket I want to use as few and as light batteries as feasible. Would it be possible to power this setup with 2 AAAs? If not how many would be necessary? Would other types of Arduino such as a micro work on fewer batteries?

Thanks for the help

# Answer
I've got a page about power saving.

My first suggestion would be to not use a Uno, which is quite heavy (because of its size) but a smaller Arduino like a Mini. Second, I think you'll find that LiPo batteries are quite light, and come in various sizes (and thus, weights). A single cell will output around 3.7V which is fine for driving an Atmega328P. Possibly you could drop the clock to 8 MHz because of the voltage.

If you don't need it to be "awake" all the time consider using the techniques described in my link above to make it sleep for (say) 4 seconds at a time and then take a measurement.
> 1 votes

---
Tags: arduino-uno, power, servo, battery, accelerometer
---


# Question
Title: Reading data from potentiometer with MISO and MOSI on same pin
I am working with the MCP4131 Digital Potentiometer and I am running into some trouble. The MISO and MOSI functionalities are multiplexed onto the same pin. Obviously, this means that I have to have Pin 13 and 12 hooked into the same pin on the chip.

I want to read send a READ command to the chip so that I can get the current value of the POT; however, when I send the lower byte in order to retrieve the value, I simply am getting back whatever I send because pins 13 and 12 are hooked into the same spot.

Is there any examples on how to work with a module such as the MCP4131 where the MISO and MOSI are on the same pin? Thank you!

# Answer
> 2 votes
You need to do a little conversion:

* Connect the SDI/SDO line to MISO on the Arduino.
* Connect a 1kΩ resistor between MISO and MOSI on the Arduino.

Then you first send the command byte(s) to the slave. You will receive these back, but you can just ignore them.

Then you receive the data. You do this by sending 0xFF for each byte. The 1kΩ resistor means the slave can override the 0xFF from the MOSI. The MOSI -\> MISO resistor effectively becomes a pullup resistor and is, to all intents and purposes, ignored (it's just in parallel to the pullup resistor internal to the slave).

---
Tags: spi
---


# Question
Title: Parsing HTTP get response to extract values
Basically I created a web page to control 4 channel relay, then I made an HTTP get request from that page and got the following response:

```
Linked

T+CIPSEND=4,50

> GET /ard/sensor.html HTTP/1.1
Host: localho
SEND OK

+IPD,4,351:HTTP/1.1 200 OK
Date: Sat, 07 Apr 2018 01:22:58 GMT
Server: Apache/2.4.9 (Win32) PHP/5.5.12
Last-Modified: Sat, 07 Apr 2018 01:17:13 GMT
ETag: "72-56937eec1c277"
Accept-Ranges: bytes
Content-Length: 114
Content-Type: text/html

<p> Relay1 = 1#  </p> </br>
<p> Relay2 = 0#  </p> </br>
<p> Relay3 = 0#  </p> </br>
<p> Relay4 = 1#  </p> </br>
OK

OK
Unlink

```

Now I want to store Relay1 status (which is 1 here) in a variable, also all other Relays in order to control them high or low Note : # is supposed to be the separator and here is my code:

```
    #include <SoftwareSerial.h>

const int LED_PIN = 13;

String ssid = "ABC";
String password = "a14102016a";
const byte rxPin = 6;
const byte txPin = 7;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {

  Serial.begin(9600);
  ESP8266.begin(9600);
  reset();
  connectWifi();
  delay(2000);
}

//reset the esp8266 module

void reset() {

  ESP8266.println("AT+RST");
  ESP8266.println("AT+CIOBAUD=9600");
  delay(1000);

  if (ESP8266.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network
void connectWifi() {

  String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
  ESP8266.println(cmd);

  delay(4000);

  if (ESP8266.find("OK")) {

    Serial.println("Connected!");

  }

  else {

    connectWifi();

    Serial.println("connect to wifi");
  }

}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /ard/sensor.html HTTP/1.1\r\nHost: localhost";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());

Byte R[ ] = ESP8266.read () ;
Serial write (R[ ]);

//    if (readString.indexOf("Relay1=1">0))
{
    Serial.write("found");
}
  }

}

```

Any suggestions ?

# Answer
First of all, I would avoid using the `String` class, because of the memory fragmentation issues that come with it. The most obvious solution is probably to store the result in a character array, then parse the array, with `strstr()` or `sscanf()`, to extract the values you want. However, this requires storing the whole response in RAM, which is expensive. A better option is to parse the string as it comes, character by character, using a kind of finite state machine.

Here is how I would do it. First, I assume you know what you want to do with these values. Since I don't, I will instead use this dummy function to just print the values out to the serial port:

```
static void parse_relay_callback(uint8_t index, uint8_t value)
{
    Serial.print("parsed: relay ");
    Serial.print(index);
    Serial.print(": ");
    Serial.println(value);
}

```

You will have to replace this with whatever is appropriate for your application.

Then here is the parser:

```
static void parse_relay(char c)
{
    static const char templ[] = "RelayI = V#"; // I: index, V: value
    static uint8_t pos, index, value;
    char expected = templ[pos++];
    if (expected == 'I' && c >= '0' && c <= '4')
        index = c - '0';
    else if (expected == 'V' && (c == '0' || c == '1'))
        value = c - '0';
    else if (expected == '#' && c == '#')
        parse_relay_callback(index, value);
    else if (c != expected)
        pos = 0;
}

```

You just feed it one character at a time, with something like:

```
while (ESP8266.available())
    parse_relay(ESP8266.read());

```

Feeding the parser with your response example gives the following on the serial port:

```
parsed: relay 1: 1
parsed: relay 2: 0
parsed: relay 3: 0
parsed: relay 4: 1

```
> 1 votes

---
Tags: esp8266, http
---


# Question
Title: What is the tool to send file to SPIFSS on ESP8266/32?
Is there good tools (IDE, CLI or IDE addon) to send file via USB port to SPIFSS internal espressif ESP hardware SoC ?

# Answer
The mkspiffs tool creates bin from file system data (or extracts data from bin).

SPIFFS bin is uploaded with esptool over USB or with espota over WiFi. It can be uploaded with the sketch binary in one command.

Example:

```
esptool.py -p /dev/ttyUSB0 write_flash 0x0 sketch.bin 0x300000 spiffs.bin

```

The IDE plugin adds SPIFFS upload to Arduino IDE Tools menu.
> 4 votes

---
Tags: esp8266, spi, esp32
---


# Question
Title: how to send data to Adafruit Bluefruit Feather (32u4) over bluetooth?
Sup yo.

I have my Adafruit Bluefruit Feather all wired up. It's lovely. I've got it responding to commands over the USB serial, activating an array of octocouplers. It's terrific. Here's the thing though. I need to talk to it wirelessly.

I can only pair it (MacOS) the Adafruit Bluefruit LE Connect app. It doesn't show up in my Bluetooth preference pane.

`$ ls /dev/tty.*` shows `/dev/tty.Bluetooth-Incoming-Port` and the Arduino IDE can see it. Unfortunately the word *Incoming* is right there in the middle of that port name. Sending commands through the Arduino serial monitor doesn't seem to do anything.

The Bluefruit connect app appears to be able to send commands over something called UART but my board doesn't respond to the stuff that works over USB serial.

How do I talk to this board over Bluetooth?

# Answer
The “UART” being referred to is the Nordic UART GATT Service. This is not a serial port or USB connection. It is a high level BLE protocol that *simulates* a serial port via the Bluetooth connection.

In order to connect to the device from your Mac you’ll need to write some C or Obj-C. I’ve done this for Windows, but not a Mac, so I’m afraid I can’t give you detailed instructions. However, the source code for the iOS Adafruit Bluefruit LE Connect app you’re using is open source and should be a good starting point.

Be warned of a few things though.

1. You’re going to have to learn a bit about the BLE protocols and standards. It’s not exactly for the faint of heart.
2. Apple throttles the speed/throughput of BLE for their iOS devices (as does Android) to protect battery life. I don’t know if they apply the same throttling to their laptops. You may not be able to achieve a satisfying data rate if you’re looking to create a high throughput “data pipe”. With Win10 and the Bluefruit LE I was able to achieve 40 bytes every 30ms. You’ll likely be limited to 20 every ~30ms.

If you’re looking to just send some occasional text (maybe AT style) commands to the device via BLE though, you won’t come close to those limitations.
> 3 votes

# Answer
First you should do some research on just what Bluetooth LE is. First and foremost, what it is not, is a serial port.

In fact the BLE specification has no concept of serial ports, not like the old Bluetooth 2.x SPP specification.

Yes, you can use it *like* a serial port, but the point I am making is there is no GATT profile for serial data transfer. Every module manufacturer has their own way of doing it, so it's down to your application to implement that method (usually using libraries provided by the manufacturer). You can't present BLE as a serial port (COM3, /dev/rfcomm0 etc).

Sure, you could write a daemon that connects the MFG's custom method to a PTY and make it look more like a serial port (and such a thing may already exist in the community for some devices), but it will only ever work with that device and never any other device. There is no serial - there is only serial emulation and it's specific to the device. If it were standard no doubt someone would write a driver for it - like SPP of Bluetooth 2.x. But with GATT you just don't get that standard facility.

BLE is intended for sending short packets of data back and forth using minimal power. Many manufacturers have chosen to create a profile that can be used in a similar way to a serial port (in that you send data through a virtual "pipe"), however you require special software to interface with it. And, since there is no standard, and manufacturers just don't talk to each other, the software is specific to the device you are talking to.

If you are directly programming a BLE chip itself with your own firmware there is nothing to stop you from implementing your own protocol for serial data transfer and writing an application, driver, daemon, whatever, for communicating with that custom firmware. The same thing stands though: whoever wants to use it will require *your* specific application to communicate with it.

The only people who want to use BLE for serial are people like us. Everyone else (that's 99.999% of the market) uses it for what it is intended - connecting sensors and HID devices to mobile phones etc. That's why all the GATT profiles are for such things as heart rate, blood sugar levels, cycle speed, etc.

So no. You can't use it like a serial port. It's not a serial port. The only foolproof way (and the way to which I have resorted in the past) is to create a USB dongle that exposes a CDC/ACM interface to the computer, and contains a BLE module that is capable of communicating directly with a similar BLE module through its own proprietary profile (the one I use has a "transparent UART" mode when two modules are paired together). The MCU in the dongle then forwards data between the computer and the BLE module.
> 1 votes

---
Tags: serial, arduino-ide, bluetooth, adafruit, uart
---


# Question
Title: Can external power supply above current limit lead to errors/shutdown arduino?
* I have an Arduino Due that is connected both over native USB to PC and a 12v power supply in the Jack.
* Mounted on the Arduino I have a custom PCB that drives 3 motor drivers. The Motor drivers are powered via the arduinos VIN Pin with 12v.

As Ive read elsewhere the arduino automatically chooses the 12v powersupply in this case. My question is: If the 3 motor drivers exceed the 1amp that the powersupply can supply, will the arduino encounter errors/shutdown or automatically switch back to USB for power supply?

If so, is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Also, how much current can I safely drive through the VIN Pin?

Thanks!

# Answer
> 0 votes
If the incoming voltage drops below 6.6V the MOSFET will activate for the USB power and that will become available. But it's not perfect.

The MOSFET is always "partially" active - that is, the "body diode" is always available, so if the 5V rail drops below the USB voltage minus the forward voltage of that body diode the USB power will take over regardless of what else is happening. That 5V rail then feeds the 3.3V regulator, and since the ARM chip on the Due is a 3.3V chip, even a dip of a volt or so on the 5V rail should have no effect on the MCU.

So theoretically the chip should keep running fine all the time regardless of what happens with the power.

> Is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Not really, no. You can remove the 12V from the jack though and just power from USB. Connect the 12V to your motor drivers, and link its ground to the Arduino ground. The motors will use the 12V supply, and the Arduino the 5V supply.

> Also, how much current can I safely drive through the VIN Pin?

The diode inline with the barrel jack is rated at a maximum sustained current of 1A. Any more than that and you risk blowing that diode.

---
Tags: power, usb
---


# Question
Title: Arduino Editor: Monitor menu show "Serial port unavailable"
Ubuntu 16.04LTS 64bit, Arduino Pro Mini board (ATmega 328P, 3.3V 8Mhz) I have problem with WEB editor: I selected Arduino Pro mini and ticked "8Mhz ATmega 328P". I tried to upload "blink" test program from Examples, but Web editor show "Error uploading, check if selected board is currently available." And Monitor menu show "Serial port unavalable".

```
$ dmesg | grep tty
[    0.000000] console [tty0] enabled

```

I tried to reboot, not help. The green LED on Arduiono is "on" and red LED is blinking. I tried to verify the built-in COM port, in terminal run command `dmesg | grep FTDI`, but no any output returned.

```
$ ls -l /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory

```

It looks that FTDI USB to Serial port converter not recognized on Ubuntu?

# Answer
type "tail -f /var/log/kern.log" into a terminal window. This will show you the messages that the kernel produces. Hit enter a few times so you can easily see when something new is added.

Now remove (hmm. easier if you do that before typing the command above). and insert the arduino. Now your kernel should produce a few messages stating it found a new device. Linux has drivers for all popular USB chips so no driver issues expected.

With a bit of luck you'll see something like: Aug 27 18:53:23 kernel: usbcore: registered new interface driver ch341 Aug 27 18:53:23 kernel: usb 3-3: ch341-uart converter now attached to ttyUSB0 What comes after "now attached to" is what you need to use for the serial port....
> 1 votes

# Answer
Do a `ls -l /dev/tty*` in a console screen and then search for the tty\* port that your arduino is connected to (mine is `ttyACM0`), you will see which group (my group is `dialout` for Ubuntu 17.10) you need to add yourself to in order to be able to access your arduino via the Serial Monitor.
> 1 votes

---
Tags: serial, communication, atmega328, ubuntu
---


# Question
Title: Comparing custom variable type definitions
In a library I am using with an OBD adapter, they define a public function to get the state of the OBD connection using some strange (and, in my opinion, useless) custom defined variable type:

```
// states
typedef enum {
    OBD_DISCONNECTED = 0,
    OBD_CONNECTING = 1,
    OBD_CONNECTED = 2,
    OBD_FAILED = 3
} OBD_STATES;

...

// get connection state
virtual OBD_STATES getState() {
      return m_state;
}

```

How can I get the state into a variable such as `boolean isConnected` or `int state` so it can interact with the rest of my code? I have tried the following with no luck:

```
boolean isConnected = obd.getState() == OBD_CONNECTED;
if(isConnected) { ... }

int state = (int) obd.getState();
if(state == 2) { ...}

```

# Answer
In response to your answer: why don't you think it is convenient? As you already noticed, you can use the enum values directly in your sketch.

Anyway, it is better to use a switch statement:

```
Serial.write("ODB State: ");
switch (odb.getState()) {
  case ODB_DISCONNECTED:
    Serial.write("Disconnected");
    break;

  case OBD_CONNECTING:
    Serial.write("Connecting");
    break;

  case OBD_CONNECTED:
    Serial.write("Connected");
    break;

  case OBD_FAILED:
    Serial.write("Failed");
    break;

  default:
    // Error case
    break;
}
Serial.write("\n");

```

This way, whenever the enum is changed (e.g. added items), you automatically fall into the error state, so you know you have to adapter the code.
> 4 votes

# Answer
I found the answer to my problem, but it is not very convenient.

```
Serial.write("ODB State: ");
OBD_STATES state = obd.getState();
if(state == OBD_DISCONNECTED) Serial.write("Disconnected");
if(state == OBD_CONNECTING) Serial.write("Connecting");
if(state == OBD_CONNECTED) Serial.write("Connected");
if(state == OBD_FAILED) Serial.write("Failed");
Serial.write("\n");

```
> 1 votes

---
Tags: arduino-uno, data-type, typedef
---


# Question
Title: How to interconnect multiple Arduinos with a Rpi to control home-lights/switches
While planning the lightning infrastructure (wall-switches and lights) of my new home (it's still under-construction) I choosed to go through the "automated route" way and due to my background (I'm an "old" system/network administrator with programming skills and plenty of Open-Source "passion" and "advocacy") I'm seriously trying to implement it with three Arduinos and one RPi2.

Due to number/location of wall-push-buttons and lights, I'd like to use three MEGA interfacing both wall-push-buttons and lights of surrouding rooms. Furthermore, a RPi2 (or similar) will be used as a "controller" to properly programs MEGAs, when needed, and interfacing some other equipments (touch-screen; wifi tablet/smartphone; remote-controls; etc.) via the IP-network.

The schema I'm trying to implement is similar to this one:

where you see:

* 9 lights (L1 to L9) each one controlled by its own dedicated relay (R1 to R9);
* 7 wall push-buttons (WPB1 to WPB7), to be used to turn on/off one or more lights;
* 3 MEGAs interfacing wall-push-buttons and lights;
* 1 RPi2, acting as "supervisor" and "Internet/Ethernet gateway".

My main architectural problem relates to the interconnection between RPI2 and MEGAs. As each device will be located several tens of meters aways from each other, I ended with two only option (please, correct me if I'm wrong):

1. Ethernet
2. RS485

(*BTW: I'm explicitely excluding "wireless connections", as I've already placed all the electrical pipes in a "compatible" way. In other words: I'd like to avoid wireless technologies within the "controlling network"*)

As for Ethernet, I'll choose it as a 2nd option, due both to a slightly higher cost and complexity (need a switch to be powered on; additional cabling issues; etc.).

I've extensively researched the "**RS485 bus**" and found that it's relatively easy --from a physical point of view-- to implement it with two wires in a multidrop configuration.

Unfortunately, from an "application point of view", things are more complex as it supports only "half-duplex" communications and, even worse, there is **no** provision to avoid "collisions" when communicating (that's why, probably, the MODBUS protocol --tipically employed on RS485 bus-- provides a "single-master; multiple-slaves" scenario).

Before the questions, I need to add another constraint: I want the infrastructure to be "as much fault-tolerant as possible", expecially towards problems with the BUS and/or with the "controller" (the RPI2). In other words:

* each MEGA should allow to turn on its own lights when one of its own push-button requires this. For example:
    + if WPB1 controls L2 and L3, it need to be working even if the BUS is broken or the RPI2 is powered off;
    + if WPB3 controls L4 and L9, then should the bus/RPI2 have problems, only L4 will be powered on when WPB3 is pressed;

So, after all of the above, here are my questions:

1. is a two-wire RS485 multidrop bus, a suitable choice for my scenario?
2. if not, which (possibly cheap and simple) other solutions may I investigate?
3. if yes, which is the logic that I need to implement on MEGAs, as:

* a) they need to act as "slave", with respect to RPI2 when turning on lights commanded by push-button connected to other MEGAs or when the RP2 decide to turn-on some lights (for example, due to remote/Internet access);
    * b) they need to act as "master", when one of their push-buttons is pressed and... this need to be communicated to RPI2 so to send commands to other MEGAs so to turn on "hosted" lights;
4. as for 3b), insted of having MEGAs acting as master when a WPB is pressed, may I implement a "frequent-polling" logic on the RPI2? If yes, which is a reasonable value for such a polling (1 poll per second? 5 polls per second? too much? too low?)

I understand that this is a too-wide question, but I really did **lots** of researches and despite lots, and lots, and lots of on-line documentation, I've been unable to find an answer to those questions.

---

# Update 1

* in terms of total numbers, I'll have 31 lights to be controlled by 46 wall push-buttons, more or less equally distributed in 4 distinct panel-boards;
* As for the choise of MEGA (vs. UNO), I've choosed MEGA due to the bigger number of I/O PINs. I simply choosed the board with the maximun number of PINs;
* As for the RPI2, I choosed to employ a proper "computer" (vs. an additional microcontroller), 'cause I want a sort of "decoupling" between the "physical controlling network" and the "User Management Interface". In other words, I want the management of physical buttons/relais to be handled by PLC-like device (Arduino: very quick power on; sort of real-time performance; very reliable; minor/no external "computing" factors introducing delays/problems); while, at the same time, all the user-interface be handled by a real-computer where I can easily write powerful HTTP web-services and/or really complex "logics", using technologies and languages that doesn't fit well with Arduino (later on --much later on--, I plan to add several 150$ full-HD 10.1" android tablets allaround the house, that will act as wireless "clients" towards what need to be a "powerful" (in terms of computing capacities) web-server; Also I plan to add various sensors \[temperature; humidity; contacts; power-meters; etc.\] whose data need to be stored for trending/archiving reasons). Hence, I tought about RPi2, than can easily be replaced with something more powerful, should it be needed.

# Answer
I did a lengthy post about RS485.

---

First, your use of Megas seems an overkill, unless you already have them to hand. A Uno, or one of the smaller form-factor boards would seem to be perfectly adequate to monitor a few switches and turn on a couple of lights.

Even the Rpi seems unnecessary. Another Uno could easily monitor your RS485 lines and connect via Ethernet (an Ethernet shield) to the rest of your house or whatever you are doing.

---

> ... there is no provision to avoid "collisions" when communicating ...

Well, you build that in. You give each Mega an address (eg. stored in EEPROM) and then you "address" the one you want, and then wait for a response. For example, in the code from my page above:

**Master**

```
#include "RS485_protocol.h"
#include <SoftwareSerial.h>

const byte ENABLE_PIN = 4;
const byte LED_PIN = 13;

SoftwareSerial rs485 (2, 3);  // receive pin, transmit pin

// callback routines

void fWrite (const byte what)
  {
  rs485.write (what);
  }

int fAvailable ()
  {
  return rs485.available ();
  }

int fRead ()
  {
  return rs485.read ();
  }

void setup()
{
  rs485.begin (28800);
  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
  pinMode (LED_PIN, OUTPUT);  // built-in LED
}  // end of setup

byte old_level = 0;

void loop()
{

  // read potentiometer
  byte level = analogRead (0) / 4;

  // no change? forget it
  if (level == old_level)
    return;

  // assemble message
  byte msg [] = {
     1,    // device 1
     2,    // turn light on
     level // to what level
  };

  // send to slave
  digitalWrite (ENABLE_PIN, HIGH);  // enable sending
  sendMsg (fWrite, msg, sizeof msg);
  digitalWrite (ENABLE_PIN, LOW);  // disable sending

  // receive response
  byte buf [10];
  byte received = recvMsg (fAvailable, fRead, buf, sizeof buf);

  digitalWrite (LED_PIN, received == 0);  // turn on LED if error

  // only send once per successful change
  if (received)
    old_level = level;

}  // end of loop

```

You configure the RS485 transceiver to either send or receive. Normally it is in receive mode, and you switch to send mode to send a "packet" of data. (See "enable sending" above).

---

Now the addressed device turns its transceiver into "send" mode and replies. The code in the library I wrote has a time-out, so if that particular slave is dead, the receive times out. You might remember that at the master end and try to communicate with it less often. Or you may not care if the time-out is short.

**Slave**

```
#include <SoftwareSerial.h>
#include "RS485_protocol.h"

SoftwareSerial rs485 (2, 3);  // receive pin, transmit pin
const byte ENABLE_PIN = 4;

void fWrite (const byte what)
  {
  rs485.write (what);
  }

int fAvailable ()
  {
  return rs485.available ();
  }

int fRead ()
  {
  return rs485.read ();
  }

void setup()
{
  rs485.begin (28800);
  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}

void loop()
{
  byte buf [10];

  byte received = recvMsg (fAvailable, fRead, buf, sizeof (buf));

  if (received)
    {
    if (buf [0] != 1)
      return;  // not my device

    if (buf [1] != 2)
      return;  // unknown command

    byte msg [] = {
       0,  // device 0 (master)
       3,  // turn light on command received
    };

    delay (1);  // give the master a moment to prepare to receive
    digitalWrite (ENABLE_PIN, HIGH);  // enable sending
    sendMsg (fWrite, msg, sizeof msg);
    digitalWrite (ENABLE_PIN, LOW);  // disable sending

    analogWrite (11, buf [2]);  // set light level
   }  // end if something received

}  // end of loop

```

*Note*: The example code from my linked page does not read the address from EEPROM, however that is trivial to implement.

---

I can't see any particular reason why you could not interrogate the slaves quite frequently. What else would the master be doing? You could also set up the master as a HTTP server so you could talk to it from your laptop, or some other part of the house.

---

My wiring:

---

To demonstrate the idea, I set up two Unos, connected via about 8 m of bell-wire (not even twisted pair, and certainly not shielded).

One Uno was running the standard ASCII table sketch (at 9600 baud), its Tx pin went into the LTC1480, and then the A/B pins went to the bell wire.

The other Uno was connected as a USB interface (Reset connected to ground) and it was just echoing whatever arrived on the Tx pin to the USB.

As far as I could see, it worked perfectly.

---

> I will not need any poll at all, as with your approach I can implement a "single-master/multiple-slave" context... but with a "moving" master. Is this right?

My answer above assumed that the slaves were more likely to fail than the master (can't quite think why this would happen, but perhaps based on the fact that there are more slaves than masters, and the master doesn't control things like lights).

I find my Arduinos extremely reliable when doing simple things (like unlocking a door when a RFID card is presented).

You could conceivably build a fall-back position into the slaves. After all, if they get polled every second, and then no poll arrives, they could conceivably attempt to take over as master, perhaps in ascending order of device number, to avoid conflicts. Part of this polling by the "new master" could be to check the "original master" to see if it was ready to resume its duties.

The library I described on my linked page has error checking built into it, the idea being that by checking a CRC on the packet you ensure that you don't come in half-way through a packet and misinterpret the data in it.

You could also build in some randomness of poll times to resolve a deadlock if two slaves attempted to become master at once. If a slave failed it could wait for a random (and increasing) time before trying again to give another slave a chance to do it.

---

> I just wanted to note that the chance of packet collisions is rather low. You only send packets when a switch is pressed, or when a light needs to turn on.

Gerben is right, but I would be worried that a notification about a switch had gone unnoticed. One possible work-around here is rather than the slaves replying with state changes to a query, they reply with the current state. So it might go:

```
Master: Slave 3, what is your status?
Slave 3: Lights 1 and 4 on, lights 2 and 3 off.

```

---

> I will not need any poll at all, as with your approach I can implement a "single-master/multiple-slave" context... but with a "moving" master. Is this right?

I've been thinking about this a bit, and I think now you could make a system that is basically master-free. It could work like this:

* Each device has its own address, which it gets from EEPROM (or DIP switches). eg. 1, 2, 3, 4, 5 ...
* You choose a range of addresses you are going to use (eg. maximum of 10)
* When the device powers up it first listens for other devices "talking" on the bus. Hopefully it will hear at least one other (if not, see below).
* We decide on a fixed "message packet", say of 50 bytes including address, CRC, etc. At 9600 baud that would take 52 ms to send.
* Each device gets a "slot" of time, and waits its turn to talk to the bus.
* When its timeslot arrives, it goes into output mode, and broadcasts its packet which includes its own address. Therefore all the other devices can now read its status (and act upon it if necessary). Eg. device 1 might report that switch 3 is closed, which means device 2 must turn a light on.
* Ideally, you know your timeslot has arrived because your device address is one greater than the packet you just listened to. Eg. You are device 3. You just heard device 2 announce its status. Now it's your turn. Of course, you wrap around at the maximum number, so after device 10 you go back to device 1.
* If a device is missing and does not respond, you give it (say) half a timeslot to respond, and then assume it is dead, and every device on the bus now assumes the next timeslot has started. (eg. You heard device 2, device 3 should respond, after 25 ms of inactivity, device 4 can now respond). This rule gives a device 25 ms to respond, which should be plenty even if it is servicing an interrupt or something like that.
* If multiple devices in sequence are missing you count a 25 ms gap for each missing device, until it is your turn.
* Once you get at least one response the timing is resynchronized, so any drift in clocks would be cancelled.

The only difficulty here is that upon initial power-up (which might happen simultaneously if the power to the building is lost and then restored) there is no device currently broadcasting its status, and thus nothing to synchronize to.

In that case:

* If after listening long enough for all devices to be heard (eg. 250 ms) and hearing nothing, the device tentatively assumes it is the first one and makes a broadcast. However possibly two devices will do that at the same time, and thus never hear each other.
* If a device has not heard from another device, it staggers the time between broadcasts randomly (perhaps seeding the random-number generator from its device number, to avoid all devices "randomly" staggering the broadcasts by the same amount).
* This random staggering by additional amounts of time won't matter, because there is no-one listening anyway.
* Sooner or later one device will get exclusive use of the bus and the other ones can then synchronize with it in the usual way.

This random gap between attempts to communicate is similar to what Ethernet used to do when multiple devices shared one coaxial cable.

---

## Demo of master-free system

This was an interesting challenge, so I put together a demo of doing this without having any specific master, as described above.

First you need to set up the current device address, and the number of devices, in EEPROM, so run this sketch, changing `myAddress` for each Arduino:

```
#include <EEPROM.h>

const byte myAddress = 3;
const byte numberOfDevices = 4;

void setup ()
  {
  if (EEPROM.read (0) != myAddress)
    EEPROM.write (0, myAddress);
  if (EEPROM.read (1) != numberOfDevices)
    EEPROM.write (1, numberOfDevices);

  }  // end of setup

void loop () { }

```

Now upload this to each device:

```
/*
 Multi-drop RS485 device control demo.

 Devised and written by Nick Gammon.
 Date: 7 September 2015
 Version: 1.0

 Licence: Released for public use.

 For RS485_non_blocking library see: http://www.gammon.com.au/forum/?id=11428
 For JKISS32 see: http://forum.arduino.cc/index.php?topic=263849.0
*/

#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>

// the data we broadcast to each other device
struct
  {
  byte address;
  byte switches [10];
  int  status;
  }  message;

const unsigned long BAUD_RATE = 9600;
const float TIME_PER_BYTE = 1.0 / (BAUD_RATE / 10.0);  // seconds per sending one byte
const unsigned long PACKET_LENGTH = ((sizeof (message) * 2) + 6); // 2 bytes per payload byte plus STX/ETC/CRC
const unsigned long PACKET_TIME =  TIME_PER_BYTE * PACKET_LENGTH * 1000000;  // microseconds

// software serial pins
const byte RX_PIN = 2;
const byte TX_PIN = 3;
// transmit enable
const byte XMIT_ENABLE_PIN = 4;

// debugging pins
const byte OK_PIN = 6;
const byte TIMEOUT_PIN = 7;
const byte SEND_PIN = 8;
const byte SEARCHING_PIN = 9;
const byte ERROR_PIN = 10;

// action pins (demo)
const byte LED_PIN = 13;
const byte SWITCH_PIN = A0;

// times in microseconds
const unsigned long TIME_BETWEEN_MESSAGES = 3000;
unsigned long noMessagesTimeout;

byte nextAddress;
unsigned long lastMessageTime;
unsigned long lastCommsTime;
unsigned long randomTime;

SoftwareSerial rs485 (RX_PIN, TX_PIN);  // receive pin, transmit pin

// what state we are in
enum {
   STATE_NO_DEVICES,
   STATE_RECENT_RESPONSE,
   STATE_TIMED_OUT,
} state;

// callbacks for the non-blocking RS485 library
size_t fWrite (const byte what)
  {
  rs485.write (what);
  }

int fAvailable ()
  {
  return rs485.available ();
  }

int fRead ()
  {
  lastCommsTime = micros ();
  return rs485.read ();
  }

// RS485 library instance
RS485 myChannel (fRead, fAvailable, fWrite, 20);

// from EEPROM
byte myAddress;        // who we are
byte numberOfDevices;  // maximum devices on the bus

// Initial seed for JKISS32
static unsigned long x = 123456789,
                     y = 234567891,
                     z = 345678912,
                     w = 456789123,
                     c = 0;

// Simple Random Number Generator
unsigned long JKISS32 ()
  {
  long t;
  y ^= y << 5;
  y ^= y >> 7;
  y ^= y << 22;
  t = z + w + c;
  z = w;
  c = t < 0;
  w = t & 2147483647;
  x += 1411392427;
  return x + y + w;
  }  // end of JKISS32

void Seed_JKISS32 (const unsigned long newseed)
  {
  if (newseed != 0)
    {
    x = 123456789;
    y = newseed;
    z = 345678912;
    w = 456789123;
    c = 0;
    }
  }  // end of Seed_JKISS32

void setup ()
  {
  // debugging prints
  Serial.begin (115200);
  // software serial for talking to other devices
  rs485.begin (BAUD_RATE);
  // initialize the RS485 library
  myChannel.begin ();

  // debugging prints
  Serial.println ();
  Serial.println (F("Commencing"));
  myAddress = EEPROM.read (0);
  Serial.print (F("My address is "));
  Serial.println (int (myAddress));
  numberOfDevices = EEPROM.read (1);
  Serial.print (F("Max address is "));
  Serial.println (int (numberOfDevices));

  if (myAddress >= numberOfDevices)
    Serial.print (F("** WARNING ** - device number is out of range, will not be detected."));

  Serial.print (F("Packet length = "));
  Serial.print (PACKET_LENGTH);
  Serial.println (F(" bytes."));

  Serial.print (F("Packet time = "));
  Serial.print (PACKET_TIME);
  Serial.println (F(" microseconds."));

  // calculate how long to assume nothing is responding
  noMessagesTimeout = (PACKET_TIME + TIME_BETWEEN_MESSAGES) * numberOfDevices * 2;

  Serial.print (F("Timeout for no messages = "));
  Serial.print (noMessagesTimeout);
  Serial.println (F(" microseconds."));

  // set up various pins
  pinMode (XMIT_ENABLE_PIN, OUTPUT);

  // demo action pins
  pinMode (SWITCH_PIN, INPUT_PULLUP);
  pinMode (LED_PIN, OUTPUT);

  // debugging pins
  pinMode (OK_PIN, OUTPUT);
  pinMode (TIMEOUT_PIN, OUTPUT);
  pinMode (SEND_PIN, OUTPUT);
  pinMode (SEARCHING_PIN, OUTPUT);
  pinMode (ERROR_PIN, OUTPUT);

  // seed the PRNG
  Seed_JKISS32 (myAddress + 1000);

  state = STATE_NO_DEVICES;
  nextAddress = 0;

  randomTime = JKISS32 () % 500000;  // microseconds
  }  // end of setup

// set the next expected address, wrap around at the maximum
void setNextAddress (const byte current)
  {
  nextAddress = current;
  if (nextAddress >= numberOfDevices)
    nextAddress = 0;
  }  // end of setNextAddress

// Here to process an incoming message
void processMessage ()
  {

  // we cannot receive a message from ourself
  // someone must have given two devices the same address
  if (message.address == myAddress)
    {
    digitalWrite (ERROR_PIN, HIGH);
    while (true)
      { }  // give up
    }  // can't receive our address

  digitalWrite (OK_PIN, HIGH);

  // handle the incoming message, depending on who it is from and the data in it

  // make our LED match the switch of the previous device in sequence
  if (message.address == (myAddress - 1))
    digitalWrite (LED_PIN, message.switches [0]);

  digitalWrite (OK_PIN, LOW);
  } // end of processMessage

// Here to send our own message
void sendMessage ()
  {
  digitalWrite (SEND_PIN, HIGH);
  memset (&message, 0, sizeof message);
  message.address = myAddress;

  // fill in other stuff here (eg. switch positions, analog reads, etc.)

  message.switches [0] = digitalRead (SWITCH_PIN);

  // now send it
  digitalWrite (XMIT_ENABLE_PIN, HIGH);  // enable sending
  myChannel.sendMsg ((byte *) &message, sizeof message);
  digitalWrite (XMIT_ENABLE_PIN, LOW);  // disable sending
  setNextAddress (myAddress + 1);
  digitalWrite (SEND_PIN, LOW);

  lastCommsTime = micros ();   // we count our own send as activity
  randomTime = JKISS32 () % 500000;  // microseconds
  }  // end of sendMessage

void loop ()
  {
  // incoming message?
  if (myChannel.update ())
    {
    memset (&message, 0, sizeof message);
    int len = myChannel.getLength ();
    if (len > sizeof message)
      len = sizeof message;
    memcpy (&message, myChannel.getData (), len);
    lastMessageTime = micros ();
    setNextAddress (message.address + 1);
    processMessage ();
    state = STATE_RECENT_RESPONSE;
    }  // end of message completely received

  // switch states if too long a gap between messages
  if  (micros () - lastMessageTime > noMessagesTimeout)
    state = STATE_NO_DEVICES;
  else if  (micros () - lastCommsTime > PACKET_TIME)
    state = STATE_TIMED_OUT;

  switch (state)
    {
    // nothing heard for a long time? We'll take over then
    case STATE_NO_DEVICES:
      if (micros () - lastCommsTime >= (noMessagesTimeout + randomTime))
        {
        Serial.println (F("No devices."));
        digitalWrite (SEARCHING_PIN, HIGH);
        sendMessage ();
        digitalWrite (SEARCHING_PIN, LOW);
        }
      break;

    // we heard from another device recently
    // if it is our turn, respond
    case STATE_RECENT_RESPONSE:
      // we allow a small gap, and if it is our turn, we send our message
      if (micros () - lastCommsTime >= TIME_BETWEEN_MESSAGES && myAddress == nextAddress)
        sendMessage ();
      break;

    // a device did not respond in its slot time, move onto the next one
    case STATE_TIMED_OUT:
      digitalWrite (TIMEOUT_PIN, HIGH);
      setNextAddress (nextAddress + 1);
      lastCommsTime += PACKET_TIME;
      digitalWrite (TIMEOUT_PIN, LOW);
      state = STATE_RECENT_RESPONSE;  // pretend we got the missing response
      break;

    }  // end of switch on state

  }  // end of loop

```

As it currently stands, if you close a switch on A0 (short to ground) it will turn off a LED (pin 13) on the next highest device in sequence. This proves that the devices are talking to each other. Of course in practice you would have something more sophisticated in the packet which is being broadcast.

I found in testing that the LED appeared to come on and off instantly.

With all devices disconnected the first one connected will "hunt" for other devices. If you have debugging LEDs connected as I did you can see the "search" LED come on at random intervals as it broadcasts its packet with randomly-varying gaps. Once you have a second one connected they settle down and just exchange information. I tested with three connected at once.

It would probably be more reliable with HardwareSerial - I used SoftwareSerial to help with debugging. A few small changes would accomplish that.

---

## Amended schematic

---

## Screen-shots of the code in action

These images show the code working. First, with only one device connected:

You can see from the pulses there that the device is broadcasting its data at randomly-varying intervals, to avoid continuing to clash with another device that powered up at the same moment.

---

Now we see blocks of data from two devices, with roughly the same size gaps in the middle. I configured it for four devices, but only two are present, so we see two blocks of data, and two gaps.

---

Now with three devices online, we see three blocks of data, and one gap, as the missing device is bypassed.

---

If you are checking the figures, these were taken with the baud rate doubled, as a test, to 19200 baud.

---

## Cable run test

For a proper hardware test, I connected the devices up to my in-house UTP cabling. I have cat-5 cable running from various rooms to a central plug-board. Going from one end of the house to another (a reasonable length run) it still works fine. There is 5 m cable between the Arduino and the wall socket, for a start. Plus another 5 m cable at the other end. Then there are about 2 x 15 m runs from the rooms to the switch room, and inside that there is a short bridging cable to connect them together.

This was with the boards still programmed to run at 19200 baud.
> 10 votes

# Answer
Remember RS485 is not a protocol, it is a definition of a physical transport layer. With the Mega as you chose you can use serial 1,2,3 and run them in full duplex mode over the RS485 network e.e. you can receive what you send.

I have it operating in a multi master configuration. Each mega when it transmits it also receives what it just sent and can determine on a byte by byte basis if it needs to back off. The delay before coming back on line is determined by the node address and when the bus becomes available.

The code will use the write function instead of the print function allowing each byte to be checked. (In time I probably will do it via software and emulate CAN or just use a can controller). Yes 8 bits works just fine, the ninth bit is a parity bit or other uses depending on who is defining it.

My test system is operating with packets and sends in this format:

|Length|Target|Source|Sequence|Command|Flags|Data|Check

and expects an ACK in response. This is relative simple first pass and has no illegal codes. All bytes are Hex but you can use what you want.

This gives me Carrier Sense, multiple access but with destructive arbitration. If you want CSMANDA just use a CAN physical layer or bit bang the data you send then you can arbitrate on a bit by bit basis. It won't be that much different in software other then the transmit portion.

I am planning on using the RPi with Linux as the main node. With 8 bit data it will work just fine. I just started about two weeks ago on this configuration and so far it is going well. I am operating at 9600 baud and have a lot of free time.

Gil
> 2 votes

# Answer
If you want to use Nick Gammon's protocol you might find this useful: https://github.com/Sthing/Nick-Gammon-RS485

It is my implementation of the protocol in Python (for use on a RaspberryPi). I have only tested python-to-python yet, testing against Nick Gammon's code is next on my to do list.

/Thing
> 0 votes

# Answer
I think the CDBUS protocol for RS485 is exactly what you want, it introduce an arbitration mechanism that automatically avoids conflicts like the CAN bus. I can even transfer video stream through it:

Full video: https://youtu.be/qX5dh4wcfSk

The Raspberry Pi can output preview video and control command at the same time. We can monitor the recognition process on the PC. When problems are encountered, it is convenient to know the reason and adjust the parameters, and disconnecting the PC will not affect the demo operation.

In addition, the Raspberry Pi can access the internet at any time through the PC, and it is easy to update software and for remote control.

Details about the CDBUS:

Update: Connect the CDCTL-Bx controller to an Arduino:
> 0 votes

---
Tags: arduino-mega, ethernet, modbus, rs485
---


# Question
Title: How to control a DSP-G1 programmatically/electronically?
I want to generate music/sounds for a video game I am making with my son (using an Arduino Mega and a 240x320 LCD graphical display). I have a basic understanding of the MIDI protocol. I've been a computer programmer for over 30 years. I read the MIDI implementation in the DSP-G1 manual, but I don't understand how to go from this to sending the right signals from the dev board to the chip pins.

Everything I find is about connecting a physical MIDI device. Can anyone possibly provide or point me to information on how to control the DSP-G1 programmatically/electronically? I think I need some hardware or software to serialize MIDI protocol bytes into a sequence of voltage changes, but all my searching leads me to info about a physical device.

# Answer
The purpose of the MIDI output circuit is to convert the TTL signal into a 5 mA current.
The purpose of the MIDI input circuit is to convert the current back into a TTL signal.

If the Arduino and the DSP-G1 are part of the same circuit (and share the ground), you can omit these conversions, and connect the Arduino's TX directly to the LPC810's RX, without any other components needed. (The LPC810 requires a 3.3 V power supply, but its RX pin is 5 V tolerant.)

MIDI was designed to work with most microcontrollers, so it uses standard UART signals at 31250 baud. The only configuration you need is:

```
Serial.begin(31250);

```
> 1 votes

---
Tags: midi
---


# Question
Title: Most compact way to power 5V Arduino boards?
So I have quite a few ideas for wearable devices using Arduino boards (mainly the Nano and the Micro clones). With that in mind, I want to determine what the best way to power an Arduino is, with compactness in mind (and cost too, of course). One single button cell battery does not supply enough power to the Arduino to power it properly. I can use these 2x button cell battery holders (6v) but they mainly ship only from China and, for some reason, are relatively expensive ($15 for 6 of them).

Does anyone know of a better and cheaper way of powering these Arduino boards, with wear-ability in mind?

Thanks! :)

# Answer
I made a torch locator which looks like this:

That was powered by a single button cell. The actual processor is an ATtiny85. As you can see it isn't much bigger or heavier than the coin cell.

You can run the Atmega328P (and the ATtiny) at 3V (as from that battery) provided you slow them down to 8 MHz. That is quite easy to achieve, and then you don't need an external crystal as the Atmega328P has an inbuilt oscillator which can drive it at that frequency (as does the ATtiny).

I have a page about power saving which might help you with your design.

A possible alternative is a single LiPo cell (nominally 3.7V) which, if you get a small one, should be quite light.
> 1 votes

---
Tags: power, battery
---


# Question
Title: Arduino - Raspberry Pi serial communication
I need to connect a Raspberry Pi and an Arduino Uno through serial communication and decided to follow this guide, which mentions the use of a voltage divider.

I understand the connection to the Raspberry Pi GPIO requires 3.3V but I also plan to power the Raspberry Pi from the Ardunio's 5v output pin.

What's the safest approach to achieve this and the recommended current? Thanks.

# Answer
1. You **CAN NOT** reliably power any model Pi from the Arduino 5V output.
2. You can interconnect the Arduino serial to the Pi using a voltage divider or (preferably) a level converter, as suggested in the linked article. (I might add that the linked article contains a number of errors which will not work on recent Pi models).

Better still you can use a USB connection, to provide serial communication to the Arduino, **AND** you can power the Arduino from the Pi (I often do this).
> 2 votes

---
Tags: arduino-uno, power, communication, raspberrypi
---


title: MPU-6050 - angle drift

text:
# Question
Title: MPU-6050 - angle drift
**Setup**

* Windows 7 Entreprise
* MPU-6050 : GY-521 breakout
* Arduino Nano (chinese) with CH340 FTDI driver
* Arduino IDE 1.6.12
* Library for the gyro

---

**Problem**

When I run my code, the MPU will detect the angles at a good enough accuracy, but when I leave it on the table, the MPU starts drifting. Its not anything major, yet, but on something like a rocket guidance system, these values can srew up many things.

---

**Actual questions**

* Is this a common problem?
* Why is this happening?
* What is the best way to solve it?

---

**Note**

I'll include the code if you guys really need it, but I doubt its the problem because multiple codes have had the same problem.

Please do not recommend any other gyros.

# Answer
> Is this a common problem?

Yes it is. The drift is a common problem.

> Why is this happening?

The drift results, in general, from the fact that to calculate the angles it is made an integration. The errors and noises present in the inicial variable before integration (in this case angular velocity) will be "summed" over time. For simplicity, let's say your gyro is perfect with noise free but it has a small offset , and lets considere only rotation in one axis, meaning:

```
Ang_Velocity(x) = Real_Ang_Velocity(x) + offset_x

```

if this was the case, the sensor standing still should output only:

```
Ang_Velocity(x) = 0 + offset_x

```

now using the integral over time results in an output of:

```
Angle(x) = int[Ang_velocity(x)] = offset_x * t

```

For example note that using a simple 0.01 offset over axis x, causes the sensor to output 1rad angle after 100 seconds and in fact the sensor didn't move at all.

Taking this as example the sources of errors I'm aware of are:

* **offset:** already talked
* **scale factor:** is the relation between input and output
* **scale factor linearity:** sometimes the scale factor at slow speeds are not the same as speed increases.
* **temperature:** (not 100% sure!) this changes the sensitivities of axis. Majority of digital sensores already come with an integrated temperature sensor. If not auto compensated, there will be probably information on the datasheet to guide you how to compensate for this. If your application will not take high temperature variations, it is common sense to let the sensor achieve thermal internal stability and then do a simple calibration.
* **Random Walk:** This is probably the hardest to process. In general is assumed that the noise is a normal distribution with mean of zero and a certain variance (white noise). If that was true, the integral over time, as time increases would go to zero (because the mean is zero). However, the noise is usually not evenly distributed in the spectrum, causing the integral to not tend to zero (Brownian noise).

> way to solve it?

The first two are simple using calibration. You must do a series of tests at diferent rotation speeds to determining the non-linearities, offsets (at zero speed) and scales factors for each axis. Then your sensor equation of the module should take acount for this facts. Usually the sensor datasheets describes the equation to be used. Take a look at **IMU\_Zero** in the repository you gave.

As for the other two, it depends on the application. Typically the temperature will be considered stable after a few working minutes. If temperature is important datasheet will probably be your best friend.

As for random walk. The most common use to take into account corrections of this is to use an accelerometer (and in some cases magnetometer) and apply a sensor fusion algorithm generally denoted as AHRS. Some examples go as:

If you really want to model the noise of the sensor to improve the result, you probably should search for Allan variance but you will need a lot of basis in stochastic processes and statistical theory

Some devices like yours already have an Motion processor built-in, that makes a similar application of (probably) one of these filters. See examples **MPU6050\_DMP6.ino**

If you just want an implementation, just google for AHRS arduino. Github as a lot of examples used by other sensors that are easy to adapt. For instance and this

More information on IMU errors
> 9 votes

# Answer
The change in yaw (rotation of the x-y plane around the z-axis) is not drift or an error that needs to be nullified. I set my MPU-6050 on the kitchen table and collected the axis outputs over a six and one half hour period. The pitch and roll values were rock solid over the entire period. The Yaw values, however, constantly change at an extremely linear rate of 0.25 degrees per minute. That's 15 degrees per hour. The planet you are on is rotating at that rate. This is not a coincidence.
> 1 votes

---
Tags: gyroscope
---


# Question
Title: Differences between Arduino Uno SMD and Uno DIP
I just bought an Arduino Uno (SMD version) from W11Stop and want to know whether there is any other difference between Arduino UNO DIP and Arduino UNO SMD besides knowing that the SMD version doesn't have a DIP chip which can be replaced?

I am just a beginner so please help me if I am wrong!

# Answer
> 2 votes
As far as I know there is no real difference, at least not directly related to the SMD.

There are many clones which sometimes have slightly different behavior or protection.

But for the SMD the only disadvantage is it cannot (easily) be replaced.

I have one original one (with DIP) and several clones and so far I did not found any difference, except for having mini USB instead of normal USB.

# Answer
> 1 votes
Actually, there are no different on the functionality. But you may can't go through some features, because the ATmega can be remove it manually without any special tools. One of the useful case as ArduinoISP for burning bootloader to another ATmega328p AVR.

For personal suggestion, you just needed one piece of PDIP/DIP version UNO, others boards you can consider the lower cost, such as Nano, Pro Mini(Without USB-to-TTL), UNO(SMD).

For the USB-to-TTL, there are many options in the market, watch this video to explain what are they different.

# Answer
> 0 votes
There's no actual difference, but just the "look". Neither version of it should bother you at anything, but there are 2 things, worth mentioning.

1. The IC can fall out of DIP socket: I've been told a few times this already, but never had experienced such behaviour or been at occasion, where that happened. So here's a **disadvantage** for DIP cases.
2. DIP has also possibility of changing waaaaaaaaaay easier the microprocessor in case of failure. You simply grab it off (even might with a help of a screwdriver) and you're ready to put in a new one. So this is an **advantage nr. 1**. I also like to use an Arduino in projects, but not the whole board. I just take the IC (atmega328) and use 2 ceramic caps with 16MHz quartz and I've got my own arduino on other PCB - in this case, you can use Arduino UNO board as a programmer. This is how to avoid installing FTDI or CH340 chip on other boards. **Advantage nr. 2.**

---
Tags: arduino-uno, arduino-uno-smd
---


title: put_index = (put_index + 1) % 100;

text:
# Question
Title: put_index = (put_index + 1) % 100;
Can someone interpret the code in the Title line for me? Specifically the function of the "%" sign? It is a line having to do with a 100 element circular buffer.

# Answer
> 3 votes
The `%` is the modulo operator in C/C++, which basically means:

1. Divide the value to the left of the `%` by the value to the right of it
2. Discard the quotient and keep only the remainder.

For instance, `10 % 5 = 0`, because 10/5 = 2 with no remainder. Whereas `11 % 5 = 1`, because the remainder of the division is 1.

In your case, the modulo operator is likely being used to keep the value of `put_index` less than 100 at all times. If it became 100 because of the operation `put_index = put_index + 1`, then the modulo operation would make the 100 into 0, so `put_index` will keep incrementing 0–99 repeatedly.

# Answer
> 1 votes
In C the % symbol is the modulo operator : https://en.m.wikipedia.org/wiki/Modulo\_operation

---
Tags: loop
---


# Question
Title: DIY printer + Arduino. Can I use the position sensor? Multithreading?
I'm trying to make a computer-controlled painter/drawer/CNC, something like this, from an old junk printer that didn't work... I have got as far as a working motor shield that can move the sliding trolley back and forth by running the DC for a short amount of time, and running the stepper that would be "paper feed". But it is currently just some gears and roller.

1: Assuming I can attach the paper-feed gear to a platform to move it in both X and Y directions, is there still no way I can multithread Arduino code? Searching for this, I found results in some really old howtos/forums that say you cannot, but you can fake it by doing one thing then another. I would want a serial command to send the Arduino to say, "start 3mm right" and while doing so, run "3mm forward" for example for a diagonal line. I've only run this on commands that are run intermittently and can block while the command is running like so.

2: There is a clear "tape" with lines on it that goes through the sliding trolley and has a ribbon coming out of the sliding trolley that I assume is reference indicating that it is x mm away from the end, that lets the printer see how long to move. Would it be feasible to reverse-engineer this type of device to use in this custom application? Could this be done with an oscilloscope output connected to pins on the ribbon?

# Answer
You can multi*task* on arduino by doing stuff for one task for a bit and then do stuff for another task for a bit and switch back and forth like that.

However many arduino libs tend to rely on blocking calls and don't support giving control back to calling code so time spent in `delay()` calls can be used by other code.
> 0 votes

# Answer
I recommend using the AccelStepper library (installable via the Library Manager) which will allow you to drive multiple stepper motors at once without blocking commands.

1. It's possible to multithread on an Arduino but it's a sophisticated operation that you don't actually need to do for this application. Better instead to call one motor move, then the next, in rapid succession in your main loop. The AccelStepper library sort of builds this in when you're using it for position-based control; you tell one motor where to move and then run `motor.run()` as often as possible in the loop to actually send the commands to your driver to move it. (You *also* tell the other other motor to move, and also run `motortwo.run()` just as often as `motor.run()` in the loop; neither command takes much time at all to run.) For precisely coordinated multi-motor moves, look at the `MultiStepper` example included in the library, but note that the sort of thing I'm describing, implemented in the similarly-named `MultipleSteppers` example, will do the trick for you.
2. Regarding that "clear tape," my suspicion is if you look close, you'll find it's got lots of very narrowly spaced black and clear bands. It is used to report position data back to the motor driver. It more than likely has a photointerruptor that reads its movement. You can read the speed (but not absolute position) of that tape by monitoring the clear and black sections moving through the photointerruptor. For higher precision of data, likely necessary because the tape will be moving relatively fast, you'll likely want to use an interrupt feature of the chip to watch the ticks as they go by, which is designed to take precedence over other would-be simultaneous operations the chip is doing.

Good luck with the project!
> 0 votes

---
Tags: arduino-uno
---


title: SIM800L can't send SMS

text:
# Question
Title: SIM800L can't send SMS
I have a SIM800L module (green board). I used this to test my module.

In that page, it use a SIM800L red board with a 3.7v LiPo battery. But I directly connected 5v from the Uno to the module.

* GND \>\>\> GND
* RX 10 \>\>\> TX
* TX 11 \>\>\> RX
* 5v \>\>\> Vin

I see "Message Sent Successfully!" message in COM window but nothing happened.

I can not find the problem.

The SIM800L module (green board) specification is here.

The SIM800L module (red-green-blue boards) is here.

# Answer
> 0 votes
I used a Power Supply and tested the board and SIM800L with it.

At the beginning, the SIM800L only uses a max of 100mA (V = 5v) and after finding the network only 10mA. In this situation the message is sent. I tested it with 4.2v but no message was sent.

It seems it needs 5v to be applied. The 5v of the Uno will be reduced to reach the SIM800L and so no message is sent.

---
Tags: arduino-uno, gsm
---


# Question
Title: How to add a pedestrian button code to a traffic light with ultrasonic sensor?
So I have a project to create a 2 set of traffic lights which would detect a car coming and stopping on the ultrasonic sensor and my code would allow the traffic lights to loop and let the car through. But now I also have to add a pedestrian code in for the pedestrians to press the button, the traffic lights to loop back to red and give 30 seconds of crossing time.

I did the ultrasonic sensor traffic lights code already and some of it seems confusing but somehow works quite well. I'm not familiar with the buttons and looping the traffic lights correctly back to red so I need help to add a pedestrian crossing code to this code:

```
// Variables for Station 1 Traffic Light Components
const int Red1LED = 9;
const int Yellow1LED = 2;
const int Green1LED = 3;
const int GreenArrow = 4;
#define trigPin 12
#define echoPin 13
// Setup Variables for Station 2 Traffic Light Components
const int Red2LED = 5;
const int Yellow2LED = 6;
const int Green2LED = 7;
const int GreenArrow2 = 8;

void setup() {

  pinMode(Red1LED, OUTPUT);
  pinMode(Yellow1LED, OUTPUT);
  pinMode(Green1LED, OUTPUT);
  pinMode(GreenArrow, OUTPUT);
  pinMode(Red2LED, OUTPUT);
  pinMode(Yellow2LED, OUTPUT);
  pinMode(Green2LED, OUTPUT);
  pinMode(GreenArrow2, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
 Serial.begin(9600);
  // Set Initial state of all red LED to HIGH
  digitalWrite (Red1LED, HIGH);
  digitalWrite (Red2LED, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
 long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  //delayMicroseconds(10); // Added this line
  //digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  Serial.println(distance);
  if (distance < 20) {  // This is where the LED On/Off happens
     delay(1000);  //  1 Seconds of Red
  digitalWrite(Green1LED, LOW);  //  Sets Red1 OFF Green ON
  digitalWrite(Yellow1LED, HIGH);
  delay(1000);  // 1 Seconds of Green
  digitalWrite(Yellow1LED, LOW);  //  Sets Green1 OFF Yellow ON
  digitalWrite(Red1LED, HIGH);
  delay(1000);  // 1 Seconds of Yellow
   // Station 2 Timing
  delay(1000);  //  1 Second of Red
  digitalWrite(Red2LED, LOW);
  digitalWrite(GreenArrow2, HIGH);  //  Sets Red2 OFF Green ON
  delay(1000);  // 1 Second of Green
  digitalWrite(GreenArrow2, LOW);
  digitalWrite(Green2LED, HIGH);  //  Sets Green ARROW OFF Yellow ON
  delay(1000);  // 1 Second of Yellow
  digitalWrite(Green2LED, LOW);
  digitalWrite(Yellow2LED, HIGH); // Sets Green 2 OFF YELLOW OFF
  delay(1000);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Red2LED, HIGH);

   digitalWrite(Red1LED, LOW);
  digitalWrite(GreenArrow, HIGH);
  delay(1000);
  digitalWrite(GreenArrow, LOW);  //  Sets Yellow1 OFF Red ON
  digitalWrite( Green1LED, HIGH);
}
  else {
   digitalWrite(Red1LED, LOW); // When the Red condition is met, the Green LED should turn off
  digitalWrite(Red2LED, HIGH);
  digitalWrite(GreenArrow, LOW);
  digitalWrite(Green1LED, HIGH);
  digitalWrite(Yellow1LED, LOW);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Green2LED, LOW);
  digitalWrite(GreenArrow2, LOW);

  }
}

```

I NEED HELP ASAP PLEASE. Due tomorrow by 12 am. It is extension so I am not that worried if I don't get help by the deadline but if I still do after the deadline I can still learn so don't hesitate to post.

# Answer
> 2 votes
Thank you for making it clear that this is course work. You are asking for help to do the extension, but by your own words you don't understand how the core code works. I have to be honest I can't be bothered to read the code, it looks horrible. If I was your teacher I would quit, because I have failed to teach you one of the most fundamental aspects of coding. "You write it once but it gets read many times", it is ALWAYS worth spending a few minutes making the code look pretty! (If you teacher can't be bothered to read it, you aren't going to get 100%!)

1. Comments - commenting out code is not the best use for // explaining **why** you are doing what you are doing is.
2. Its good that you have defined variables to identify you pins, but you have two identical sets of variables, so you could have used an array, a structure or an array of structures. (These might be more advanced than where you are at the moment, sorry if that's the case).
3. Breaking you code down into bite sized pieces make it more readable. That start of your loop contains some code that could be in a function called `getDistance()`
4. Turning the lights on and off in the way you are doing it is open to errors. You could turn the red light on and the green light on. If you made a class to represent the lights then you could have a function that turned off all of the lights and only turned on the one you wanted. You wouldn't need to store the state.

Example code (not tested or compiled)

```
class Lights
{
  public:
    enum eLight {Red, Amber, Green, GreenArrow, GreenPedestrian, RedPedestrian, eMaxLight};
    Lights(int[] pins)
    {
      for (int l = 0; l < eMaxLight; ++l)
        pinMode (pins[l], OUTPUT);
    }
    ~Lights()
    {}
    void setLight (eLight newLight)
    {
       for (int l = 0; l < eMaxLight; ++l)
         digitalWrite(m_Light[l], LOW);
       digitalWrite(m_Light[newLight], HIGH);
    }
}

```

You probably want to look at a state machine. List all the possible LEGAL combinations and then create a enum with each of those states in and then write a function that moves from a state to the next legal state, you will need conditionals for has the button been pressed. This should give you a working system with a pedestrian button that hopefully you understand.

---
Tags: programming, button
---


title: Which container to use?

text:
# Question
Title: Which container to use?
So for my project, I am measuring heartbeat of a person in a span of 10s. However, as the number of heartbeats may differ for each person, is it wise to use a vector?

# Answer
> 1 votes
No, you don't want a vector, for a number of reasons:

1. There is no "vector" unless you add extra (unsupported) code.
2. Vectors use dynamic memory. Arduinos don't work well with dynamic memory.
3. It's pointless anyway.

Just allocate an array big enough to contain enough timestamps. In a 10 second period, if you get more than 100 beats, the person you are measuring the heart rate of is most likely in a noticeably "unfortunate" state. That's 600bpm. That's entering panicked mouse territory.

Even with that extreme number of beats an array of 100 32-bit values is only 400 bytes.

---
Tags: array, vector
---


title: how can I send a variable to println?

text:
# Question
Title: how can I send a variable to println?
this is my method

```
void mensaje_sms()
{
  string numero = "777777";  // this is my variable
  SIM900.print("AT+CMGF=1\r");
  delay(100);
      SIM900.println("AT+CMGS=\"591"numero"\"");
//IM900.println("AT+CMGS=\"59177777777\""); //only in this way does it work
      delay(100);
      SIM900.println("SEND NUMERO VARIABLE RODO");
      delay(100);
      SIM900.println((char)26);
      delay(100);
      SIM900.println();
      delay(5000);
      Serial.println("SMS sent successfully");
    }

```

***how can I send a variable to println?***

# Answer
Change:

```
SIM900.println("AT+CMGS=\"591"numero"\"");

```

to

```
SIM900.print("AT+CMGS=\"591");
SIM900.print(numero);
SIM900.println("\"");

```

Note that only the final call is to `println()` (which just prints a carriage-return character at the end.)
> 3 votes

---
Tags: arduino-uno, print
---