title: How to map sensor analog output voltage

text:
# Question
Title: How to map sensor analog output voltage
My sensor output voltage values ranges from 0.6 V - 3 V. How can I convert this voltage values to ppm in the range 0-1000? Upon exposure to CO gas: 0 ppm = 0.6 V , 500 ppm = 1.52 V and 1000 ppm = 3.01 V. Which means that the sensor cannot detect under 214 ppm (approx). Can you please help with mapping the sensor output values as ppm in the serial monitor? thnk u

```
// the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);

      // print out the value you read:
      Serial.println(voltage);

    }

```

# Answer
On page 4 of the datasheet,

> Left side value of detection range (zero point) is corresponding to left side value of voltage output range,but right side value of detection(max detection value) is not corresponding to the right side value of voltage output range.

Thus, 0ppm would correspond to 0.6V, for CO. And 1000ppm *does not* necessarily correspond to 3V.

Assuming that 500ppm = 1.52V was obtained from the "inspection report", you now have two reference points, (0, 0.6) and (500, 1.52).

Further below on the same page, a formula for `N` is given, which, points towards a linear response of Vo with respect to ppm. Thus, you can use the `map()` function to do the linear mapping from voltage to ppm.

Note that `map()` only works with integers, so instead of mapping voltage (0.6 - 1.52) to ppm, you should directly map the analogRead value (123 - 311) to ppm to get better accuracy. Other wise, implement your own mapping using floats.
> 2 votes

# Answer
This Codes works for you :)

```
int SensorPin = A0;
int Readings;
int Min = 0;    // This is the Min reading of the sensor
int Max = 614; // This is the Max reading of the sensor
int Desired_Min = 0; // this is the desired number that you want converted with min reading of the sensor
int Desired_Max = 1000; // this is the desired number that you want converted with max reading of the sensor

void setup(){
 Serial.begin(9600);
 pinMode(SensorPin, INPUT);
 }

void loop(){
  Readings = analogRead(SensorPin);
  Readings = map(Readings, Min , Max, Desired_Min, Desired_Max);
   Serial.println("Mapped Value:"+Readings);

}

```

I Strongly prefer you to note the min and max reading Value of your sensor with arduino and replace the 'Min' and 'Max' according to that in the programm....
> 1 votes

# Answer
In the main loop, `sensorValue` is assigned to store the raw analog value read from the potentiometer. Arduino has an `analogRead` range from 0 to 1023, and an `analogWrite` range only from 0 to 255, therefore the data from the potentiometer needs to be converted to fit into the smaller range before using it to dim the LED.

In order to convert this value, use a function called `map()`:

```
outputValue = map(sensorValue, 0, 1023, 0, 255);

```

`outputValue` is assigned to equal the scaled value from the potentiometer. `map()` accepts five arguments: The value to be mapped, the low range and high values of the input data, and the low and high values for that data to be remapped to. In this case, the sensor data is mapped down from its original range of 0 to 1023 to 0 to 255.

The newly mapped sensor data is then output to the `analogOutPin` dimming or brightening the LED as the potentiometer is turned. Finally, both the raw and scaled sensor values are sent to the Arduino Software (IDE) serial monitor window, in a steady stream of data.

```
// These constants won't change. They're used to give names to the pins used:
const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 255);
  // change the analog out value:
  analogWrite(analogOutPin, outputValue);

  // print the results to the Serial Monitor:
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);

  // wait 2 milliseconds before the next loop for the analog-to-digital
  // converter to settle after the last reading:
  delay(2);
}

```

Few useful commands while mapping any analog output values:

* map()
* analogRead()
* analogWrite()
* serial()
* AnalogInput - Use a potentiometer to control the blinking of an LED.
* AnalogWriteMega - Fade 12 LEDs on and off, one by one, using an Arduino or Genuino Mega board.
* Calibration - Define a maximum and minimum for expected analog sensor values.

```
/*
  Calibration

 Demonstrates one technique for calibrating sensor input. The sensor readings
  during the first five seconds of the sketch execution define the minimum and
  maximum of expected values attached to the sensor pin.

  The sensor minimum and maximum initial values may seem backwards. Initially,
  you set the minimum high and listen for anything lower, saving it as the new
  minimum. Likewise, you set the maximum low and listen for anything higher as
  the new maximum.

  The circuit:
  - analog sensor (potentiometer will do) attached to analog input 0
  - LED attached from digital pin 9 to ground

  created 29 Oct 2008
  by David A Mellis
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Calibration
*/

// These constants won't change:
const int sensorPin = A0;    // pin that the sensor is attached to
const int ledPin = 9;        // pin that the LED is attached to

// variables:
int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value

void setup() {
  // turn on LED to signal the start of the calibration period:
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);

  // calibrate during the first five seconds
  while (millis() < 5000) {
    sensorValue = analogRead(sensorPin);

    // record the maximum sensor value
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }

    // record the minimum sensor value
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }

  // signal the end of the calibration period
  digitalWrite(13, LOW);
}

void loop() {
  // read the sensor:
  sensorValue = analogRead(sensorPin);

  // apply the calibration to the sensor reading
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

  // in case the sensor value is outside the range seen during calibration
  sensorValue = constrain(sensorValue, 0, 255);

  // fade the LED using the calibrated value:
  analogWrite(ledPin, sensorValue);
}

```
* Fading - Use an analog output (PWM pin) to fade an LED.
* Smoothing - Smooth multiple readings of an analog input.
> 1 votes

---
Tags: arduino-uno, sensors, voltage-level
---


title: Only 2 decimal places in printed float

text:
# Question
Title: Only 2 decimal places in printed float
There was a similar thread before but it didn't solve my problem. I had an issue with sending GPS data, which is float, and I couldn't receive the float with the same amount of significant figures as I was sending. I always received a number with 2 digits after a decimal point. So I started debugging and wrote this simple code just to check if floats work as intended:

```
#include <SoftwareSerial.h>
void setup() {
Serial.begin(9600);
}
void loop() {
float number1;
number1=1.45436;
Serial.print(number1);
delay(200);
}

```

And the serial monitor showed 1.45 as an output. How can increase the precision of the float I am saving in memory?

# Answer
By default, the Serial print function shows only 2 decimals, however I'm sure the float has the full (unrounded) value, even if it does not show it.

You can read about it in the official documentation here

With the following code you can use more decimals (fragment from the official documentation):

```
-Serial.println(1.23456, 0) gives "1"
-Serial.println(1.23456, 2) gives "1.23"
-Serial.println(1.23456, 4) gives "1.2346"

```

Also, probably the next link (PrintFloat) will help:

PrintFloat

It works roughly by iterating through the digits and printing them.
> 17 votes

# Answer
By default, `Serial.print()` prints floats with two decimal digits.

```
float num = 7.875;
Serial.println(num, 4);

```

will print `num` with 4 decimal digits, thus: 7.8750.

The precision of float is not decreased in the way you think it decreases. See this answer for a better explanation.
> 9 votes

# Answer
Multiply your float by 10000 (or whatever number you wish), send it as an integer, and convert the received integer back to float.

Alternatively change the library or write your own.
> 1 votes

---
Tags: arduino-uno, serial, arduino-ide, float
---


title: ESP32 wifi module

text:
# Question
Title: ESP32 wifi module
I want to connect my arduino uno rev3 to wifi. The best option I found was esp8266. After searching about it I found that it is succeeded by esp32. But I am not able to find much information about it. So I just wanted to ask if esp32 module exists as a addon to arduino or is it a board on its own. It will be really helpful if somebody can send the link from where I can buy this module(and not the board) and how to connect it to arduino.

# Answer
> 0 votes
ESP32 is not a replacement for the ESP8266. There is quite a bit of info out there, but mostly in Chinese. If you were to use an ESP32 to provide WIFI its like using a Formula 1 car as a mobility scooter (Rascal in American?) It will do the job, but its really not suitable.

You can buy ESP32 on eBay or AliExpress, but really you shouldn't for this task. Stick with an ESP8266.

BTW People will mark this as off topic, because it isn't strictly Arduino related.

---
Tags: arduino-uno, wifi, esp32
---


# Question
Title: Arduino Leonardo(Atmega32u4) - Detecting if USB is connected to a computer?
The closest thing I can find is if(Serial) but that only returns true if there's a serial port open.

The function I want, ideally, should:

Return true if plugged into a computer

Return false if plugged into a USB power bank

Return false if not plugged in at all(Running off of its own lithium cell)

# Answer
> 5 votes
`ADDEN` of `UDADDR` is set if the '32U4 has been assigned a USB address by the host and the firmware wants to enable USB connectivity.

```
UDADDR & _BV(ADDEN)

```

---
Tags: arduino-leonardo, atmega32u4
---


# Question
Title: Check to see that String only contains .csv style numbers
I'm looking to determine if an Arduino **S**tring contains any other character than those that would be in the `[number],[number]'\r''\n'`where `[number]` could be positive or negative.

I know I can run a for down the entire string and use `if(isDigit([char]) || isWhitespace([char])||[char]=='-')` however, I imagine there's a better way to do this.

Could I (for example) convert the String to an array of values and search the array for any value that doesn't correspond to the characters I'm looking for? Or is there a better way to check this out?

# Answer
There is a better way, which is called regular expressions (or regexp). However, afaik these are not supported by Arduino by default.

However, I'm sure you can find some 'generic C++' class that can handle them.

For that, it's best to check on StackOverflow.com probably.

After a short check, on the Arduino forum there is a library available for regexp:

library

It is created by Nick Gammon, so all credits are for him.
> 1 votes

---
Tags: arduino-mega, string
---


# Question
Title: How to convert an hex string to an array of bytes?
How to convert the char array to Byte array? I tried every method but it doesn't work.

```
char CardNumber[8] = "B763AB23"; // Length is 8, basically it's in Hex
                                 // B7 63 AB 23

```

I need to convert it into Byte array to `byte CardNumberByte[4];` So basically, it should be like :

```
CardNumberByte[0] = B7;
CardNumberByte[1] = 63;
CardNumberByte[2] = AB;
CardNumberByte[3] = 23;

```

I am unable to find any solution for that.

# Answer
There are indeed many methods (and they all work if done right).

Is it always a lenght of 8 ? That means it is 32-bit unsigned long number. The strtoul can convert it to a long. Use '16' for the base. If you need the seperate numbers, you can shift the unsigned long and convert to bytes or use a union.

It is also possible to do with a for statement can convert each character of the input to a value: forum.arduino.cc: convert HEX (ASCII) to a DEC int

\[**ADDED**\]
Thank you @goddland\_16 for providing a full sketch. I could not stay behind and wrote a sketch with strtoul.

```
char *CardNumber = "B763AB23";
byte CardNumberByte[4];

void setup()
{
  Serial.begin(9600);
  Serial.println("With strtoul");

  // Use 'nullptr' or 'NULL' for the second parameter.
  unsigned long number = strtoul( CardNumber, nullptr, 16);

  for(int i=3; i>=0; i--)    // start with lowest byte of number
  {
    CardNumberByte[i] = number & 0xFF;  // or: = byte( number);
    number >>= 8;            // get next byte into position
  }

  for(int i=0; i<4; i++)
  {
    Serial.print("0x");
    Serial.println(CardNumberByte[i], HEX);
  }
}

void loop()
{
}

```
> 2 votes

# Answer
Here is a simple solution to your question. I took each character, checked against its hexadecimal character and returned as a combination.

```
char CardNumber[] = "B763AB23";
byte CardNumberByte[4];

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

void loop() {
  for(char i = 0; i < 4; i++)
{
  byte extract;
  char a = CardNumber[2*i];
  char b = CardNumber[2*i + 1];
  extract = convertCharToHex(a)<<4 | convertCharToHex(b);
  CardNumberByte[i] = extract;
  Serial.println(CardNumberByte[i], HEX);
}

  while(1);
}

char convertCharToHex(char ch)
{
  char returnType;
  switch(ch)
  {
    case '0':
    returnType = 0;
    break;
    case  '1' :
    returnType = 1;
    break;
    case  '2':
    returnType = 2;
    break;
    case  '3':
    returnType = 3;
    break;
    case  '4' :
    returnType = 4;
    break;
    case  '5':
    returnType = 5;
    break;
    case  '6':
    returnType = 6;
    break;
    case  '7':
    returnType = 7;
    break;
    case  '8':
    returnType = 8;
    break;
    case  '9':
    returnType = 9;
    break;
    case  'A':
    returnType = 10;
    break;
    case  'B':
    returnType = 11;
    break;
    case  'C':
    returnType = 12;
    break;
    case  'D':
    returnType = 13;
    break;
    case  'E':
    returnType = 14;
    break;
    case  'F' :
    returnType = 15;
    break;
    default:
    returnType = 0;
    break;
  }
  return returnType;
}

```
> 0 votes

# Answer
A char array is a byte arrray. No difference whatsoever

What you are attempting to do is a conversion of hex string to byte. For that you have to determine if you are scanning left to right or right to left.

After that convert a char in the string to a half byte.

From there you shift the half byte left and or it with the next half byte until the whole string has been exhausted.
> 0 votes

---
Tags: arduino-uno, arduino-ide
---


title: Convert int to char[]

text:
# Question
Title: Convert int to char[]
I'm looking to convert an int value to a char array. currently I've found the following will return `[number]`

```
int num = [number]
str = String(num);
str.toCharArray(cstr,16);
Serial.println(cstr);

```

However, per Majenko's The Evils of Arduino Strings I feel like this code would make my Arduino's heap look like swiss cheese. Is there a better way to change an `[int]` into a `char[n]` array that avoids the **S**tring class?

# Answer
`itoa` is the best route:

```
int num = 1234;
char cstr[16];
itoa(num, cstr, 10);
-> "1234"

```

You can read more about using it here.

If you want more control over the format of the number (and don't mind the increased PROGMEM usage) you can use `sprintf` (or the more secure `snprintf`) to format it:

```
sprintf(cstr, "%05d", num);
-> "01234"

```

Or with PROGMEM string constant:

```
sprintf_P(cstr, (PGM_P)F("%05d"), num);
-> "01234"

```

Or with more values:

```
sprintf_P(cstr, (PGM_P)F("%02d:%02d:%02d"), hours, minutes, seconds);
-> "03:23:11"

```
> 17 votes

---
Tags: arduino-mega, string, c-string
---


# Question
Title: Unable to compare char from radio (RF24)
The code below is receiver code using nRF24L01. In the loop section I'm comparing the char that was being sent from the Arduino transmitter. In this case the char array says "I'm off" just like the char array `compare` below. Even though the text is the same, it does not do what it is supposed to do.

Basically the if function below does not seem to work for some reason, both are char arrays (the text\[32\] and compare\[32\]) and both will have the same value which is "I'm off" yet it is not registered as the same thing. I cannot figure out what is wrong with the code, please help.

This is the receiver code. The question is about the if function in the loop below.

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char text[32] = "";
    char compare[32] = "I'm off";
    radio.read(&text, sizeof(text));
    Serial.println(text);
    Serial.println(compare);
    // this is the problem  -->
    if (text == compare) {
      // it is supposed to print this but it does not -->
      Serial.println("not on");
    }
  }
}

```

This is the transmitter code

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";
const int button = 5;

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  pinMode(button,INPUT);
}

void loop() {
  int reading = digitalRead(button);
  if(reading == HIGH) {
    // send a message to the radio
    const char text[] = "I'm on";
    radio.write(&text, sizeof(text));
    delay(1000);
  }
  if(reading == LOW) {
    // send a message to the radio
    const char text[] = "I'm off";
    radio.write(&text, sizeof(text));
    delay(1000);
  }
}

```

# Answer
Finally i found a solution, turns out the problem was that Arduino will not comparison between char == char like this if (char == char). then i decided to CONVERT char to string. this is the example code for Receiver.

```
void loop() {

  if (radio.available()) {
    char text[32] = "";
    char compare[32] = "im off";
    radio.read(&text, sizeof(text));
    // you must convert char to String for it to work
    test1 = String(text);
    test2 = String(compare);

    Serial.println(text);
    //Serial.println(compare);

    if (test1 == test2)
    {
    delay(500);
    Serial.println("not on");
    }

  }

```

i have convert char to String then i compare the value of it, and it works like a charm. if any of you have the same problem with me and solve it after this please give me thumbs up
> 1 votes

# Answer
That is not a good way to solve it. That is a hack. The String class does bad things on microcontrollers and it is something you should try to stay away from. What you need to compare two char arrays is the strcmp function.

```
if(strcmp(someCharArray, anotherCharArray) == 0){
    // the strings are the same
}

```

Use google to find out more about strcmp.
> 1 votes

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


title: Open source PLC Wifi

text:
# Question
Title: Open source PLC Wifi
I'm working on a project that involves a device called the plduino (aka Open Source PLC). This is the website for the device:

https://www.digital-loggers.com/plc.html

and the GitHub:

https://github.com/digitalloggers/PLDuino

Using the examples on the GitHub, I've been able to figure out other parts- storing on the SD card, the GUI, digital IO, etc. But I haven't been able to figure out the WiFi module (which seems to be through a ESP8266 device). I looked through the libraries directory on the GitHub link, but didn't find anything that looked like it connected to the internet or could send or receive data. The documentation says the device can connect to wifi, but is otherwise very little help.

Has anyone used this before? How do I make this device connect to wifi?

# Answer
> 1 votes
This is not particularly easy to figure out. The ESP8266 is addressable via a serial port. The ESP8266 firmware is called NodeMCU, which sits on top of the ESP8266 firmware and allows you write Lua code to implement custom Wifi functions. The PLC comes with example Lua that starts a webserver and publishes a webpage that allows you to check and set the status of the PLC (but only if you connect to the PLC, which is in access point mode.)

If you want it to behave like wifi on a normal desktop computer, you have to do some Lua programming (I could not find any Lua code online that did basic things out of the box, but there are a fair number of examples and snippets on the NodeMCU sites.)

In spite of how cool this device is, I ultimately decided it was just too much work to get the Wifi integration working (the Arduino stuff is of course pretty easy). You also have the problem of how to get your data logs somewhere. Since the data is on the Duino and the ESP8266 is the web interface, you either have to poll the Duino (which the example code does) and upload to a site (e.g. AWS), or log the data on the Duino, then send it over the serial port for upload -- MORE Lua and Duino coding. Plus if you want to put your data on AWS IoT (for example) the Duino/NodeMCU technically does not support the TLS 1.2 and X.509 cert handling you need to register (although they are apparently some workarounds now.) Life. Is. Too. Short. For. That.

I switched to Raspberry Pi, which is about 1000 times simpler, even though it does not have the cool features like open collectors and optical isolators. I'm now looking at Pi enclosures, such as the nice BC packaging from Phoenix Contacts. I decided it was simpler to make my own custom PLC for my home HVAC automation project than it was to code the DL-PLC. Bummer. Maybe they'll do a Pi version of this someday.

The repositories for my DL-PLC and RPi projects are on GitHub (https://github.com/dglcinc/HVAC-plc and https://github.com/dglcinc/HVAC-pi), you may find my Lua code and implementation notes useful if you want to get the wifi working on the DL-PLC. I *did* get it working in station mode (so you can join it to your home access point, address it with a DHCP IP, etc.) but that's about as far as I got.

---
Tags: wifi
---


# Question
Title: How do I prevent Arduino from running on startup?
I just uploaded a sketch to my Arduino Leonardo, which presses a key on the keyboard. The code was unfortunately bugged and now as soon as the Arduino is powered on, the key is being pressed.

When I try to upload a new sketch that fixes the issue, I am unable to do so as the Arduino is executing the sketch, preventing the new sketch from being uploaded.

How can I prevent the Arduino from executing the sketch once powered on? Pressing the reset button or wiring it in does not work...

# Answer
The Leonardo should wait a couple of seconds after resetting to see if a new sketch arrives.

* Power off the board completely (remove the USB cable).
* Hold down the Reset button, and *keep it held down* (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting.
* Still holding down Reset, reconnect the USB cable.
* Start uploading a sketch that does not have this problem (eg. Blink) Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).
> 6 votes

---
Tags: arduino-leonardo
---


# Question
Title: How can I control the speed and direction of dc motor at the same time (through Bluetooth
I am working on a project of an arduino car it's simple really i know how to control the speed and direction using simple button but I was looking for an upgrade so I add a virtual joystick in my app now It can send 2 values first is the angle where the pointer of the joystick is which will be used to control the direction. And the distance between the center of the joystick and the pointer will be used to control the speed, problem is they are both int values how can I make the arduino differentiate between both values ? also they would be sent simultaneously over Bluetooth which might be a problem as well

# Answer
Use delimiters to separate the two values you are sending over bluetooth.

Something like

```
"30,5\n"

```

instead of

```
"30\n"
"5\n"

```

On the Arduino side, read the the incoming string into a `char` array and add a `\0` after the last read character to make it a C string. The use `strtok()` to parse the C string and `atoi()` or `atof()` to convert the parsed C strings to an `int` or `float`.

See this answer for more information about parsing a string.
> 0 votes

# Answer
I would say it would be the best way to use a H-bridge motor driver such as L293N. With it you can simply drive a DC motor both ways and even control it's speed.

Make the connection as shown on picture below, but connect wires of both motors to the same motor and PWM\_SPEED\_CTRL are channels connected to the Arduino. Don't forget to add relays between pins: 3-1, 6-2 and 11-1, 14-2, which would determine the turning direction.

If you don't understand certain thing, just ask and I'll try to reply ASAP.
> 0 votes

---
Tags: bluetooth, joystick
---


# Question
Title: Is it possible to run two for loops separated?
I have three funtion which describe the brightness of three LEDs. I want the seconde loop run 1 second after the first one and the third 1 second after the second one. One loop needs approximately 5 seconds. So basically I need to run three loops separated. How is this possible?

Update: So I have this code running which I can compile but does not work:

```
int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
// Update loop enablers.
switch(periodIndex)
{
case 0:
 loop1state = true;
 loop1index = 0;
 break;

case 1000:
 loop2state = true;
 loop2index = 0;
 break;

case 1500:
 loop3state = true;
 loop3index = 0;
 break;

case 4000:
 periodIndex = 0;
 break;
}

if (loop1state)
{
 for (loop1index = 0; loop1index<255; loop1index++){
  analogWrite(LED,loop1index);
 }

 loop1state = loop1index < 256;
 }

 if (loop2state)
 {
 for(loop2index = 0; loop2index<255; loop2index++)
 {
  analogWrite(LED2,loop2index);
 }

 loop2state = loop2index < 256;
}

 if (loop3state)
 {
 for(loop3index = 0; loop3index<255; loop3index++)
 {
  analogWrite(LED3,loop3index);
 }
 loop3state = loop3index < 256;
 }
 delay(10);
 }

```

# Answer
> 1 votes
No, but there is a solution to put the action in one loop (main loop).

If I understand you well, you have the following scheme:

Time\[s\] 0..1 Loop 1 1..2 Nothing 2..3 Loop 2 3..4 Nothing 4..5 Loop 3

Define a variable that keeps track of the time. Check against the current time (millis) and when within the correct 'range' perform an action. After 5 seconds start over again.

```
uint32_t lastTime = -1;

void loop()
{
    if (lastTime == -1)
    {
        lastTime = currentTime; // Initialization, can be done in setup too
    }

    uint32_t diffTime = millis() - lastTime;

    if (diffTime < 1000) // 0..1 sec
    {
        DoLoop1();
    }
    else if (diffTime < 2000)
    {
         // Do nothing();
    }
    else if (diffTime < 3000)
    {
       DoLoop2();
    }
    else if (diffTime < 4000)
    {
        // Do nothing
    }
    else if (diffTime < 5000)
    {
       DoLoop3();
    }
    else // diffTime >= 5000
    {
         lastTime == currentTime; // Reset after 6 s
    }
}

```

## Update

Since you need all three loops together (and mixed), it's easier to define some variables.

```
bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

```

Too bad I don't know the conditions when a loop starts, but let's say each iteration is 10 ms, and loop 1 starts immediately, loop 2 after 1000 ms, loop 3 after 1500 ms. After 3000 ms it starts all over.

```
void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
     loop1state = true;
     loop1index = 0;
     break;

  case 1000:
     loop2state = true;
     loop2index = 0;
     break;

  case 1500:
     loop3state = true;
     loop3index = 0;
     break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
     DoLoop1(loop1index++);
     loop1state = loop1index < 256;
  }

  if (loop2state)
  {
     DoLoop2(loop2index++);
     loop2state = loop2index < 256;
  }

  if (loop3state)
  {
     DoLoop3(loop3index++);
     loop3state = loop3index < 256;
  }

  delay(10); // 10 ms
}

```

Note, not tested, but the idea shold be clear

# New update

You should not do a full loop during each switch, but only one iteration of the loop.

I did not run the sketch, just out of my head.

Some tips: print out the variables during each loop, so you get a clear idea what is happening (so all loop states and indices, and the periodIndex).

```
int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
    loop1state = true;
    loop1index = 0;
    break;

  case 1000:
    loop2state = true;
    loop2index = 0;
    break;

  case 1500:
    loop3state = true;
    loop3index = 0;
    break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
    analogWrite(LED,loop1index++);
    loop1state = loop1index < 256;
  }

  if (loop2state)
  {
    analogWrite(LED2,loop2index++);
    loop2state = loop2index < 256;
  }

  if (loop3state)
  {
    analogWrite(LED3,loop3index++);
    loop3state = loop3index < 256;
  }

  periodIndex++;
  delay(10);
}

```

# Answer
> 1 votes
Let me see if I understand correctly what you want... You want to ramp up the brightnesses of 3 LEDs, one step every roughly 10 ms, and you want the brightness ramps to start at different times. If this is the case, I would start by writing a function that handles one LED, increases its brightness by one step, and tells the caller whether the ramp is done or not:

```
// Update the LED.
// Returns true if there are brightness steps left,
// false if we have finished the brightness ramp.
bool update_led_1()
{
    static uint8_t level = 0;  // brightness level
    analogWrite(LED1, level);
    level++;  // wraps to zero when we are done
    return level != 0;
}

```

This stores the brightness level as a single byte, rather than a two-byte `int`, because I am cheap. ;-) Notice that on the last step of the ramp, the value 255 is sent to the LED, then `level++` wraps the level to zero, then the function returns false to tell us the ramp is finished. At this point, since `level` is zero, the function is ready for the next ramp.

You can copy and paste this function three times, for each of the three LEDs. Name them `update_led_1()`, `update_led_2()` and `update_led_3()`. The main loop can then go along these lines:

```
void loop()
{
    static int periodIndex = 0;  // increasing every 10 ms

    static bool led1active = false;
    if (periodIndex == 0)
        led1active = true;
    if (led1active)
        led1active = update_led_1();

    static bool led2active = false;
    if (periodIndex == 1000)
        led2active = true;
    if (led2active)
        led2active = update_led_2();

    static bool led3active = false;
    if (periodIndex == 1000)
        led3active = true;
    if (led3active)
        led3active = update_led_3();

    if (++periodIndex == 4000)
        periodIndex = 0;
    delay(10);
}

```

Notice the idiom `if (led1active) led1active = update_led_1();`. This will be executed on every loop iteration, it will increase the LED brightness if the LED is supposed to be active, and it will set `led1active` to false when the brightness ramp is complete.

There is something I do not like in the solution I am suggesting here: the copy-and-paste programming paradigm. If I am allowed to use C++ constructs, then I would encapsulate the ramp logic in a C++ class:

```
class RampingLed {
    const uint8_t pin;
    bool active;
    uint8_t level;
public:
    RampingLed(uint8_t pin)
        : pin(pin), active(false), level(0) {}
    void start() {
        active = true;
        level = 0;
    }
    void update() {
        if (!active) return;
        analogWrite(pin, level++);
        if (level == 0)
            active = false;
    }
};

```

Then the logic of the main program would appear more straightforward:

```
RampingLed led1(LED1), led2(LED2), led3(LED3);

void loop()
{
    static int periodIndex = 0;  // increasing every 10 ms

    // Start the LEDs at the appropriate times.
    if (periodIndex == 0)
        led1.start();
    if (periodIndex == 1000)
        led2.start();
    if (periodIndex == 1500)
        led3.start();

    // Update every LED.
    led1.update();
    led2.update();
    led3.update();

    if (++periodIndex == 4000)
        periodIndex = 0;
    delay(10);
}

```

# Answer
> -1 votes
If your three described for loops are the *only* thing the Arduino needs to do, then you can simply use blocking `delay()` calls. **However, this scheme will not be extensible to also satisfying other needs at the same time** \- should you anticipate those, then you should use a mechanism of time comparisons instead.

```
void loop() {
    int i;
    /* First loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_1, i);
        delay(20); //256 * 20 = 5.12 seconds
    }

    /* I want the second loop run 1 second after the first one */
    delay(1000);

    /* Second loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_2, i);
        delay(20);
    }

    /* and the third 1 second after the second one */
    delay(1000);

    /* Third loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_3, i);
        delay(20);
    }
}

```

Ultimately which type of solution is best depends on your goals - you can do things in a simple but limited way, or a more complicated but less limited one. For every 3d printer firmware that cleverly squeezes every last drop of coordinated capability out of an Arduino, there are also those that spend their days sitting in a blocking `delay()` waiting for the next trivial bit toggle task.

# Answer
> -1 votes
> So I have this code running which I can compile but does not work:

because it is wrong.

try something like this instead:

```
  time_elapsed = millis() / 1000 - start_time;  //time past start time, in seconds
       if (time_elapsed < LOOP1_ENDTIME) loop1();
  else if (time_elapsed < LOOP2_STARTTIME) do_nothing();
  else if (time_elapsed < LOOP2_ENDTIME) loop2();
  else if (time_elapsed < LOOP3_STARTTIME) do_nothing();
  ...
  else start_time+=TOTAL_TIME; //update start time

```

edit 2:

so here is the above code in action.

three simple tasks: loop1() flips D12, loop2() flips D13 and loop3() flips D8.

The time duration + gaps for those tasks are specified by the following macros:

```
#define LOOP1_DURATION  5  //time in x100 ms for easier simulation
#define LOOP1_GAP       1
#define LOOP2_DURATION  4
#define LOOP2_GAP       2
#define LOOP3_DURATION  3
#define LOOP3_GAP       6

```

from those macros, I built the ending and starting time used in the code above.

the code is long-term error free and will never lose track of time.

As you can see, it is essentially a fancy way of executing the following:

```
  do {loop1();} while (loop1's time isn't up);
  do {nothing();} while (loop1's gap time isn't up);
  do {loop2();} while (loop2's time isn't up);
  do {nothing();} while (loop2's gap time isn't up);
  ...

```

the advantage with my implementation is that each loop run is very quick and you can execute other tasks as well.

But the general idea is the same.

---
Tags: led
---


title: Having issues with Arduino + Bluetooth

text:
# Question
Title: Having issues with Arduino + Bluetooth
I am working with a combination of Teensy++ 2.0 and Sparkfun Bluetooth Modem.

The Arduino program, inside the loop, continuously reads a sensor value. If the value read is above a threshold, the Arduino transmits a "CHARACTER" over Bluetooth for any receiver.

So, inside the same loop, I check for the availability of data, and print the received character. The problem is, the received character is not what is transmitted. The received character is some garbage value.

Please let me know what is going wrong here.

```
#include <SoftwareSerial.h>

#define bluetooth Serial1

#define BAUDRATE 9600

// Analog read 0 is pin 38
int sensorValue = 0;
int SENSOR_ANALOG_READ_PIN = 0;
int LED = 17;

char toPrint = '\0';
bool sent = false;
char state = ' ';

void setup()
{

// put your setup code here, to run once:

  pinMode(LED, OUTPUT);

  Serial.begin(BAUDRATE);

  bluetooth.begin(BAUDRATE);

}

void loop() {

  // put your main code here, to run repeatedly:

  sensorValue = analogRead(SENSOR_ANALOG_READ_PIN);

  if(value > 500)

  {
      //Serial.println("HIGH");

      digitalWrite(LED, HIGH);

      bluetooth.write(state);

      bluetooth.flush();

      sent = true;

      digitalWrite(LED, LOW);

  }

  else

  {

      delay(100);

  }

  ///////////////////////////////////////////////////////////
  if((bluetooth.available()) && (sent == true))

  {

        Serial.println("printing : ");

        toPrint = (char)bluetooth.read();

        Serial.println((char)toPrint);

        sent = false;

   }

}

```

Output:

```
printing :
1
printing :
ˆ
printing :
Ì
printing :
¦
printing :
È
printing :
Ì
printing :
Ì
printing :

```

# Answer
Is the device on the other side of the bluetooth connection running at 9600 baud too ?

You say you transmit the state of the sensor - which BTW is only ever a space ' ', and never changes.

So that value gets written *out* via the bluetooth connection.

But then you read data *in* from the other party to the bluetooth communications.

It sounds like you expect the data written to the bluetooth output serial line to also be echoed back from the bluetooth input. The serial transmit and receive are separate channels. You are receiving on the bluetooth.read() whatever the device connected to it is sending, not what you write yourself.

What you are sending goes only to the other side of the conversation. The remote device would need to echo whatever it sees back for it to work how you describe.
> 1 votes

# Answer
The default baud rate for HC-05 is 38400 bauds. I was trying to set it to 9800. For some reason, that was not accepted by HC-05.

Solution: I changed the line

```
#define BAUDRATE 9600

```

to

```
#define BAUDRATE 38400

```

This solved my problem.
> 1 votes

# Answer
Are you sure you have defined your pins properly? I don't see anywhere where you define SENSOR\_ANALOG\_READ\_PIN as an input. If this is the Tx/Rx pin (I forgot the pin configuration), you can define the input pin to be somewhere else to test using the SoftwareSerial library.

This is what I did and it worked for me, hope it helps.

This link isn't for your module but the concept should be the same: Arduino AND Bluetooth HC-05 Connecting easily.
> 0 votes

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


# Question
Title: Arduino and HC-05 hardware serial issues
I have a software sending bitmap data to an Arduino Pro 5V 16MHz 328P that drives an LED display (sketch). This works using the USB-Serial adapter for the Arduino Pro with baud rates up to 500000 Baud. Now I wanted to switch to Bluetooth...
I tried connecting a 5V HC-05 module (set to 230400 Baud 8N1) to the hardware RX/TX pins on the Arduino Pro (Pins 0/1) and connect the PC to the Bluetooth serial port wirelessly (e.g. /dev/rfcomm0 on Linux). My problem is that I can receive data on the PC side using a terminal (the 'Ada' string is received), but nothing is displayed on the LED display. I have tried connecting an oscilloscope to the RX/TX pins on the Arduino and Data is arriving from the HC-05 module TX pin to the Arduino RX pin.
When the USB-Serial adapter is connected to the same pins (0/1 instead of the regular pin header) it still works as before, so there should be no connection issues.
What I tried was adding a 5kOhm resistor from the Arduino RX line to ground. (I found this hint somewhere here), but no dice... I'm not sure what's wrong, because communication IS working over the USB-Serial adapter. Any ideas on what to try?!

# Answer
A simple 10k/20k voltage divider is enough to bring the 5V arduino logic-level voltage down to ~3.3 for the HC-05. It worked for me anyway.

The default baud rate for HC-05 is 9600 baud. So unless you've changed this with AT- commands you will run into issues. Although I read that some boards default to 38400 - best check your documentation. All the cheap HC-05 boards I've tested default to 9600.
> 2 votes

# Answer
The HC-05 requires a 5V power supply and 3.3V logic. Using SoftwareSerial might be easier for you as you can use pins 8 and 9 rather than 0 and 1, because there can be issues with the USB. Are you transmitting the data you think you are, might Big/Little Endian be an issue? I can get two HC-05 devices to communicate when they are connected to the PC via serial port adapters. However when I replace the receiver with a HC-05 connected to an UNO I get intermittent garbage received. So I suspect there may be some sort of problem with PC-\>Arduino.
> 1 votes

# Answer
I've run into similar issues with the Arduino and serial communications - it's quite a pain.

There really shouldn't be an issue with your sketch if PC-\>USB-\>FTDI-\>Arduino is working since the same protocols are used (UART is UART, after all).

In regard to the BAUD rate, sure, 230400 should work just fine. For purpose of testing, though, I would slow it down to a measly 9600 or something like that just to rule out any possible issues. (Plus, if I remember right, 9600 or ~11000 is the rate at which it operates when being programmed via AT commands).

Now these are my thoughts on what the problem may be:

You said several times that you have a 5V HC-05 with level shifters. The HC-05 chip itself operates on 3.3V, so typically there is a voltage regulator on the breakout board dropping the voltage down to 3.3V for the Vcc pins and whatever else is pulled high on the chip.

However, I have never seen an HC-05 on Amazon, Sparkfun, or Ebay that actually has a true logic-level shifter on the board itself. Instead (and this is true from my experience with Ebay sellers who claim logic-level shifting built in), there is a voltage divider on the HC-05 RX pin that allows you to send a 5V signal without external resistors. But this isn't bidirectional, so your TX pin still has a logic high level of 3.3V. In short, I think your HC-05 chip really doesn’t have a logic-level shifter.

You may be thinking I’m totally wrong about this, and I very well could be since I don’t have your module in front of me, but just hear me out by reading my reasoning below.

(1) You said you can receive data on your PC. This means the HC-05 is receiving data from a 5V signal and successfully converting it to 3.3V. Great. That works!

(2) You said you were able to get an HC-05 (presumably the same model) to work with an Arduino Due in both directions. The Arduino Due operates on 3.3V, so its logic high threshold is around 2.1v.

(3) On the 5V Arduino Pro, the minimum logic high threshold is (0.6)\*Vcc -\> 3V. So if the HC-05 is transmitting a signal with a logic high of 3.3V, the Arduino is barely registering it. Factoring in resistance and noise, your signal is probably less than 3.3V. (In fact, my HC-05’s usually push out a signal of ~3V).

Reading that you can see a signal on the HC-05 TX line, but the Arduino is not registering it, I’d bet your signal is below the threshold.

So, I’d fire up your oscilloscope again and check the peak voltage to see what it is.

**Additional (Response to "what can I do?)"**

You have a few options. The best option would be to use a bidirectional 3.3V-5V level shifter, but not many people have those laying around. If you happen to have some common components, you could try building a makeshift level shifter like in the images below:

The first "level-shifter" is a a voltage comparator using an opamp. If you go this route, ground V-, tie V+ to 5V, and calculate a voltage divider for around 1.5V. (Note: use the non-inverting setup). A cheap TL272 from Radioshack should work.

The second level shifter uses two NPNs and is self-explanatory.

Note, though, that I haven't tried any of these setups nor know their frequency responses. However, the TL272 should handle signals into the MHzs, and BJTs handle high frequencies rather well. My gut tells me it should work, but just in case, I would use a low BAUD rate.
> 1 votes

# Answer
I have used HC-05 modules earlier, with baud rate 9600. But the Chinese modules I recently purchased from eBay appear to be pre-wired for 38400. The module refused to transmit anything, and was receiving garbage on the Rx side. So I changed the line

```
softSerial.begin (9800);

```

to

```
softSerial.begin (38400);

```

This solved my problem.
> 0 votes

---
Tags: serial, bluetooth
---


title: Arduino language

text:
# Question
Title: Arduino language
I'm learning with my school Arduino and how to use it etc.

I know Swift and a little bit of HTML and I would like to learn Arduino language, because I think it's easy!

What are the best resources for learning Arduino?
What are the best programs to write Arduino?
Thanks!

# Answer
> I would like to learn Arduino language, because I think it's easy!

it is C/C++.
> 3 votes

# Answer
To begin as a newbie get started with the inbuilt examples that are already given.You will learn one by one and its easy to understand anyways.Try few simple codes like LED BLINK,LED WITH SWITCH, SENSOR INPUT AND OUTPUT USING SERIAL MONITOR and you will get used to with the ARDUINO IDE.

Ofcourse the best site is www.arduino.cc but try few pdfs for Arduino beginners which are available on the internet.Try youtube if you are having any trouble working out with just text information.

Go through the book "ARDUINO PROJECTS FOR DUMMIES" LINK: http://www.dummies.com/store/product/Arduino-Projects-For-Dummies.productCd-1118551478.html

check out this link: http://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/
> 1 votes

# Answer
I guess Arduino is not the best language to learn as a beginner if you are interested in programming. Try Python, C#, JavaScript. Or directly C++ (which Arduino is actually).

Arduino has too specific usage and is limited. You wont use OOP here very often and will miss a lot of programming principles and practices.
> 1 votes

# Answer
Best resources:

I don't know what you mean with 'best programs' ... that depends on what you want. My 'best program' is probably not your 'best program'
> 0 votes

---
Tags: programming, arduino-builder
---


# Question
Title: Why is a delay(1) necessary before Wire.requestFrom?
I had a problem communicating an nodeMCU with an Arduino Pro Mini with I2C.

To find the culprit, I finally wrote an Echo Server in Arduino: it receives a byte and responds the same byte. In the nodeMCU I wrote a test program: it sends bytes to the Echo Server and verifies the response, in addition to any error conditions in the `Wire` methods.

Both processors are connected GND-GND, VCC-VCC, SDA-SDA and SCL-SCL. SDA and SCL have 10K pull-up resistors. Both are connected via USB to my PC, and I have two serial monitors to trace the execution.

In the tester program line 38 there is a `delay(1)`. If you comment it out, some `requestFrom()` fails randomly with return value != 1, but the Echo Server still received the byte.

As ATmega328 included TWI in the silicon, I can't understand what is failing here and why `delay(1)` seems to solve the problem. What I'm missing here?

**The tester program**

```
/*
 * Echo Server Test
 * Send one byte to the Echo Server and read it back.
 * Do it for bytes from 0x01 to 0xDD
 */
#include <Wire.h>

#define SLAVE_ADDRESS  42
byte car = 1; // car to be send to the Echo Server.

void setup() {
    Serial.begin(9600);
  // We have a nodeMCU con I2C on pins D5 and D6.
    Wire.begin(D5, D6);
    delay(1000);
  Serial.println("");
    Serial.println(" Echo Server Tester");
    Serial.println("---------------------");
    Serial.println("###  Sent   Received");
    delay(1000);
}

/*
 * Send one byte in each loop().
 */
void loop() {
    byte status;

    if(car > 0) {
        do {
            Wire.beginTransmission(SLAVE_ADDRESS);
            int written = Wire.write(car);
            status = Wire.endTransmission();

            switch(status) {
            case 0:
        delay(1); // Comment this out and watch requestFrom() fails.
                if(Wire.requestFrom(SLAVE_ADDRESS, 1) == 1) {
                    byte r = Wire.read();
                    printChar(car, r);
                    car++;
                } else {
                    Serial.println("error in return");
                    status = 4;
                }

                break;

            case 1:
                Serial.println("Data too long");
                break;

            case 2:
                Serial.println("NACK on address");
                break;

            case 3:
                Serial.println("NACK on data");
                break;

            case 4:
                Serial.println("Some error");
                break;
            }
        }

        while(status != 0);
    }
}

/*
 * Utility: print in bytes sent and received
 */
void printChar(byte s, byte r) {
    Serial.print(s);
    Serial.print(" ");
    printBits(s);
    Serial.print(' ');
    printBits(r);

    if(r != s) {
    //  Mark invalid responses.
        Serial.print(" *");
    }

    Serial.println();
}

/*
 * Print a simple byte in binary
 */
void printBits(int car) {
    byte bit = 0x80;

    for(int i = 0; i < 8; i++) {
        int digit = car & bit;
        Serial.print(digit ? '1' : '0');
        bit >>= 1;
    }
}

```

**The Echo Server program**

```
/*
 * I2C Echo Server
 * Receive one byte from Master, echo the same byte to Master.
 */
#define MY_ADDRESS  42

#include <Wire.h>

volatile byte received;
volatile int count = 0;

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

  Wire.begin(MY_ADDRESS);
  Serial.println("--- Echo Server ---");

  Wire.onReceive(receiveCommand);
  Wire.onRequest(sendAnswer);
}

void loop() {
  static int lastCount = 0;

  if (count != lastCount) {
    Serial.print(lastCount + 1); Serial.print(" ");
    printChar(received);
    lastCount++;
  }
}

/*
 * Receive a byte from Master
 */
void receiveCommand(int howMany) {
  received = Wire.read();
  count++;
}

/*
 * Send a byte to Master
 */
void sendAnswer() {
  Wire.write(received);
}

/*
 * Utility print byte received/sent
 */
void printChar(byte car) {
  Serial.print("Char ");
  byte bit = 0x80;
  for (int i = 0; i < 8; i++) {
    byte digit = car & bit;
    Serial.print(digit ? '1' : '0');
    bit >>= 1;
  }
  Serial.println();
}

```

# Answer
> 2 votes
The 1 millisecond is not needed, try delayMicroseconds with 50 or maybe 20 µs.

The Arduino as a slave is totally different than for example a sensor. The Arduino as a slave uses a combination of hardware and software. The onRequest and onReceive functions are executed while the Arduino keeps the SCL line low. That is called clock pulse stretching.

With an Arduino **Uno** (ATmega328P microcontroller) connected to an Arduino Uno, this delay problem between a write and read on the I2C bus existed for a long time. A few years ago it was solved. It was a bug, a real bug. That delay is no longer needed.
There are still ways to make it unreliable, for example by disabling the interrupts for too long in the slave.

I read that is still exists with the Arduino **Due**. With the Due as a master and for example an ATmega328P (at 3.3V) as a slave, the Due still needs a delay.

The **nodeMCU** and the Raspberry Pi might still have some problems when an Arduino is used as a slave. The Arduino as a slave should at least run at 3.3V or a I2C level shifter should be used.
I don't know if the nodeMCU Wire library supports clock pulse stretching.
That delay might still be needed. Even then, I don't know how reliable the communication will be.

The Wire.endTransmission is the function that transmits the data (not the Wire.write). If that is followed too soon by a Wire.requestFrom and there is a bug in the Wire library, that can cause troubles.

---
Tags: i2c
---


title: 5V and Vin pins on Arduino

text:
# Question
Title: 5V and Vin pins on Arduino
I am working on connecting two Arduino boards (Arduino Uno & Arduino Nano). I am trying to run a stepper motor connected to Arduino Nano with two digital Pins on Arduino Uno to alter the direction of the stepper motor(BYJ48) connected to the arduino Nano. While making connections I attached the pins as:

1\] 5V (UNO) -\> 5V (NANO) & GND (UNO) -\> GND (NANO)

2\] 5V (UNO) -\> 5in (NANO) & GND (UNO) -\> GND (NANO)

Both \[1\] & \[2\] worked fine initially but I kept the arduino powered and tried toggling the Vin with 5v. Nothing went wrong in the beginning but later fumes started coming out and I dont know the reason why? Was that because I kept the power on while toggling between Vin & 5v ?
NOTE: besides the code and success in running the possible reason of fumes is much important here.

# Answer
You can try software serial communication between the two boards. Any two digital pins of one board can be used as Rx and Tx, and make sure the roles of Rx and Tx are reversed on the other board. See the Software Serial library: https://www.arduino.cc/en/Reference/SoftwareSerial
> 1 votes

---
Tags: arduino-uno, power, arduino-nano
---


# Question
Title: Arduino DigitalWrite() Super Basic Circuit measure voltage with multimeter
I am having a problem measuring the voltage with a multimeter. I am not sure if arduino is even sending out a voltage from the Pin.

I will try to create a really basic circuit drawing for reference. (Drawing attached).

What I am trying to do is to measure with a Multimeter the Voltage (or current) across the alligator clips.

I will attach the code below:

```
//Code Section Start//

int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(10000);                  // waits for a second
}

//Code Section End//

```

Typically the digital write I believe will out put 5 volts and with a 1k Ohm resistor that is only 5mA current. I have heard Arduino can take up to 40mA currents so I don't think I am frying something.

There are two weird things I have noticed. When I try other Pins like "int ledPin = 10;" The green light on the Arduino does not light up. It only lights up when I use pin 13. However, even using Pin 13 or any other pin, I cannot find a voltage or current with the Multimeter. I am using an Arduino Micro.

Can someone please help me identify what I am doing wrong or some method of how to check what is wrong? So that I can have a complete circuit with a voltage I can measure.

# Answer
As you have drawn it, the alligator clips are clamped together (shorted togther). You reading the voltage "across" a shorted element in the circuit should yield ~0V (shorts by definition have no to very little resistance, meaning there should be no voltage across them). In order to get your proper voltage reading, you should place the multimeter positive clip above the resistor (where the voltage drop is occuring).

Remember.

Measure current THROUGH.

Measure voltage ACROSS.

p.s. if you're trying to alternate the pin, you should do something like DigitalWrite(pin10, digitalRead(pin10)!=HIGH); (if it's low, then the statement evaluates to true, setting the pin high, if it's high, then the statement evaluates to false, setting the pin low)
> 1 votes

# Answer
As you connected the alligator clips (from the image it seems that they are touching each other) you won't be able to measure anything.

This is how to connect a multimeter to read the current (A) and the voltage (V). You can consider the `+` of E as the pin 13 and the `-` as the ground

Remember that your code will not change the state of pin 13, it will be always high. If you want to make the signal change try this on your `void loop` :

```
  digitalWrite(ledPin, HIGH);
  delay(10000);
  digitalWrite(ledPin, LOW);
  delay(10000);

```
> 1 votes

# Answer
you are telling that you are not getting any current or voltage on your multimeter right...... i suggest you to use the following code:-

```
int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
}

```

this will stay your arduino pin 13 always high then you can measure the voltage on that pin........
> 0 votes

---
Tags: voltage
---


# Question
Title: Receiving Multiple data on Arduino Serial
I am writing a very simple code in Arduino Nano, in which I am reading data that I send on Serial. Here is the code snippet.

```
int incomingByte ;

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

void loop() {

    if (Serial.available() > 0) {

            incomingByte = Serial.read();

            Serial.print("I received: ");
            Serial.println(incomingByte);
    }

```

}

When I send 'A' , I receive the following output:

I received: 65

I received: 13

I received: 10

What is wrong with the working of Serial Port here?

# Answer
> 3 votes
You send a string "A"

However, to denote the end, a carriage line (code 13) + line feed (code 10) is sent.

So what is sent is actually an 'A' character followed by a return. This way you also know when a new line starts

Just strip off the return (13,10) items if you do not need them.

If you do not want to send the return, try sending 'A' (which is the character A, and not the string A.

Update

You can ignore them by:

```
     if ((incomingByte != 10 && (incomingByte != 13))
     {
        Serial.print("I received: ");
        Serial.println(incomingByte);
     }

```

If you only want printable characters, check if you can use the isprint function (isprint function

so it should look like

```
    if (isprint(incomingByte))
    {
        Serial.print("I received: ");
        Serial.println(incomingByte);
    }

```

# Answer
> 3 votes
nothing is wrong, it's to do with operator overloading and the print function trying to be helpful.

if you change this line:

```
int incomingByte ;

```

to this:

```
char incomingByte ;

```

it should display correctly

And the extra characters are because the software on the computer is sending line endings. these may be a linefeed with or without a carriage return. you could either just ignore them, or make use of them to create multi character commands (if you need them)

# Answer
> 2 votes
this is just because you are typing a letter i the serial monitor ans in your code your are declaring it as a integer 'int' so you not need to worry about that just try the following code

```
int incomingByte ;

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

void loop() {

    if (Serial.available() > 0) {

            incomingByte = Serial.read();
            Serial.write(incomingByte);
    }
}

```

-------------------------------- OR ---------------------------------------

```
char incomingByte ;

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

void loop() {

    if (Serial.available() > 0) {

            incomingByte = Serial.read();
            Serial.print(incomingByte);
    }
}

```

Both of the programs will work try that.......

---
Tags: serial
---


title: Help What am I doing wrong? Matrix Led

text:
# Question
Title: Help What am I doing wrong? Matrix Led
I'm new and im trying out the Matrix LED heres my code

```
#include <LedControl.h>

LedControl lc = LedControl(12, 11, 10, 1);

unsigned long delayime = 100;

void setup()
{
  lc.shutdown(0, false);
  lc.setIntensity(0, 8);
  lc.clearDisplay(0);
}

void writeArduinoOnMatrix()
{
  byte H[10] = {8, 8, B01100110, B01100110, B01100110, B01111110, B01111110, B01100110, B01100110, B01100110};
  byte E[10] = {8, 8, B01111110, B01111110, B01100000, B01111110, B01111110, B01100000, B01111110, B01111110};
  byte L[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};
  byte O[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};

  lc.setRow(0, 0, H[0]);
}

```

I keep on getting this error no matter what. collect2.exe: error: ld returned 1 exit status

exit status 1 Error compiling for board Arduino/Genuino Uno.

Help What am I doing wrong?

# Answer
Unfortunately I think you are missing the actual error message and have just copied the result. I suspect if you scroll back up through the output it will say loop is missing.

All Arduino sketches (well almost all) have to have `setup()` and `loop()` functions. The underlying 'stuff' will call `setup()` once and `loop()` repeatedly.

I hate global variables, but in this case I would be tempted to move those arrays out of the function and make the constant global values. That way they will be in memory as the Arduino boots and you won't have to waste processor cycles setting them up.

It may be a silly question, but are you using the right hardware? This might help check that http://playground.arduino.cc/Main/LedControl
> 1 votes

# Answer
A ld error normally means a link error, i.e. you call a function that is not defined.

Are you sure it is the complete error? That it does not show which function you miss?

Also, I notice:

* function writeArduinoOnMatrix never seems to be called, or you didn't post the full code?
* In writeArduinOnMatrix, you declare 4 arrays, but you use only one (H).
* Typo in: unsigned long delayime = 100; ... this should be delayTime
> 0 votes

---
Tags: led
---


title: Error running the code

text:
# Question
Title: Error running the code
The error I get is as follows:

```
F:\Josh\GIZDUINO PROJECT\Joshua\arduino-1.8.3\libraries\arduino-ledcube-master\examples\ledcube\ledcube.pde: In function 'void loop()':

ledcube:49: error: taking address of temporary array
         cube.createFrame((byte[]) {0,6, 1,6, 2,6}, 6, 80),
                                                         ^
ledcube:50: error: taking address of temporary array
         cube.createFrame((byte[]) {0,7, 1,7, 2,7}, 6, 70),
                                                         ^
ledcube:51: error: taking address of temporary array
         cube.createFrame((byte[]) {0,8, 1,8, 2,8}, 6, 60),
                                                         ^
ledcube:52: error: taking address of temporary array
         cube.createFrame((byte[]) {0,5, 1,5, 2,5}, 6, 50),
                                                         ^
ledcube:53: error: taking address of temporary array
         cube.createFrame((byte[]) {0,2, 1,2, 2,2}, 6, 40),
                                                         ^
ledcube:54: error: taking address of temporary array
         cube.createFrame((byte[]) {0,1, 1,1, 2,1}, 6, 30),
                                                         ^
ledcube:55: error: taking address of temporary array
         cube.createFrame((byte[]) {0,0, 1,0, 2,0}, 6, 20),
                                                         ^
ledcube:56: error: taking address of temporary array
         cube.createFrame((byte[]) {0,3, 1,3, 2,3}, 6, 10)
                                                         ^
F:\Josh\GIZDUINO PROJECT\Joshua\arduino-1.8.3\libraries\arduino-ledcube-master\examples\ledcube\ledcube.pde:115:38: warning: narrowing conversion of '(((int)cube.LedCube::getLevels()) + 1)' from 'int' to 'byte {aka unsigned char}' inside { } [-Wnarrowing]
     byte planes[] = {cube.getLevels()+1,cube.getLevels(),cube.getLevels()*2,1};
                                      ^
F:\Josh\GIZDUINO PROJECT\Joshua\arduino-1.8.3\libraries\arduino-ledcube-master\examples\ledcube\ledcube.pde:115:74: warning: narrowing conversion of '(((int)cube.LedCube::getLevels()) * 2)' from 'int' to 'byte {aka unsigned char}' inside { } [-Wnarrowing]
     byte planes[] = {cube.getLevels()+1,cube.getLevels(),cube.getLevels()*2,1};
                                                                          ^

exit status 1
taking address of temporary array

```

# Answer
> 2 votes
Three remarks to your question.

1. Avoid using UPPERCASE as that is considered to be a typographical notation for shouting. See http://practicaltypography.com/all-caps.html
2. The compiler error is due to that you are using a temporary byte vector as parameter. You should declare the vector as a local or global variable and pass the reference. See https://stackoverflow.com/questions/42332229/how-to-pass-a-temporary-array or web-search for more info.
3. The compiler warning is due to an implicit conversion from int to byte. The conversion may result in a loss of precision thus the warning. You can use a type cast to avoid this. The type case will tell the compiler that you know what you are doing.

Cheers!

# Answer
> 1 votes
You have to declare your array by itself, with a name, like this:

```
void fcn(byte p[]) {
  Serial.print("p[1]=");
  Serial.println(p[1]);
}

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

  byte ar[] = {0, 6, 1, 6, 2, 6};
  fcn( ar);
  }

void loop() {
}

```

And the warning are for using a `int` where a `byte` is expected. It's just a warning. There is no problem as long the values are between 0 and 255.

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


title: Call class B from Class A

text:
# Question
Title: Call class B from Class A
I have two classes in my sketch that are independent of each other (a serial output and an LCD display) A simplified structure of my code is as follows:

```
class A
{
  public:
   int x;
   void afoo()
   {
     x=1;
   }
   void afoo2
   {
     x=ClassB.bfoo+1;
   }
};

A ClassA;

class B
{
  public:
    int y;
    void bfoo()
    {
      y=ClassA.afoo+2;
    }
};
B ClassB;

```

However, if I don't comment out `class afoo2` I get the following error:

> exit status 1
>
> `'ClassB' was not declared in this scope`

I'm guessing that this is because I haven't yet created `B ClassB` while class is being defined. Is there a way I can do what I'm intending here?

# Answer
You can't see non-static member variables in a class like that. The closest is to make it `static`, which means you get one and only one copy of the variable across all instances of your class:

```
class ClassB;
class ClassA {
    public:
        int x;
        void foo();

};
class ClassB {
    public:
        static int bfoo;
};

void ClassA::foo() {
    x = ClassB::bfoo + 1;
}

```

However I suspect that isn't what you want. I suspect you actually want to see the `bfoo` value stored in class instance `B` \- so you need to tell you `classA` instance `A` what and where `B` is. To do that you will have to pass it when constructing or during some other setup phase. If you want A to know B and B to know A you can't easily do it during construction, so you will have to do it at a later stage:

```
class ClassB;

class ClassA {
    public:
        ClassB *B;
        int fooa;
        void begin(ClassB *b) {
            B = b;
        }
        void foo();
};
class ClassB {
    public:
        ClassA *A;
        int foob;
        void begin(ClassA *a) {
            A = a;
        }
        void foo();
};

void ClassA::foo() {
    fooa = B->foob + 1;
}

void ClassB::foo() {
    foob = A->fooa + 1;
}

ClassA A;
ClassB B;

void setup() {
    A.begin(&B);
    B.begin(&A);
}

void loop() {

}

```
> 3 votes

# Answer
What you are trying to do is call class A from B and vice versa.

What you could try, is remove one of the functions out of the class, possibly to a third class, so class A and B depend on a class C and not on each other.

However, if they are really depend, you can split up the files in header/implementation files.

Instead of using two classes directly, pass them as a parameter (reference).

Somewhat like this (not tested)

File A.h:

```
class A
{
  public:
   int x;
   void afoo();
   void afoo2(B& b);
};

```

File A.cpp:

```
#include "A.h"
#include "B.h"

void A::afoo()
{
  x=1;
}

void A::afoo2(B& b)
{
  x=b.bfoo+1;
}

```

file B.h:

```
class B
{
  public:
    int y;
    void bfoo(A& a);
}

```

file B.cpp:

```
#include "A.h"
#include "B.h"

B::void bfoo(A& a)
{
  y=a.afoo+2;
}

```

And your ino file you declare A and B.

```
#include "A.h"
#include "B.h"

A ClassA;
B ClassB;

ClassA.afoo(ClassB);
ClassB.bfoo(ClassA);

```
> 1 votes

---
Tags: arduino-mega, programming, class
---


# Question
Title: Works with gcc, not with Arduino. error: taking address of temporary array
I need to hard code 8 byte addresses into char arrays of length 8. This must be done many places in my code (in function scope), so I have tried to come up with a one-liner. The following works perfectly in C when compiling with gcc.

```
char a[8];

void cpaddr(char target[], char *source) {
    int i;
    for (i=0; i<8; i++)
        target[i] = source[i];
}

int main() {
    char b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
    cpaddr(a, b);

    // line below does not compile with Arduino IDE
    cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
}

```

When compiling on Arduino the last line, which is the one-liner I was aiming for, does not compile. It gives:

```
/home/bob/Desktop/ate/Ate.ino: In function 'int main()':
Ate:101: error: taking address of temporary array
cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
^
exit status 1
taking address of temporary array

```

What is the problem here, that apparently is not a problem with gcc?

How do I fix it?

# Answer
It is quite right, using that kind of syntax is not allowed. It's a bit of a pain, but it's ok since there is an alternative method - kind of a "trick" if you will.

That trick is to use a string, not an array. After all, a string is just an array, it's just handled slightly differently by the compiler.

Instead of using `{...}` use `"..."` and use the hexadecimal character escape sequence `\xNN`, such as:

```
cpaddr(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D");

```

You could even lose your custom function and use a standard library function - `memcpy()`:

```
memcpy(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D", 8);

```

On the 8-bit AVRs you can save RAM by using the progmem variant and the `F()` macro:

```
memcpy_P(a, F("\x00\x10\xFF\xCA\x00\x00\xA2\x7D"), 8);

```
> 4 votes

# Answer
See Using array init list as temporary in C++11?

You can solve it by using `const`. This compiles:

```
char a[8];

void cpaddr(char target[], const byte *source) {
    int i;
    for (i=0; i<8; i++)
        target[i] = source[i];
}

int main() {
    byte b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
    cpaddr(a, b);
    cpaddr(a, (const byte[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
}

```

Note I had to change your array from `char` to `byte` because I was getting (valid) warnings that things like 0xCA don't fit into a char.
> 1 votes

# Answer
> How do I fix it?

"Char \[\]" shouldn't compile under c. It is just invalid.

You can use string, cast to char * . or just another pointer as you did already.
> 0 votes

---
Tags: c++, array, pointer, gcc
---


# Question
Title: Reliably measuring the energy consumption of arduino running sketch
I would like to know if there is a programmatic way of measuring the energy consumption of a sketch or at least if this is possible via external devices.

My aim is to compare the energy consumption of two devices, connected to usb, running slightly modified versions of the same sketch e.g., one using crypto and one without using crypto.

# Answer
> 0 votes
> programmatic way of measuring t

Not sure what you meant by that but typically you can use a high side current sense amplifier to get a measurement of the current. Then adv a known voltage to get vcc. That known voltage could be the internal reference, if available

In some cases a resistor on vcc can be used to measure current, together with two dividers.

---
Tags: arduino-uno
---


title: (ESP8266) Check if a SSID is in range

text:
# Question
Title: (ESP8266) Check if a SSID is in range
I need to check if a given SSID is in range. Would be good if it didn't disconnect from the current wifi network that it's connected to, but it doesnt matter, i just need to see if a SSID is in range, whether it does disconnect or not. It should be something like this:

```
if(WiFi.SSID(checkforthisSSID)) {
  //do something
}

```

Thanks.

# Answer
> 4 votes
Not so tough it is possible just try the bellow code :)

```
void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  CheckPossibility();
  }

 CheckPossibility(){
 int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      if(WiFi.SSID(i) == "REPLACE THIS WITH YOUR SSID"){ //enter the ssid which you want to search
      Serial.println("The network you are looking for is available");
      }
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
 // delay(5000);
}

```

# Answer
> -1 votes
Try to connect to an AP, Use scan networks example, then look if the SSID in in the response. Did not try, the scan networks example has an "WiFi.disconnect()" before the scan() function.

---
Tags: esp8266, wifi
---


title: Compile Error for Arduino Mega

text:
# Question
Title: Compile Error for Arduino Mega
I am using the Arduino IDE 1.6.0, There is a project that has compiled both for Due and Mega on another computer. But on my machine, it only compiles for Due. When compiling for "Mega or Mega 2560", I get the following error:

> /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: skipping incompatible /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/lib/libc.a when searching for -lc /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: cannot find -lc collect2: error: ld returned 1 exit status Error compiling.

My newbie guess is something is wrong with AVR libraries. But how to solve it? Also could someone please explain what `-lc` is, which cannot be found? At first glance it looks like an option.

# Answer
> 1 votes
tldr; `-lc` means "link with the `libc.a` library"

The compiler takes your source code (`*.c`, `*.ino`) and produces "object" files ending in `*.o`.

The linker takes those compiled modules and links them all together to make the final executable, linking symbols in one file (such as variable references and function calls) with the definitions in the others (the actual variables and functions). But it also takes libraries - predefined collections of object files - and links those in as well, if necessary.

Libraries are files of the form `lib*.a` (`a` is for "archive"), and are distributed by software vendors as easy containers for their modules. The compiler/linker itself also uses them as the implementations for languages features such as `printf()` and `digitalWrite()`. The most fundamental library is `libc.a` \- the library containing the standard C implementation.

When you want to get the linker to use a library, you give it the `-l` option, with the library name appended (not including the `lib` prefix and `.a` extension). In short, `-lc` means "link with the `libc.a` library".

But if your development machine has support for numerous processors, there will be a number of `libc.a` files on it - how does the linker know where to look? Another linker option is `-L` (note uppercase), which defines the directories to look in to find libraries. The linker will look through the directories in turn until it finds the referenced library.

If you attempt to link modules that have been compiled for different processors, you will get linker errors when it does a sanity check. The reason your fix worked is because it now uses the correct directories to find what it is looking for.

# Answer
> 1 votes
I think you have included some libraries in the sketch. The problem is that one of the libraries doesn't support the Arduino Mega.

As a solution, I suggest you to comment out the libraries one by one and then try to compile the program. If code runs successfully,try to install that library with other versions. Don't forget to remove the previous library.

# Answer
> 0 votes
So what I did that solved the problem was, I downloaded the latest Arduino IDE, titled "**Windows ZIP file** for non admin install". Then I unzipped the download, and I copied all of the files of the new IDE and pasted them into the old installation. But I did not replace anything. i.e. For each file that existed, I kept the old file.

~400 new files were copied. Now it compiles without error.

BTW since this has been a blind workaround, I will not accept this as the final answer.

---
Tags: arduino-mega, compile
---


title: Linking one circuit to two Arduinos

text:
# Question
Title: Linking one circuit to two Arduinos
I don't actually have to achieve this, it's more of an attempt to see what the best way to do this is. I'm sure the answer also differs depending on what circuitry you're trying to connect.

In this case, I plan on an Arduino (probably a Pro Mini or similar) that will control some RGB LEDs (via the WS2811 chip). If I wanted to add a second Arduino that would drive the LEDs if the first one failed (obviously very unlikely), I was wondering how I would do it. The WS2811 chip takes 5V, GND and data in.

My best attempt at a solution is using 3 relays which are SPDT. Connect the LEDs to the main Arduino via the normally open, which is controlled by that particular Arduino, and connect the LEDs to the backup Arduino via the normally closed, which is held open by the main Arduino. In the event of a failure, the main Arduino would lose connection to the LEDs while the backup would make a connection.

This probably isn't a very safe way of doing it (especially if the relay failed for example). Is there a way to do this?

The two Arduinos will be powered from two separate laptops.

# Answer
> 1 votes
You first need to make a communication between both Arduinos and then you can control RGB led from any Arduino.

For the connection between both the Arduinos, you can make a serial port interface for doing this, you just need `softwareserial.h` library. Then you just need to connect the RGB LED to one Arduino. Then when you send a command from another Arduino to that one, the Arduino (Connected to RGB LED) can operate the LED according to the command.

# Answer
> 0 votes
You can try something like this:

Tie both arduino 5V to WS2811 chip VCC.

Tie both arduino GND to WS2811 chip GND.

Tie both arduino DATA LINE to WS2811 chip DATA LINE.

Tie an analog input pin from the backup arduino to chip DATA LINE.

Tie an analog input pin from the main arduino to chip DATA LINE.

Issue RS232 or some form of communications between the main and backup arduino.

Program the main arduino to control the data line. Program the second arduino to:

* Sleep, if DATA LINE PWM is present. (Optional: Ask main arduino if operational)
* If DATA LINE PWM is absent (you'll see this from analog input), ask main arduino if he is okay or if this is a fault
* If no answer is received and PWM is absent, assume main arduino dead, start own PWM on DATA LINE. Also, send message to main arduino that the backup is currently online and he should not intervene.
* If main arduino comes alive, he first checks if backup is operational (Also it's good to read if PWM exists). If message is received that backup is operational, send message to backup to shut off and take DATA LINE for self.
* If no message is received and no PWM is present in DATA LINE, assume backup dead, take DATA LINE to self.

Further notes:

* If you decide to use communications, make sure to use a handshake algorithm to prevent accidental interventions.
* You can do this project without the communications between chips but it will depend on your project and will require some clever coding.
* Make sure you create some clever time gaps on those messaging and reading stuff.
* I would advise you to both use analog readings and communications because it is a sort of double check on seeing who is active at the moment. Communications will ease your code development and analog read is required in case of com line failure.

Good luck!

P.S. Don't just use relays like that. It will make debugging and code writing very difficult.

---
Tags: relay
---


title: Can't upload new sketch

text:
# Question
Title: Can't upload new sketch
Recently I have unsoldered most connector pins there are on the arduino uno board. However, when I now attempt to upload a new sketch (works when I upload it to another model) it gives me the following error:

```
> avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xfa

```

I would like you take a look at my arduino board to see whether I have unsoldered important pins which might have to be connected.

Also when I try to upload a new sketch the 'L'-LED doesn't flash but the RX one.

(BTW: Yes I've set the settings to the correct board, port etc...)

Thanks for any solution attempts!

# Answer
> 1 votes
Removing there pin headers should not cause any sketch upload issue. I have done it many times.

You did try uploading BEFORE unsoldering the headers right ?

However looking at the desoldering job you did, my guess is that you applied too much heat or cut a trace on the PCB while doing it.

Can you upload a high resolution of the back side of the board?

What I would try is to take a known good 328p chip and replace the one on this board with it and try uploading again.

# Answer
> 0 votes
Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.

# Answer
> 0 votes
Checking the schematic, the TX/RX leds are driven directly by the atmega16u and are not connected to the TX/RX lines of the 328p. That would seem to indicate the 16u has a problem so it's a good place to double check. The lines that run to the TX/RX of the 328p run from pins 8 - 9 of the 16u. I assume that this ran previous to the fatal 'surgery'? I don't suppose you loaded something simple, like the led flash program before surgery? Just curious, are you hard wiring it to something?

# Answer
> 0 votes
Try to unplug the IC and the plug it again.

I think that you have removed the IC off of the board. If it doesn't work then buy a new ATmega328P IC and replace it with the old one and then try again.

---
Tags: arduino-uno, uploading, upload
---


title: Modified Mesh networking using nrf24l01

text:
# Question
Title: Modified Mesh networking using nrf24l01
I am trying to make a mesh network of three nrf24l01 nodes in which all three are transceivers, such that all three are in a line. The modification I want to make is that if two end nodes are not able to communicate with each other as they fall short of range the signal must be sent via the middle node. How should I approach?

# Answer
To be honest, I still have to receive my RF's... But I have a similar problem, meaning I also need to have them all to both receive and transmit.

I thought it was not possible, since in a 6-1 network, one is receiver, 6 are transmitting. With auto-ack messages can be returned.

Depending on the amount of messages being sent and latency you can let them talk when needed and hope there is not too much sending simultaneously (causing resends).

One solution you could use, is to put in the message a receiver ID. Suppose the 'geographic location' of your objects are

A \<----\> B \<----\> C

Assume A wants to send to C, but it will not be received by C, C does not auto-ack, and A knows this. Know A can send the message to B, which can auto-ack, and B has to send it to C. Possibly the original source (A) has to be added to the message as well, if this is important for C to know.

Update: (in steps)

Suppose A wants to send a message m to C

* A sends message m to C
* C does not receive it, thus is does not send an ACK-message back to A
* A gets a timeout
* A knows that message m has not been sent to C (so it is out of range)
* A sends the message m to B (adding 'A' as sender of the message if not already done)
* B receives message m
* B sends an ACK back to A
* A knows message m has been sent to B
* B sends message m (with A as sender) to C
* C receives the package
* C sends back a message to B
* B needs to send a message to A that m has been sent successfully

Some generic remarks: \- This scheme is maybe not full-proof or can be optimized (like that A knows from now on it needs to send to B first to reach C). \- Also both B and C can be out of range, you want to resend it (later)?
> 1 votes

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


title: Advance arduino programming?

text:
# Question
Title: Advance arduino programming?
I have worked with basic arduino IDE for making robots and sensor based projects.Now I want to learn some advance arduino programming and try some complex Arduino projects.Can anyone help me with the links or related information..?

# Answer
Here are 4 suggestions:

> Especially for point 2 there are plenty of resources that are easy to find. Once you learn "Blink" sketch,you will realize there is a lot out there.

1. Don't use Arduino IDE

It lacks a lot of features which any serious programming IDE offers today. Visual Micro for Visual Studio and PlatformIO are two examples. More alternatives mentioned in the comments. These IDE which give you advance features like syntax highlighting, autocompletion, multifile projects, etc..

2. Start learning C/C++

Arduino programming is derived from C++ with some nice libraries to make it easier, specially on Embedded Systems. Instead of looking up and setting registers to change pin state Arduino libraries will make it easier for you.I have worked with complex projects on arduino and arduino libraries made it very easy to go. There is a lot more to learn in arduino.

3. Start learning electronics

Your advanced projects surely comes with advanced electronics. This is a whole other place where things might go beyond our understanding. I have spent hours and days debugging my codes. It will also help you find your way through the jungle of all the current "maker toys". There are different platforms, variety of boards and chips,people often spend a lot of time figuring out which one is suitable for our project.

4. Have a look at Arduino's "successors": ESP8266, ESP32

These Chinese chips are like Arduino on crack. They have onboard WiFi and higher clock frequencies (but are also a lot more capricious and don't have as much documentation as Arduino). Best part: You can program them just as easily as your Arduino Or you can try barebone programming (javascript)later. The newest one, the ESP32 is a dual-core chip with 240 MHz, WiFi and Bluetooth. Cost is around USD 2. It is available on Aliexpress. There are also a lot of other chips/boards out there that I have not mentioned here. Above is AFAIK the most common.
> 3 votes

---
Tags: programming, arduino-ide
---


title: Understanding a PWM spec

text:
# Question
Title: Understanding a PWM spec
I have to send a PWM signal to a controller module from an Arduino Uno. I'm not sure how to interpret the spec I've been given, and how to translate it into a PWM signal. The module is a Castle Creations *Mamba Monster 2*, if that helps.

The spec says the unit wants a 50Hz carrier, and the control is:

```
1500 microsec = idle
2000 usec = full forward
1000 usec = full reverse

```

I get that the period of the carrier is 20,000 usec but how does that relate to the control periods? Does it mean that for "idle" the PWM signal is high for 1500 usec and low for (20000 - 1500) usec?

Any help or insight is appreciated. Are there libraries that can deal with PWM in the given terms? Any good tutorials? I generally understand how PWM works, I just don't get the notation used here.

# Answer
For a full 50Hz wave you have 1/50 seconds, or 20,000 microseconds, as you have already determined.

That is split into two portions - the ON period and the OFF period. With a 50% duty cycle the ON and OFF periods are equal - 10,000 microseconds each.

With a 25% duty cycle it is ON for 25% of the time (5,000 microseconds) and OFF for 75% of the time (15,000 microseconds).

Every time the ON and OFF must add up to 20,000 microseconds.

So for a 1,500 microsecond "idle" time that's 1,500 microseconds on, and (20,000 - 1,500) 18,500 microseconds off.

Or to see it as a duty cycle - 1,500 / 20,000 * 100 = 7.5% duty cycle.

With an 8-bit resolution that's a value of 19.2 (256 * 0.075), or the closest integer match of 19.
> 1 votes

---
Tags: arduino-uno, pwm
---


# Question
Title: Can I get the arduino to run ESP8266 code?
So I got this water flow sensor that measures the flow of water. I also got an ESP8266 module to help me make HTTP requests.

So as far as I know, one must set the board type to Generic ESP8266 and upload a sketch that the ESP8266 runs.

However, how can I write code in such a way that when the water flow goes over say 30 Litres, it makes a GET request to the Api that alerts the user? I am not able to use both the modules in one sketch. Any possible methods?

# Answer
I think you have a fundamental misunderstanding of what you are working with.

There are two ways of working with an ESP8266:

1. Directly program the ESP8266. This involves installing the ESP8266 boards package and uploading the code to the ESP8266. No Arduino is required (unless you want to use one as a USB to UART adaptor for the programming).
2. Use the ESP8266 as a serial peripheral to an Arduino. You program the Arduino, not the ESP8266, and no special software is needed (unless you want to use an ESP8266 library for Arduino). You send the ESP8266 `AT` commands to get it to do internet related operations. *You are still working with an Arduino, so that is the board that should be selected.*

It sounds like you are wanting to do (2) but are mistakenly trying to so (1).

Option 2 does rely on the ESP8266 having the AI Thinker AT firmware installed on the ESP8266, which most come preinstalled with. If you have uploaded code to your ESP8266 using the ESP8266 boards package that firmware will have been replaced with your code and you will need to put the original firmware back on. There's many tutorials on the web showing you how.

If you do want to program the ESP8266 directly then it's the ESP8266 that you need to program, not an Arduino. Everything will be done by the ESP8266 - the GET request, the water flow sampling, the decision making, etc. The Arduino will be relegated to your bits box where it will gather dust.
> 2 votes

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


# Question
Title: Should BLK and GRN of Pro Mini be connected to upload sketch?
Is the following connector is valid for Arduino Pro Mini (no `BLK` and `GRN`)?

I was told to make a certain Arduino application, and got some Arduino Pro Mini (ATmeag328 3.3V 8 MHz) with the connector above.

Everytime I tried to upload an example sketch 'Blink', the IDE complains (verbose enabled):

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83

```

`resp` may differ (I saw `0x1f` and `0x83`)

But, according to the official document, I think that I should use some *FTDI* thing, which has 6 pins including BLK and GRN.

I wonder whether I can use the existing 4-pin connector, or whether I must use 6-pin FTDI connector.

# Answer
> 1 votes
If you look at the picture in your link, you would see that `BLK` is ground (`GND`) and `GRN` is `DTR`, that is used to reset the board and enter the bootloader for programming.

As Majenko said, without `DTR` you will need to press the reset button at the right time, to enter the bootloader.

---
Tags: arduino-pro-mini, uploading, ftdi
---


# Question
Title: How to merge 2 batteries socketof 6v each
i want to merge 2 batteries socket of 4 AA 1.5v batteries , how can combine them to have 12v ?

# Answer
> 3 votes
Put them in serie. One red cable to another black cable. Glue the cases back to back.

Don't get confused by the clamps; I only used them for keeping things in place. Oh, my cases are for 3 batteries, but the procedure is aplicable to 4 batteries cases also.

---
Tags: battery
---


title: Can't find OV2640 module! pid: 254

text:
# Question
Title: Can't find OV2640 module! pid: 254
I'm trying to follow this tutorial. But I'm stuck in this error:

```
Can't find OV2640 module! pid: 254

```

I tried to contact the author of the program, but I have not had an answer yet. I'm using the ArduCAM Mini module OV2640.

Has anyone ever been in this situation?

# Answer
> 0 votes
Thank you very much for your attention. But the problem was in the dupont connection wires, as mentioned here!

# Answer
> 1 votes
If you look at line 762 of 'ArduCam\_ESP8266\_FileCapture.ino' you should see it is looking to read two bytes from the camera to check that the model number is either a '2641' or '2642'.

You are seeing the error because you are not getting those values back. So between 761 and 762 insert some debug and print what you are getting back:

```
Serial.print ("vid = ");
Serial.println (vid);
Serial.print ("pid = ");
Serial.println (pid);

```

I guess you will either get 00 00 or a different valid (maybe) model number. If you think its a valid model number add another condition to the if statement and see if it works.

Oh and don't forget to post the results, because I'm going to give it a chance too when I get time :)

# Answer
> 1 votes
Does it still happen if you power the cameras off and then on again. I was getting the same thing as there is a bug in one of the examples where the cameras are placed into deep sleep mode so when you reset the microcontroller or whatever you have the cameras can't be found because they are sleeping. I add the line

```
yourcam.clear_bit(ARDUCHIP_GPIO, GPIO_PWDN_MASK);

```

to clear this state when intialising.

---
Tags: arduino-ide, esp8266
---


title: 3-Way Bluetooth Communication?

text:
# Question
Title: 3-Way Bluetooth Communication?
I need two Arduino units with the HC-06 Bluetooth board to communicate with each other and one of these Arduino units also connected to my Android phone. Is this possible to do with just two HC-06 modules, or even three? Or is there a better solution for this?

To reiterate what is going on here: I have two Arduinos that are running off battery. Arduino 1 is sending data every 0.5 seconds to the Arduino 2. Arduino 2 collects this, adds its own bit of data to it, and then sends this new data packet to my Android phone which will only be connected to Arduino 2.

I haven't completely decided upon what kind of Arduino board to get, but it needs to be fairly small, but I am planning on the Adafruit Pro-Trinket 5v.

Hopefully you get the basic scenario, let me know if you need more clarification and what you think could be done here.

Thanks a lot!

# Answer
> 1 votes
Should be possible, but only if you setup the Bluetooth module of Arduino 2 as the master. You see, Bluetooth requires to connect to a master. A master can connect to 8 slaves in total. Because Arduino 2 connects to multiple devices (Arduino 1 and your Android device) it should be the master. This also means your Android device cannot connect to any other devices.

Hope this gives you a place to start exploring.

# Answer
> -1 votes
Ok

So From Whatever I can Understand you could do this.

1. make one of the boards talk to a master control board.
2. make the control board talk to your phone.

Why don't you change your approach

1. Make the board A communicate with board B with Bluetooth.
2. Use different pins to setup communication b/w phone and board b.

**Arduino to Arduino Bluetooth**\- http://www.martyncurrey.com/arduino-to-arduino-by-bluetooth/

**Arduino to phone via Bluetooth**\- http://www.instructables.com/id/Connect-Arduino-Uno-to-Android-via-Bluetooth/

**PS: - USE DIFFERENT PINS!**

---
Tags: sensors, bluetooth
---