title: Can't print on LCD

text:
# Question
Title: Can't print on LCD
I'm a newbie here. And sorry for my bad English first of all.

Right now I'm working on VLC (Visible Light Communication). I have working code, in which output is displayed on the Serial Monitor. But now I want to print this output on an LCD.

I made necessary changes like including the LCD library and instead of `Serial.print` I used `lcd.print`. But nothing is displayed on the LCD.

Here is the modified code including LCD:

```
static int TRESHOLD = 500;
static unsigned int standardDelay = 13500000; //1350 is limit
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 7,6,5,4);

void setup() {
  Serial.begin(9600); // 9600 bits per second
  pinMode(3,OUTPUT); //digital PWM 3 on output
  int sensorValue = 0;
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // initialize the serial communications:
}

void loop() {
  WriteChar('h');
  WriteChar('e');
  WriteChar('l');
  WriteChar('l');
  WriteChar('o');
  WriteChar('w');
  WriteChar('o');
  WriteChar('r');
  WriteChar('l');
  WriteChar('d');
}

void WriteChar(char str){
  switch (str - '0'){
    case 49:
      //code for a is 011 0001
      LightFlash(false, true, true, false, false, false, true);
      break;
    case 50:
      //code for b is 011 0010
      LightFlash(false, true, true, false, false, true, false);
      break;
    case 51:
      //code for c is 011 0011
      LightFlash(false, true, true, false, false, true, true);
      break;
    case 52:
      //code for d is 011 0100
      LightFlash(false, true, true, false, true, false, false);
      break;
    case 53:
      //code for e is 011 0101
      LightFlash(false, true, true, false, true, false, true);
      break;
    case 54:
      //code for f is 011 0110
      LightFlash(false, true, true, false, true, true, false);
      break;
    case 55:
      //code for g is 011 0111
      LightFlash(false, true, true, false, true, true, true);
      break;
    case 56:
      //code for h is 011 1000
      LightFlash(false, true, true, true, false, false, false);
      break;
    case 57:
      //code for i is 011 1001
      LightFlash(false, true, true, true, false, false, true);
      break;
    case 58:
      //code for j is 011 1010
      LightFlash(false, true, true, true, false, true, false);
      break;
    case 59:
      //code for k is 011 1011
      LightFlash(false, true, true, true, false, true, true);
      break;
    case 60:
      //code for l is 011 1100
      LightFlash(false, true, true, true, true, false, false);
      break;
    case 61:
      //code for m is 011 1101
      LightFlash(false, true, true, true, true, false, true);
      break;
    case 62:
      //code for n is 011 1110
      LightFlash(false, true, true, true, true, true, false);
      break;
    case 63:
      //code for o is 011 1111
      LightFlash(false, true, true, true, true, true, true);
      break;
    case 64:
      //code for p is 100 0000
      LightFlash(true, false, false, false, false, false, false);
      break;
    case 65:
      //code for q is 100 0001
      LightFlash(true, false, false, false, false, false, true);
      break;
    case 66:
      //code for r is 100 0010
      LightFlash(true, false, false, false, false, true, false);
      break;
    case 67:
      //code for s is 100 0011
      LightFlash(true, false, false, false, false, true, true);
      break;
    case 68:
      //code for t is 100 0100
      LightFlash(true, false, false, false, true, false, false);
      break;
    case 69:
      //code for u is 100 0101
      LightFlash(true, false, false, false, true, false, true);
      break;
    case 70:
      //code for v is 100 0110
      LightFlash(true, false, false, false, true, true, false);
      break;
    case 71:
      //code for w is 100 0111
      LightFlash(true, false, false, false, true, true, true);
      break;
    case 72:
      //code for x is 100 1000
      LightFlash(true, false, false, true, false, false, false);
      break;
    case 73:
      //code for y is 100 1001
      LightFlash(true, false, false, true, false, false, true);
      break;
    case 74:
      //code for z is 100 1010
      LightFlash(true, false, false, true, false, true, false);
      break;
    default:
      lcd.print(str - '0');
      lcd.print("CAME IN DEFAULT IN WRITECHAR");
      break;
  }
}

void LightFlash(boolean a, boolean b, boolean c, boolean d, boolean e, boolean f, boolean g){

  digitalWrite(3,LOW);
  if (a == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue1 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (b == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue2 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (c == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue3 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (d == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue4 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (e == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue5 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (f == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue6 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);

  digitalWrite(3,LOW);
  if (g == true){
    digitalWrite(3,HIGH);
  }
  delayMicroseconds(standardDelay/2);
  boolean sensorValue7 = (analogRead(A0)>TRESHOLD);
  delayMicroseconds(standardDelay/2);
  delayMicroseconds(3*standardDelay); //1 second passed

  long result = 0;
  result = 1000000*sensorValue1 + 100000*sensorValue2 + 10000*sensorValue3
  + 1000*sensorValue4 + 100*sensorValue5 + 10*sensorValue6 + 1*sensorValue7;
  //lcd.print(result);
  PrintChar(result);
}

void PrintChar(long binary){

  switch (binary){

    case 110001:
      //code for a is 011 0001
      lcd.write("a");
      break;
    case 110010:
      //code for b is 011 0010
      lcd.print("b");
      break;
    case 110011:
      //code for c is 011 0011
      lcd.print("c");
      break;
    case 110100:
      //code for d is 011 0100
      lcd.print("d");
      break;
    case 110101:
      //code for e is 011 0101
      lcd.print("e");
      break;
    case 110110:
      //code for f is 011 0110
      lcd.print("f");
      break;
    case 110111:
      //code for g is 011 0111
      lcd.print("g");
      break;
    case 111000:
      //code for h is 011 1000
      lcd.print("h");
      break;
    case 111001:
      //code for i is 011 1001
      lcd.print("i");
      break;
    case 111010:
      //code for j is 011 1010
      lcd.print("j");
      break;
    case 111011:
      //code for k is 011 1011
      lcd.print("k");
      break;
    case 111100:
      //code for l is 011 1100
      lcd.print("l");
      break;
    case 111101:
      //code for m is 011 1101
      lcd.print("m");
      break;
    case 111110:
      //code for n is 011 1110
      lcd.print("n");
      break;
    case 111111:
      //code for o is 011 1111
      lcd.print("o");
      break;
    case 1000000:
      //code for p is 100 0000
      lcd.print("p");
      break;
    case 1000001:
      //code for q is 100 0001
      lcd.print("q");
      break;
    case 1000010:
      //code for r is 100 0010
      lcd.print("r");
      break;
    case 1000011:
      //code for s is 100 0011
      lcd.print("s");
      break;
    case 1000100:
      //code for t is 100 0100
      lcd.print("t");
      break;
    case 1000101:
      //code for u is 100 0101
      lcd.print("u");
      break;
    case 1000110:
      //code for v is 100 0110
      lcd.print("v");
      break;
    case 1000111:
      //code for w is 100 0111
      lcd.print("w");
      break;
    case 1001000:
      //code for x is 100 1000
      lcd.print("x");
      break;
    case 1001001:
      //code for y is 100 1001
      lcd.print("y");
      break;
    case 1001010:
      //code for z is 100 1010
      lcd.print("z");
      break;
    case 11000:
      lcd.print("dit gebeurt vaak");
      break;
    case 1011001:
      lcd.print("dit ook");
      break;
    case 100001:
      lcd.print("tenslotte dit nog");
      break;
    case 1011000:
      lcd.print("en dit is de laatste denk ik");
      break;
    default:
      lcd.print(binary);
      lcd.print("CAME IN DEFAULT ON PRINTCHAR");
      break;
  }
}

```

I want to print this output on LCD. But I'm not able to do that. Please help me out.

Circuits:

(1) VLC Circuit

(2) LCD Circuit

I combined both circuits above and made a final circuit.

The VLC circuit is set up in which DATA is transmitted from SIMPLE LED and Capture on PHOTODIODE. And using LCD Circuit I want to display data on LCD.

# Answer
Finally, got the problem. My code is working fine. I have a problem with my LCD connection.

I write

```
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

```

Instead of

```
LiquidCrystal lcd(12, 11, 4, 5, 6, 7);

```
> 1 votes

# Answer
There is so many problems with your code. It can be so much short.

Take WriteChar. Why mess with binary value for chars? Use char directly, just here:

```
void setup() {
  Serial.begin(9600);
  WriteChar('h');
  WriteChar('e');
}

void loop() {
}

void WriteChar(char c) {
  boolean b7 = c & B1000000;
  boolean b6 = c & B0100000;
  boolean b5 = c & B0010000;
  boolean b4 = c & B0001000;
  boolean b3 = c & B0000100;
  boolean b2 = c & B0000010;
  boolean b1 = c & B0000001;

  Serial.println(c);
  LightFlash(b7, b6, b5, b4, b3, b2, b1);

}

void LightFlash(boolean b7, boolean b6, boolean b5, boolean b4, boolean b3, boolean b2, boolean b1) {
  Serial.print(b7 ? "1" : "0");
  Serial.print(b6 ? "1" : "0");
  Serial.print(b5 ? "1" : "0");
  Serial.print(b4 ? "1" : "0");
  Serial.print(b3 ? "1" : "0");
  Serial.print(b2 ? "1" : "0");
  Serial.println(b1 ? "1" : "0");
}

```

There is more simply ways to write that (using arrays and loops) but this is easier to understand. And better, pass the char directly to LightBlash.

Don't use a string when you just pass a char to a function.
> 2 votes

---
Tags: arduino-uno, serial, lcd, serial-data
---


title: Code to obtain PWM output

text:
# Question
Title: Code to obtain PWM output
I tried code to obtain 100KHZ PWM output with a 41.66% duty cycle by reading an analog value from A0, which is compared with a reference 5V value for obtaining PWM value.

Can someone help me with the code? Any help is very much appreciated.

Here is my code.

```
int Pwmpin=9;//Pwm Output Pin
int Fchange= A0;//Frequency change through Potentiometer

void setup() {
  pinMode(Pwmpin, OUTPUT);//Pwm pin as Output
  Serial.begin(9600);
  TCCR1A=_BV(COM1A1)|_BV(COM1B1);//Non-inverted Mode
  TCCR1B=_BV(WGM13)|_BV(CS11);//Prescalar 8
}

void loop(){
  float freq=0;
  float count=10000,countt=0,Pinput=0;
  while(1){
    ICR1=count;//variable Frequency
    countt=16*count;
    freq= int(16000000/countt);
    OCR1A=int(count/2);
    Serial.print("Pwm Freq =");
    Serial.println(freq);
    count=10000;
    Pinput=analogRead(A0);//Read input value
    Serial.print("adc value is:");
    Serial.println(Pinput);
    Pinput=(Pinput/0.0113);
    Serial.print("pwm value is:");
    Serial.println(Pinput);
    count=count+Pinput;
    if(count>=100000) {
      count=10000;
    }
    delay(1000);
  }
}

```

# Answer
1. Read the datasheet.
2. Figure out which pen mode works for you and which prescaler and top you need.
3. Set timer1 to that mode.

After that all you need is to load the duty cycle register with the desired value.

For your application leave the top value alone.

Your code is far from that.
> -1 votes

---
Tags: pwm
---


# Question
Title: Arduino Gesture Sensor error:No such file or directory
I cloned https://github.com/sparkfun/APDS-9960\_RGB\_and\_Gesture\_Sensor and copied the libraries into the Arduino `libraries` folder. I then launched Arduino and selected the example. I opened the file GestureTest and when I started upload I received this error:

> GestureTest.ino:49:31: fatal error: SparkFun\_APDS9960.h: No such file or directory
>
> compilation terminated.

I checked the `SparkFun_APDS9960.h` and I found it in the `Gesture_Sensor/Libraries/src` folder.

Is there a solution to resolve this error?

# Answer
SparkFun made a poor choice for the folder structure of that repository. Likely this has caused you to incorrectly install the library. Please follow these instructions:

1. Download the latest release from https://github.com/sparkfun/APDS-9960\_RGB\_and\_Gesture\_Sensor/releases. Currently it is https://github.com/sparkfun/APDS-9960\_RGB\_and\_Gesture\_Sensor/archive/V\_H1.0\_L1.4.2.zip.
2. Unzip the downloaded file.
3. Rename the folder `APDS-9960_RGB_and_Gesture_Sensor-V_H1.0_L1.4.2/Libraries/Arduino` to `SparkFun_APDS9960`. This is not absolutely necessary but "Arduino" is not a very descriptive name for a library folder and the Arduino IDE works best when the library folder name matches the primary header file name so this is best practices.
4. Copy the `SparkFun_APDS9960` folder to `{sketchbook folder}/libraries`. You can find the location of the sketchbook folder at **File \> Preferences \> Sketchbook location**.
5. Restart the Arduino IDE if it's running (not necessary with recent versions of the Arduino IDE).

Note that the folder structure of this library requires Arduino 1.6.x or newer.

UPDATE: I submitted a pull request to put the library in an appropriately named folder. This won't change the instructions above until the next release but it does remove the need to rename the folder if you are cloning the repository or downloading from the tip of the repository rather than a release.
> 0 votes

---
Tags: sensors, library
---


# Question
Title: Do all serial ports on an Arduino MEGA 2560 have the potential to "brick" attached items when being flashed?
I was browsing through the hookup guide for SparkFun's OBD-II UART breakout and found something particularly worrying written half way down in a quite casually presented way:

> Keep in mind when you upload this to your board, you will want to disconnect the OBD-II board RX line from the Arduino TX-0, to prevent issues during code upload, such as bricking the OBD-II board.

For my money I think bricking your device should come with a more stark warning than one stuffed part way down a guide starting with "keep in mind" and continuing with "issues". Nonetheless it caught my attention as I tend to build sealed boxes that aren't sprawled in front of a keyboard ready to be rewired any time a re-flash might happen.

Is the real risk here the fact that all of the flashed data would stream past the RX pin of the UART board and potentially accidentally send a 'self-destruct' signal? (Also I'm not sure a system is really up to scratch if you can accidentally tell it to kill itself.)

Surely the programming port is not the one being borrowed by the UART hookup? On a MEGA 2560, using a different serial port, is this still a risk or is that only on boards with one serial port?

# Answer
In the Sparkfun example the Arduino Uno is used. The Uno has only one hardware serial port, and that is used to upload a sketch and for the serial monitor. Pin 0 (RX) and pin 1 (TX) can be overriden for something else. However, then you must know what you are doing, and connect and disconnect modules as required.

The Arduino Leonardo and (Pro) Micro use a USB CDC implementation and have a unused hardware serial port at pin 0 and 1.

The Arduino Mega 2560 uses the hardware serial port at pin 0 and 1 to upload a sketch, just as the Uno. However, the three other hardware serial ports are not used, and you are free to use them.

If you use an unused hardware serial port for the OBD-II, there is no risk at all. You can use that port and nothing else messes with that port.

If you use a serial port that is also used to upload a sketch, or a software implementation of a serial port, you probably are going to make a mistake some day, and there is a risk to send the wrong data to the wrong hardware.

\[**ADDED**\]
I see that the example code in the SparkfunHookup Guide uses the Arduino Uno and SoftwareSerial on pin 2 and 3. That is independent of the hardware serial port. The SoftwareSerial is something that should be used as a last resort, since it almost completely takes over the Arduino board. It's good to have SoftwareSerial, but try to avoid it.
If you do want to use an Arduino Uno, perhaps the AltSoftSerial can be used. The AltSoftSerial works okay for 9600 baud as long as no other code uses too much time in interrupts and no one else uses TIMER1.
> 1 votes

---
Tags: serial, uploading
---


title: FTDI breakout connection

text:
# Question
Title: FTDI breakout connection
I have been successfully programming UNO boards. I wanted to transfer the project to a Pro Mini. I am using a FTDI breakout. It wouldn't show the device port. I found the device driver I was using was supplied by MatterControl. So I updated the driver from FTDI.

When I connected it I see the port available, but cannot program it. I get

```
not in sync: resp=0x01 avrdude: stk500_recv(): programmer is not responding

```

I checked in the device manager and see "USB Serial Port (COM5)" and properties shows "This device is working properly." the provider is FTDI.

# Answer
> 0 votes
This error can come from a number of sources and you'll find this is a common question on arduino.stackexchange. The most likely reasons are:

* If the board wasn't reset, the bootloader didn't run;
* Rx & Tx connections between the FTDI and the board may be reversed;
* Avrdude may be using a different baud rate than the bootloader expects. 57600 baud used to be standard for Atmega328p bootloaders. More recent firmware is using 115200 baud. I've been bitten by this one regularly; my chips have older bootloaders and one of my PCs has a very recent Arduino IDE.

# Answer
> 1 votes
I made the board using the great tutorial by Nick Gammon for the minimum Arduino board. I got the boot loader to load using Nick's tutorial and then spent a few evenings trying to use FTDI to upload sketches but could not get it to work. In the end, using various bits of inforamtion I found on the web, I made sure the reset signal was coming from the the FTDI (going to low) and then checked the settings of the FTDI and tried to make some changes. I found that the settings in my photos work. Mainly the bit rate 115200 and the latency (m/secs) time to 5 m/secs. The wires from FTDI starting from the top in looking at photo - brown (ground to ground), red (vcc to vcc) orange (tx to rx), Yellow (rx to tx), the other separate orange (was better I used another colour!) is from RTS to reset. I selected Arduino uno as board and (in my case) COM 10. For me it ow works. I don't know if I would make many of these boars though because of the time and effort. However, itwas a good expeiance and I learnt a great deal. Particularly from Nick Gammon. Thanks Nick!

# Answer
> 0 votes
The problem was resolved by changing "set RTS on close" in the device manager properties as stated here https://electronics.stackexchange.com/a/87955/80377

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


title: Arduino Nano USB Serial Bypass

text:
# Question
Title: Arduino Nano USB Serial Bypass
I have a Nano clone here, that sporadically fails to get detected by my banana pi. This is annoying, because it works for days and hours, but fails to work randomly.

The Nano gets it's own power via `VIN` and thus should have enough power.

I thought of bypassing the FTDI and make a Serial connection via 2 Wires. Alternatively: Is there a way to force the arduino to use external Power over USB. I have the feeling, the the arduino wrongly decides, that USB is the better power source and uses it, causing the errors ( `device not accepting address 21, error -62` )

P.S.: There is also a touch-screen connected to the banana pi via USB. Whatever port I use, It works and never failed. Just the Nano fails from time to time.

# Answer
> 0 votes
To answer this question

The arduino in question was broken. Shortly after asking I was not even able to connect it to my PC successfully. I replaced it with a new one and everything runs smoothly now for months.

Since this unit survived a whole product development-process I am not surprised at all. In fact I had three and expected one to get killed in action.

---
Tags: serial, arduino-nano
---


# Question
Title: Arduino Uno not including two header files at the same time
I have an Arduino Uno and I am trying to control a stepper motor with it. I also have an RF transmitter and receiver (433MHZ). I need to transmit data about motor status.

For RF I am following this page. Individually both are working great. I am able to send data from one Arduino (TX) to another (RX). And also I am able to control the motor. But when I am merging these projects, their header files are giving an error.

For RF, I need to include `#include <RH_ASK.h>` and for the motor I need include `#include <Servo.h>`. When I am including these headers files, they are giving me this error:

```
Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin): In function `RH_ASK::maxMessageLength()':

(.text+0x0): multiple definition of `__vector_11'

libraries\Servo\avr\Servo.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

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

```

I do not know what's wrong here. Can anyone please help me?

# Answer
> 2 votes
First of all, that page has a link to an old version of the RadioHead library.
This is a link to RadioHead: www.airspayce.com/mikem/arduino/RadioHead. You will find the newest library on that page.

The Servo library uses TIMER1.
The RadioHead in RH\_ASK mode uses TIMER1.
Both use the same interrupt of TIMER1. That is what the compiler is trying to tell you with: "*multiple definition of \_vector\_11*".

You could move one of them to TIMER2.
There are alternative Servo libraries that use TIMER2.
The RadioHead can set a define for TIMER2. The explanation is in the library files in RH\_ASK.h, you have to set "#define RH\_ASK\_ARDUINO\_USE\_TIMER2" in RH\_ASK.cpp.

Why are you using the Servo library for a stepper motor ?

# Answer
> 0 votes
It is telling you that interrupt vector 11 is being defined multiple times. Such definitions should be done in the source file, not in the header file.

---
Tags: arduino-uno
---


# Question
Title: How to control Arduino using mBlock and Bluetooth?
Is it possible to control an Arduino using mBlock and Bluetooth?

Assuming yes, I tried various things, but was not able to come to a conclusion.

I am trying to get this combination working using a HC-05 Bluetooth module. I am not sure if my Bluetooh setup is the problem or is mBlock is not able to recognize the COM port provided by Bluetooth.

I can see the COM device (in fact two?) when I pair HC-05 with PC. I have the following questions based on whatever I have tried so far:

* When I connect HC-05, should I connect TX to TX OR reverse them?
* There are varying articles describing both ways of connection.
* How much baud rate do I need to set on the Bluetooth device?
* Do I need to use the voltage divider for RX? Again there are varying tutorials.
* Is mBlock default Arduino firmware sufficient for such setup?

# Answer
> 0 votes
I got it working. Following are steps.

* Set the Bluetooth baud rate to 115200. The mBlock firmware uses this baud rate for serial communication.
* Connect Bluetooth to Rx and Tx of Arduino.
* Upload default Arduino firmware (orion firmware) to Arduino using mBlock.
* Use mBlock to interact with Arduino using Bluetooth.
    + Please note that Bluetooth cannot be used to upload the sketches to Arduino for offline mode.

# Connecting Bluetooth COM device to PC in AT mode to set baud rate.

* Upload empty (default) sketch to Arduino using USB cable.
* Connect 5V of BT shield to 3.3V of Arduino.
* Connect EN or BT to 5V.
* Connect Tx to Tx and Rx to Rx.
* Use USB cable to power on Arduino.
* Before turning the power ON, keep pressing the EN button on BT shield. The LED should blink with almost a second delay. That is the indication that it is AT mode.
* Start Arduino IDE, and connect to the COM port of Arduino and NOT that of the BT.
* Start serial monitor.
* Set the baud to 38400 and terminate character settings to "Both NL $ CR".
* In the command input field of Serial Monitor type `at` twice. First time response will be error, second time it should be ok.
* Now use the at commands to set baud rate using "at +uart=115200,0,0" e.g.
* Use "at +uart?" to see what is the baud rate set on the device.

# Connect Bluetooth device to Rx and Tx of Arduino.

Arduino \<-\> HC-05 ======= ======= 5V Vcc GND GND Rx Tx Tx Rx (Via Voltage divider)

Some of the articles talk about connecting 3.3V of Arduino to the Vcc of HC-05 and not using the voltage divider at all. However this combination fails as once increases the baud rate.

Check out more details about voltage divider here. https://electronics.stackexchange.com/questions/280500/why-do-you-have-to-use-a-voltage-divider-with-hc-05-bluetooth-module-arduino

# What is the story of two COM devices for Bluetooth?

# Answer
> 0 votes
> * When I connect HC-05, should I connect Tx to Tx OR reverse them?
>     + There are varying articles describing both ways of connection.

Yes, swap them. TX on the HC-05 to RX on the Arduino. However you could struggle to use pins 0/1 since they are the USB connection. SoftwareSerial (which is nasty) is what most people use instead.

> * How much baud rate do I need to set on the bluetooth device?

Whatever rate you want to communicate at. It's up to you. However all baud rates must match throughout the system - the baud rate on the Arduino, the baud rate of the HC-05, the baud rate of the SPP port on your PC, etc.

> * Do I need to use the voltage divider for Rx? Again there are varying tutorials.

Which RX? Arduino TX to HC-05 RX yes. HX-05 TX to Arduino RX no.

> * Is mblock default arduino firmware sufficient for such a setup?

What is *mblock*?

---
Tags: arduino-uno, hc-05
---


title: Arduino ESP8266 receive email?

text:
# Question
Title: Arduino ESP8266 receive email?
Is there a sketch that supports the receiving of email using the Arduino environment on the ESP8266? I can only find support for sending email. I know it's possible because the NodeMCU environment supports it. Any help is appreciated!

# Answer
> 1 votes
Once you know how to connect to any server and send messages to it, retrieveing emails is just a matter of sending right messages (=commands).

Here below follows an "IMAP tutorial", i.e. guide to which commands to send to an IMAP server to search and retrieve messages.

Note: once you connect to the IMAP server, the first command to send is the login command:

```
foo login user password

```

"foo" is just a session identifier, not a keyword. "login" is the keyword.

Once you get the welcome message, you can start sending more commands:

Select the proper folder:

```
. SELECT "INBOX"

```

Look for desired message (strings are always considered substrings, so no wildcards are needed):

```
. SEARCH FROM "user@example.org" SUBJECT "some keywords here"

```

This will result in list of matching messages, with search results formatted as follows:

```
* SEARCH 5 10 456

```

This means messages n.5, n.10 and n.456 match the query.

If examining just the subject (which may contain keywords and switch as required) is not enough, the whole body can be retrieved, both marking the message as read or leaving it untouched:

```
. FETCH 5  BODY[TEXT]

```

or

```
. FETCH 5  BODY[TEXT].PEEK

```

End IMAP session with:

```
. logout

```

For experiments from Windows using telnet:

```
telnet mailserver.domain.com 143

```

Reference:

https://www.skytale.net/blog/archives/23-Manual-IMAP.html

---
Tags: wifi, esp8266
---


# Question
Title: GSM 900A modem not responding to AT commands
I am using GSM 900A modem which requires 5V Supply. I am connecting it to Arduino UNO. I am giving supply to modem by arduino 5V and GND pin. I am connecting RXD pin to TX(pin 1) of arduino TXD pin to RX(pin 0) of arduino and GND to GND of arduino i.e. pin 14. I am running the basic example codes but GSM is not responding. I have also tried other softwares like Putty but I am unable to write any AT command Please help me. When I tested the modem using this code:

```
/*

 This example tests to see if the modem of the
 GSM shield is working correctly. You do not need
 a SIM card for this example.

 Circuit:
 * GSM shield attached

 Created 12 Jun 2012
 by David del Peral
 modified 21 Nov 2012
 by Tom Igoe

 http://www.arduino.cc/en/Tutorial/GSMToolsTestModem

 This sample code is part of the public domain

 */

// libraries
#include <GSM.h>

// modem verification object
GSMModem modem;

// IMEI variable
String IMEI = "";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start modem test (reset and check response)
  Serial.print("Starting modem test...");
  if (modem.begin()) {
    Serial.println("modem.begin() succeeded");
  } else {
    Serial.println("ERROR, no modem answer.");
  }
}

void loop() {
  // get modem IMEI
  Serial.print("Checking IMEI...");
  IMEI = modem.getIMEI();

  // check IMEI response
  if (IMEI != NULL) {
    // show IMEI in serial monitor
    Serial.println("Modem's IMEI: " + IMEI);
    // reset modem to check booting:
    Serial.print("Resetting modem...");
    modem.begin();
    // get and check IMEI one more time
    if (modem.getIMEI() != NULL) {
      Serial.println("Modem is functoning properly");
    } else {
      Serial.println("Error: getIMEI() failed after modem.begin()");
    }
  } else {
    Serial.println("Error: Could not get IMEI");
  }
  // do nothing:
  while (true);
}

```

I am getting this output on Serial Monitor for 9600 baud rate:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Resetting modem...Modem is functioning properly

# Answer
The modem library does not communicate on pins 0 and 1. Check the reference library and tutorial. It should be pins 2 (RX) and 3 (TX). Reset is pin 7. The configuration may be found in GSM3IO.h. https://github.com/arduino/Arduino/blob/master/libraries/GSM/src/GSM3IO.h. See also https://www.arduino.cc/en/Main/ArduinoGSMShield
> 1 votes

# Answer
If you connect a GSM modem to the Arduino's Hardware Serial pins (1/0) then you *cannot* also use those pins to communicate with a host PC.

Your question is tagged "Arduino Uno" therefore the status reporting messages to the PC will be sent over these pins, and become hopellesly confused with the traffic to the GSM modem.

You must place the modem on pins distinct from the PC interface - either using a software serial interface on different pins of an Uno, using a Leonardo-type board where the PC interface does not involve the hardware UART pins, or by using a board with multiple hardware UARTs.
> 0 votes

# Answer
This answer may be totally misleading because I can't find a "GSM 900A" but I can find lots of "SIM900A GSM" results. One thing I did notice is they require a 1A+ supply to cater for transmissions so I think running of an Arduino may mean you are not giving it enough power, you should use a 1.5A supply and make sure the grounds are connected.
> 0 votes

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


title: Infinite "while" statement

text:
# Question
Title: Infinite "while" statement
I am building a robot that is both obstacle-avoiding and remote-controlled. The robot uses an infrared remote. When the front button is pressed the robot moves front, when the right button is pressed the robot turns right, and so on...
When a certain button is pressed the robot switches to obstacle-avoiding mode and starts to drive around. When the ultrasonic sensor detects an object 15cm away the robot turns right, reverses, and then continues moving forward. the obstacle-avoiding code has a problem, though. Here is the code:

```
#include <EEPROM.h>
#include <IRLib.h>
#include <AFMotor.h>
int frontlights = A1;
int backlights = A2;
int buzzer = A3;
int pingPin = A4; //setup pingpin as A4

//ir variables
int RECV_PIN = A0;
IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
unsigned int Buffer[RAWBUF];

void obstacle_avoiding(){
   while (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){  // when the automatic mode button is pressed and the stop button is not pressed do...

 motor4.setSpeed(230);
 motor3.setSpeed(230);
 motor2.setSpeed(230);
 motor1.setSpeed(230);

    long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(90);

      if(cm>15){          // if an object is greater than 10cm move forward
      motor_forward();
      Serial.println("forward");
      digitalWrite(backlights, LOW);

      }

     else if (cm<=15)     // if an object is less than or equal 10cm move backward then turn right
     {
      motor_stop();
      digitalWrite(frontlights, HIGH);
      digitalWrite(backlights, HIGH);
      digitalWrite(buzzer, HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      delay(2000);
      motor_backward();
      digitalWrite(backlights, HIGH);
      Serial.println("backward");
      delay(500);
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(900);
      motor_right();
      digitalWrite(backlights, LOW);
      Serial.println("right");
      digitalWrite(frontlights, LOW);
      delay(400);

   }
   if (My_Decoder.value==0xFF0AF5){   //the stop button is pressed break the "while" loop and stop the robot
   break;
   motor_stop();
   }
 }
}

void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();

    //automatic code here
            else if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

```

The code is working however when the "while" statement becomes true it will loop infinitely not stopping even when the condition has become false. I thought while statements should loop until the condition becomes false. Am I misinformed?

# Answer
> 1 votes
`My_Decoder.value` doesn't change inside `obstacle_avoiding()`. Hence, `while` is running infinitely.

I think you have to delete the `while`, and let `loop()` take care of controlling the execution.

**Addendum**

The intent of the `loop()` is to read some IR data in value. I under the impression that `getResults()` sometimes block, acording to this:

> However the IRrecvLoop is not interrupt driven and so when you call GetResults it sits in a tight loop and does not release control back to you until the complete signal has been received.

I also want to check that `value` doesn't change if `getResults()` return nothing with this `loop()`

```
void loop() {
bool r = My_Receiver.GetResults(&My_Decoder)
Serial.print("getResults()=");
Serial.print(r);
Serial.print(" value=");
Serial.println(My_Decoder.value);

if (r) {
    //Restart the receiver so it can be capturing another code
    //while we are working on decoding this one.
    My_Receiver.resume();
    My_Decoder.decode();
} else {
    if (My_Decoder.value == 0xFF807F && My_Decoder.value != 0xFF0AF5) {
        obstacle_avoiding();
        }
    }
}

```

I hope this works!

# Answer
> 0 votes
Copy/paste this part only:

```
void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();
        }
    //automatic code here
           if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

```

---
Tags: arduino-uno, sensors, robotics, infrared
---


title: Why is the GSM shield so expensive?

text:
# Question
Title: Why is the GSM shield so expensive?
I've been doing some Googling for GSM shields and their prices and frankly I don't understand why they are so expensive on average.

The official one sold by Arduino is 71 euros for me (I live in Europe), and third party ones have similar prices.

A cheap dumb-phone is usually 30 euros and those phones have become really impressive these days, they have even a camera. When they are locked with the carrier the price can go as low as 20 euros. How is it even possible that a single part of what is supposed to make up a phone is more expensive than the phone itself? :(

Thanks in advance!

# Answer
If you are ready to wait a month for delivery and also giving up flexibility by restricting yourself to just sending and receiving SMS, then you can go as low as €2 for a DIY kit on AliExpress.

By adding more money, you also get more features. Just sarch for "gsm arduino" or "SIM800", "SIM900".
> 1 votes

---
Tags: gsm
---


# Question
Title: What is the difference between python and arduino programming?
I am a Python programmer and want to learn Arduino programming so want to know what are the main differences between Python and Arduino C++ programming?

Is Arduino C++ more complex than Python programming?
Are there any similarities that will help me? Are there any formatting restrictions like in Python? Etc...

According to this page(printing hello), Aurdino programming looks easy to me.

# Answer
Arduino uses a language that is derived from Processing, which looks like C++.

Python is a different language, although both have similarities (both Object Oriented for example).

What is 'complex' depends on what your background is. C++ is in general more complex than Arduino, but most people using Arduino program in C++, so most examples can be found in C++, which makes support from other users easier.

If you are new to programming, I suggest using the 'standard' Arduino IDE.

To be complete, Arduino is not a programming language, it is a platform. In general, every language can be used to write Arduino code, but only a few have compilers for creating Arduino (machine) code.
> 1 votes

---
Tags: python
---


# Question
Title: Adafruit Gemma unrecognised USB device on Windows 10
I have a V2 Adafruit Gemma from the Gemma starter pack, and I'm running Windows 10 Home (version 10.0.14393), on a 64-bit laptop. Following the Introducing Gemma guide I've installed the Adafruit drivers and I'm now trying to get it to connect via USB.

After connecting, the board shows the green power LED, but not the pulsing red LED, and Windows shows the 'USB device not recognised' message.

**Tried so far**

* I'm definitely using USB 2 ports, and I have tried it connected directly to the PC and via a USB hub.
* I'm pretty sure the cable is working correctly (It works for exchanging data on a phone, and I've tried a few different ones).
* Under Device Manager, the board shows as 'USB Device (Device Descriptor Request Failed)'.
* 'Update driver software' \> 'Search automatically...' reports that 'The best driver software for your device is already installed'.
* If I do 'Update driver software' \> 'Browse my computer...' and point it to the manual Adafruit driver files (available on the link to the guide), I get the same message.

Can anyone suggest anything to try? Do I need to (re)install the bootloader itself, and if so, can you point me in the direction of how I do this?

**Update**

As mentioned in the comments I have posted on Adafruit's own support forum but got absolutely nothing yet. I have also tried it on my work PC (Windows 10 Pro, 64-bit) and got exactly the same behaviour.

I'm keen to get this sorted so bounty added for anyone who can at least come up with some suggestions of what to try!

# Answer
> 1 votes
I think, you've pretty much done everything. If you could gain access to another board, and try that one you could figure out more. Otherwise your symptoms remind me of a something called an ESD (Electrostatic Discharge) caused malfunction. This basically means one of the system essential chips on the board have been fried. It is very easy to ESD a chip without protection, just walk on a carpet or put on a sweater, and than touch the chip. Chances are you were electrostaticly charged with thousands of volts. The chip does not stand a chance. To prevent this from happening, touch something made out of metal before touching the board.
More on ESD: Electrostatic discharge

---
Tags: usb, adafruit
---


title: Programming an Arduino Mini 05

text:
# Question
Title: Programming an Arduino Mini 05
So, I recently bought an Arduino Mini (5V, 16MHz), and a USB to Serial Converter. Provided are the links to both the products: Arduino Mini, USB to Serial Converter

Now, I tried programming the mini by connecting the pins in this order: Rx -\> tx, tx-\> rx, VCC -\> 5V, GND -\> GND, DTR -\> DTR

The computer detected the USB to Serial converter after I installed the drivers manually. However, the Arduino IDE failed to program the Arduino Mini every single time, even after I swapped the TX, RX pins.

I tried to program the Arduino Mini using an Arduino Uno (I removed the onboard Atmel Atmega microcontroller on the Uno before programming). I connected the pins in this order: TX-\>TX, RX-\>RX, 5V-\> VCC, GND-\> GND, RST -\> DTR. From the IDE, I chose Arduino Pro Mini (5V, 16Mhz).

The Mini was programmed successfully this time.

My question: What was wrong with the USB to Serial converter? Why couldn't it program the Arduino Mini with the USB to Serial Converter?

# Answer
As you have said the Arduino Mini seems to be fine and the USB to Serial Converter seems to be working too.

**This might be a crazy idea but this might work**

try connecting the boards like this,

**TX -\> TX and RX -\> RX**

I'm not totally sure, but this might work.
> 2 votes

# Answer
Try to reset manually just after compiling end
> 1 votes

# Answer
> The Mini was programmed successfully this time

If so, one of them had its tx/rx pins mislabeled.
> 0 votes

---
Tags: programming, usb, arduino-mini
---


title: Lifespan of a hot microchip

text:
# Question
Title: Lifespan of a hot microchip
I'm currently building my own Home Automation System with a bunch of Arduinos and Relais, all of them wired to Ethernet "Shields". The casing I am printing on a 3D printer.

The Arduinos work great with those Ethernet "Shields", but the ENC28J60 chip on those Ethernet boards get quite hot. I am measuring 79.5°C approx. In the plastic casing, I expect that they reach higher temperatures (because it's closed and has no ventilation whatsoever).

Since I am building this as a permanent solution (House wiring is now all newly adapted and I have no way back), which lifespan can I expect from those Ethernet boards?

The datasheet of that chip is saying that it's rated up to 85°C, but what does this upper rating mean? Will it stop working at this point, or only begin to degrade it's lifetime at this point?

EDIT: I have no space to put a dissipation block on those chips, because the casing is so tight.

# Answer
The reliability data is typically not in the product datasheet but in pen whitepapers. Generally speaking life span goes down exponentially as temperature rises. For some high temperature semi conductors ( designed specifically for high temperature applications) you are talking about hubdreds or thousands of hours at rated temperatures.

That should give you some sense as to what to expect.
> 0 votes

---
Tags: ethernet, temperature
---


# Question
Title: polynomial change of LED brightness arduino
I try to change the brightness of an LED following the formular in out1. I'm pretty sure that something is going wrong because it doesn't really change its brightness and it never stops lightening. Can pleas somebody help me. It should basically do the same than a sin wave but instead of the sin I try to use my equation!

```
const int LED = 11;
const int LED1 = 10;
const int LED2 = 9;

void setup()
{
}

void loop()
{
float in1, out1, out2, out3;

for (in1 = 0; in1 < 10; in1++)
{
out1 = 8.8 * pow(10,-4) * pow(in1,4) - 0.0034 * pow(in1,3) +0.37* pow(in1,2) -6.7 *in1 +1.7 *pow(10,2);
//out2 = 1.207*pow(in1,4)-0.0011*pow(in1,3)+0.16*pow(in1,2)-5.5*in1+2,0763;
//out3 = 4.829*pow(in1,4)-0.034*pow(in1,3)+0.37*pow(in1,2)-6.7*in1+2,076;

analogWrite(LED,out1);
delay(10);
//analogWrite(LED1,out2);
//analogWrite(LED2,out3);

}

analogWrite(LED,LOW);

/*analogWrite(LED,out1);
analogWrite(LED1,out2);
analogWrite(LED2,out3);
//analogWrite(LED1,LOW);*/
delay(500);

```

# Answer
Here is the proper way to implement a polynomial function. It's a direct application of Horner's method:

```
// Polynomial function for output 1.
static float f1(float x)
{
    return (((8.8e-4 * x - 0.0034) * x + 0.37) * x - 6.7) * x + 1.7e2;
}

```

You would use it like this:

```
void loop()
{
    for (int x = 0; x < 10; x++) {
        analogWrite(LED, f1(x));
        delay(10);
    }
    digitalWrite(LED, LOW);
    delay(500);
}

```
> 1 votes

# Answer
You should make sure that your code works with known good values for out1.

After dthat, try to make sure that your formula produce values in a valid range - check analogWrite to see what values it expects.

Then you should make sure that your code formula is what you want. Aka the code reflects your intent correctly.

edit: here is what I use to calculate polynomial functions.

```
//return poly functions
//x: independent variable
//degree: degree of the polynomial function
//p[]: array for the coefficients
double poly(double x, int degree, double p[]) {
  double tmp=0;  //temp variable

  while (degree--) tmp = tmp * x + p[degree];

  return tmp;
}

```

by providing different "degree" and "p\[\]/coef", you can calculate any polynomial function with one call to poly().

I generally use a set of macros to further simplify the calling to that function.
> 0 votes

---
Tags: led, analog-sampling
---


title: My button control working in reverse

text:
# Question
Title: My button control working in reverse
I built this circuit to learn button control.

But my code (or button) is working in reverse. I want to initialize led flash effect when the button is pressed with this code

```
buttonState = digitalRead(8);
if (buttonState == HIGH)
  doFlash();

```

Instead the effect runs continuously and pauses if I push and hold the button. If change the condition as `if (buttonState == LOW)` code is working as expected. (Effect starts when I push the button.)

This is just the opposite of what I read in tutorials. What is wrong in my circuit or code?

Full code:

```
 void setup(){
  for(int i=2;i<=6;i++)
  pinMode(i,OUTPUT);
  pinMode(8,INPUT_PULLUP);
 }

 void loop(){
  int buttonState;

  buttonState = digitalRead(8);
  if (buttonState == LOW)
    doFlash();
 }

void doFlash() {
    int i;
    for (i=2;i<=6;i++) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
    for (i=6;i>=2;i--) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
}

```

# Answer
Most tutorials will make the code more "intuitive" by adding additional components to the circuit. E.g.

Here you can see one end of the button is connected to 5 volt, will the other end is connected to a digital input, and via a (pull-down) resistor to ground.

If the button isn't pressed the pull-down resistor will make the input read LOW. If the button is pressed the input will go to 5v (overpowering the pull-down resistor) and the input will read HIGH.

Like you I found the pull-up version a bit weird. But once I figured out how both versions worked, I now prefer the pull-up one. For once, because you don't need an addition resistor. (And secondly because I don't like to use unrestricted 5v signals. If in the above example you accidentally set the input to an output, and press the button, you create a short, and could blow up the micro controller.)
> 0 votes

# Answer
This behavior is expected: INPUT\_PULLUP means the pin is pulled up via the internal pull up, i.e. it will read as high if not connected externally.

With your push button you connect it to ground (0 volts), thus bringing it to low level and it will read as low. Therefore, in your code, you need to check for low level (LOW) to check if the button is pressed (as you found out by changing the code).
> 4 votes

# Answer
There are two kinds of logic: "active high" and "active low". (At least that's one way to characterize it.) Your circuit is "active low", and there's nothing wrong with it. If fact, when you use the internal pull-up resistors of the microcontroller you're bound to use active low logic. (More modern microcontrollers have configurable pull-up or pull-down resistors.)

If this confuses you you can use a #define in your code:

```
#define ACTIVE LOW

if (buttonState == ACTIVE)
  doFlash();

```
> 2 votes

# Answer
i had the same problem and no body solved it for me.but i got the solution and it works.
> 0 votes

---
Tags: arduino-uno, button
---


title: Very bright cursos positions

text:
# Question
Title: Very bright cursos positions
As you may can I see on the picture. I try to display the word "goodbye". Yet the problem is that the cursor positions are to bright. I hooked up a 10k ohm potmeter to the Anode. To change the backlight. Is there a way to make the cursos positions less visible?

Kind Regards,

Q

# Answer
> 0 votes
issue fixed: I adjusted the Anode (pin15) instead of the contrast (pin3).

Look at the conversation between me and Majenko to see the realisation.

---
Tags: arduino-uno, lcd, potentiometer
---


# Question
Title: Why would digital outputs on Arduino Due be less than 3.3V?
We are working on a project that requires a temperature sensor to tell the Arduino Due to turn a digital pin to HIGH (3.3V) to active a relay so a heating pad can be powered on.

We have diagnosed all possibilities and the only explanation as to why the switch will not active is the digital pins are only reading 1.8 V on the relay.

We are using a JQC-3F(T73) relay. We are using two digital pins to give it plenty of voltage and amps to switch on and off when needed.

so any explanation as to why it isnt working? thanks.

# Answer
The output impedance for the MCU used in the Due is about 46ohm. Along with the relay's impedance this forms a voltage divider that results in a final voltage that is lower than the unloaded voltage from the output.

In any case, **do not** connect an inductive load directly to a MCU; use a driver such as a ULN2803 instead, being certain to connect the flyback connection of the driver chip properly.
> 3 votes

---
Tags: arduino-due, relay, digital
---


# Question
Title: Using Thinger.io Wifi together with HX711 library soft resets ESP8266 (NodeMCU)
I'm trying to get my NodeMCU v1.0 board to read from a load cell connected to a HX711 amplifier and send the data through Wifi to Thinger.io. I managed to make the readings from HX711, works perfectly. I also managed to send data to Thinger.io separately (ran the example without problems). However putting these together just doesn't work for me, the board soft resets:

```
[NETWORK] Starting connection...
[NETWORK] Connecting to network xxxxxxx

Soft WDT reset

ctx: cont
sp: 3fff0c60 end: 3fff0ec0 offset: 01b0

>>>stack>>>
3fff0e10:  4021e91f 00000001 3ffefe64 3ffefd48
3fff0e20:  3fff18dc 40203d38 3ffefe64 40203f0c
3fff0e30:  3ffe8e7f 3ffefcd8 3ffefe64 402023fc
3fff0e40:  3ffe8e81 00000015 3ffefe64 402051c0
3fff0e50:  00005173 3ffefcd8 3ffefe64 402051e4
3fff0e60:  3fffdad0 3ffefcd8 3ffefe64 3ffefe90
3fff0e70:  3fffdad0 00000001 3ffefcd8 402034b9
3fff0e80:  feefeffe 3ffefcd8 3ffefe88 40203768
3fff0e90:  3fffdad0 00000000 3ffefe88 402037e0
3fff0ea0:  feefeffe feefeffe feefeffe 40205824
3fff0eb0:  feefeffe feefeffe 3ffefea0 40100718
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

```

And if I wrap the thing.handle(); with

```
  ESP.wdtDisable();
  thing.handle();
  ESP.wdtEnable(0);

```

Then I get hard reset after few seconds.

This is minimal code where I reproduce the issue:

```
#define _DEBUG_

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

#define USERNAME "zink"
#define DEVICE_ID "xxxxxxxx"
#define DEVICE_CREDENTIAL "xxxxxxxxx"

#define SSID "xxxxx"
#define PASSWORD "xxxxxx"

ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

HX711 scale;

void setup() {
  // put your setup code here, to run once:
  thing.add_wifi(SSID, PASSWORD);
  scale.begin(D6, D5);
}

void loop() {
  // put your main code here, to run repeatedly:
  thing.handle();
}

```

While this sketch works perfectly:

```
#define _DEBUG_

#include <ESP8266WiFi.h>
#include <ThingerESP8266.h>

#define USERNAME "zink"
#define DEVICE_ID "xxxxxx"
#define DEVICE_CREDENTIAL "xxxxxxx"

#define SSID "xxxxxxx"
#define PASSWORD "xxxxxxx"

ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

void setup() {
  // put your setup code here, to run once:
  thing.add_wifi(SSID, PASSWORD);
}

void loop() {
  // put your main code here, to run repeatedly:
  thing.handle();
}

```

And also this one:

```
#include <HX711.h>

HX711 scale;

void setup() {
  // put your setup code here, to run once:
  scale.begin(D6, D5);
}

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

```

But combining them triggers a soft reset. What am I doing wrong here?

# Answer
> -1 votes
When an ESP resets its usually a segmentation fault. The first area I would look at is string manipulation, but you aren't doing any. So maybe reversing the order of:

```
thing.add_wifi(SSID, PASSWORD);
scale.begin(D6, D5);

```

might stop it, but it will only be temporary.

If it isn't you, and I can't see anything in your code that would cause it, then it must be the libraries. I think you will have to sit down and look at those two functions and see if you can see any string manipulation that might be causing it.

My money (£1) is on the `add_wifi` function and the cause being because it wants variables passing to it rather than `#defines`, but that's just a pure guess.

---
Tags: esp8266, wifi, nodemcu, reset
---


title: Sizeof variables and Due's RAM

text:
# Question
Title: Sizeof variables and Due's RAM
I set out to see how much space some arrays have. I used this test code

```
bool state = false;

uint16_t BuffA[46000];
uint16_t BuffB[20000];
uint16_t BuffC[20000];
uint16_t all = 0;

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

void loop(){
if (state==false){
Serial.println(sizeof(BuffA));
Serial.println(sizeof(BuffB));
Serial.println(sizeof(BuffC));
all = sizeof(BuffA) + sizeof(BuffB) + sizeof(BuffC)
Serial.println(all);
state = true;
  }
}

```

I got this answer from the serial:

```
92000
40000
40000
40928

```
1. Why are the results doubled from those i initiated? Shouldn't the first one be 46kb and the other two 20kb?
2. Why is the last value only 40928?
3. The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?
4. If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

# Answer
> 9 votes
`sizeof` doesn't return the number of elements. It returns the number of **bytes**. Since they are `uint16_t` arrays each element is 2 bytes - hence twice the size.

The reason your last number is only 40928 is because of integer wraparound. You only provide a 16-bit unsigned variable to store it in, so all you get is the lower 16 bits of the answer.

```
92000 + 40000 + 40000 = 172000

172000 in hex is 0x29FE0

0x29FE0 truncated to 16 bits is 0x9FE0

0x9FE0 in decimal is 40928.

```

> The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?

It would, but you aren't actually using the arrays for anything, so the compiler threw them away.

> If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

There are ways of interfacing the SAM3X with external RAM, but I don't thing the Due exposes all the signals you need. I would change to a chip with more RAM, such as the PIC32MZ with 512kB of RAM and 200MHz operation.

# Answer
> 4 votes
The `sizeof` operator's result is *number of bytes*, not number of array elements. Your arrays in the program above have two bytes per element, hence twice as many bytes as elements.

If you want to report the *number of elements*, divide the total size by the number of bytes per element. For example:

```
nElements = sizeof BuffA /  sizeof BuffA[0];

```

As `uint16_t` variables have 16 bits, the total `all` will exceed the maximum (65535) that `all` can hold. Consider using `uint32_t` type for that variable. For example:

```
uint32_t all = sizeof BuffA/sizeof BuffA[0] + sizeof BuffB/sizeof BuffB[0] + sizeof BuffC/sizeof BuffC[0];

```

Because the type of `sizeof` is `size_t`, a “type able to represent the size of any object in bytes”, one need not cast any of addends to `uint32_t` for the result to not overflow.

# Answer
> 1 votes
1. A variable of uint16\_t has 16 bits, thus two bytes, so for e.g. BuffA\[46000\] this means 46000 * 2 = 92000 bytes.
2. The variable all is also 16 bits and can contain only as max value 65,535. 92000 + 40000 + 40000 = 172000 bytes but that does not fit in 16 bits. Therefore the value is clipped ... make it a uint32\_t variable.
3. The total is 172.000 bytes, this mean it will not fit in 96KB. What are the value ranges you want to store? If the values are max 255
4. You can use extra RAM. DRAM is very hard to use, EEPROM is only usable when you don't have to write it too often. Otherwise use SRAM, e.g. the 23LC1024's which can store 128 KB RAM and are only DIP8.

---
Tags: arduino-due, array, variables, sram, sketch-size
---


# Question
Title: Fastest way to read an array of numbers from python
I'm trying to send an array of numbers from python to Arduino over the serial connection. I can reliably read a small incoming set of numbers (for example 123435678) from python, which I can then parse since I know how many digits are supposed to be in each number (for example, 1, 23456, 78). I do this with my Arduino code:

```
void getInput() {
     char buff[9];
     int field1;
     char field2[6];
     char field3[3];

  Serial.readBytes(buff, 8); //read 8 bytes from the Serial port
  buff[9] = '\0'; //null terminate the string we just read
  Serial.println(buff); //check that we got it
  for(int i=0; i<buff_len;i++) { //now we divide up the string into separate numbers
    if(i==0) {
      field1 = buff[0] - 48; //turn it into an int using ASCII
    }
    if(i>=1 && i<6) {
      field2[i-1] = buff[i];
      field2[5] = '\0';
    }
    if(i>=6) {
      field3[i-6]=buff[i];
      field3[2] = '\0';
    }
  }
  for(int i=0;i<buff_len;i++) { //clear the buffer
    buff[i]=0;
  }
}

```

But if I wanted to send a whole array whose contents I don't know in advance, for example like this:

```
for i in range(200):
    ser.write(i)

```

What's the best way to get these numbers to Arduino and file them away in an int array? Should I make the array in python first as a `numpy.linspace()` and send that?

# Answer
> 2 votes
If you don't know the length of the data then you need to be sending start and end markers so your other code can tell where the transmission starts and ends. I usually use \< and \>, so the data packet might look like \<12345678\>. You don't have to use those particular characters, just pick something that you know won't show up in your data.

---
Tags: serial, array, python
---


# Question
Title: How can the sensitivity of capacitive touch sensors be limited?
I have an Adafruit circuit playground classic, and the touch-pads are so very sensitive. From a centimeter away, they trigger. I would be happy to just have regular inputs, or to have the sensitivity reduced. How can I do this?

To clarify, here is my code:

```
//keyboard control for TuxKart power Glove
#include <Adafruit_CircuitPlayground.h>
#include <Keyboard.h>
#include <Mouse.h>
// set pin numbers for the five buttons:
const int Fire = 6;
const int Nitro = 9;
const int Eagle = 10;
const int _Esc = 12;

bool slideSwitch;

void setup() { // initialize the buttons' inputs:
  pinMode(Fire, INPUT_PULLUP);
  pinMode(Nitro, INPUT_PULLUP);
  pinMode(Eagle, INPUT_PULLUP);
  pinMode(_Esc, INPUT_PULLUP);

  Serial.begin(9600);
  // initialize mouse control:
  //Mouse.begin();
  Keyboard.begin();
}

void loop() {
  if (!CircuitPlayground.slideSwitch()) {
    return;
  }

  // use the pushbuttons to control the keyboard:
  if (!digitalRead(Fire) == HIGH) {
    Keyboard.write('KEY_SPACE');
    Serial.println("F");
  }
  if (!digitalRead(Nitro) == HIGH) {
    Keyboard.write('n');
    Serial.println("U");
  }
  if (!digitalRead(Eagle) == HIGH) {
    Keyboard.write(0xB2);
    Serial.println("N");
  }
  if (!digitalRead(_Esc) == HIGH) {
    Keyboard.write(0xB1);
    Serial.println("K");
  }
delay(200);
}

```

This code or any other, where capacitive touch sensitivity has not been specified, yields pins having extreme sensitivity. I have read the comments, that say the MCU doesn't feature this natively. If that were true, how would the pins remain sensitive?

My solution to this is to set sensitivity so low, that it is negligible. If capacitive touch sensing is not specified, why am I getting that functionality? Why would this code give me capacitive touch sensing? Ideally, I would disable the touch sensing somehow, or have the pins simply behave normally, like any other Arduino based device that doesn't have touch sense. But what I have guessed, (shown in code) doesn't work. If there is a more explicit way to specify that IO pins should act as normal pins, without capacitive touch sensing, I would surely like to know.

# Answer
`digitalRead(pin)` is the wrong way to read capacitive touch inputs.

In the file from the example you linked in your answer, the reading is made by calling `CircuitPlayground.readCap(pin, num_samples)` and then the returning value is compared to a threshold.

```
const uint16_t TOUCH_THRESHOLD = 300;

...

if (CircuitPlayground.readCap(Fire) >= TOUCH_THRESHOLD) {
   Keyboard.write(KEY_SPACE);
   Serial.println('F');
}
...

```

You can change the sensitivity by changing `TOUCH_THRESHOLD`. You could also add and fiddle with the second argument to change the number of samples.
> 1 votes

# Answer
Its not the best method for finding a solution, perhaps, but I was tooling around in the Adafruit\_CircuitPalyground repo, and found a macro for the Capacitive touch sensitivity.

The macro is:

```
#define CAP_THRESHOLD 300 // Threshold for a capacitive touch (higher = less sensitive).

```

Located here: https://github.com/adafruit/Adafruit\_CircuitPlayground/search?utf8=%E2%9C%93&q=CAP\_THRESHOLD&type=

I'm reading more, and trying to find the libraries for capacitive touch. There may be a much better solution, but for now defining CAP\_THRESHOLD works well enough.
> 0 votes

---
Tags: sensors, pins, adafruit, input
---


# Question
Title: Arduino Mega - I2C pins (20/21) unreliable
Has anybody else noticed that the Arduino Mega pins 20/21 are exceedingly unreliable over long periods of time? It has been the case four times now where I have hooked up no more than 3 I2C devices to these pins and had them fail after approx. 10 days of light use on average.

For example, my team and I had 3 sensors hooked up and were successfully running tests for about two weeks, then right before our launch, I2C stopped working entirely, returning completely incorrect (all zero) data every time.

Again, I have had this issue four separate times in the past, some where pull-up resistors are present, others not.

I seem to be unable to find related information on the web.

Has anyone else noticed this?

# Answer
The I2C pins on the Arduino Mega 2560 board are 100% reliable, but you have to use them correctly.

The Wire library could halt when something is wrong with the hardware I2C bus. In that case the sketch stops. The Wire library should have timeouts programmed in case something is wrong with the hardware, but sadly it doesn't have timeouts.

**Hardware**
The hardware I2C bus on the Arduino Mega 2560 board is a 5V I2C bus, because the Arduino Mega 2560 has 10k pullup resistors to 5V for SDA and SCL.
The wires for I2C can only be short. Long wires will not work.
The worst thing is when SDA and SCL are in a flat ribbon cable next to each other. The crosstalk between SDA and SCL will make the I2C very unreliable.
Because it is a 5V I2C bus, you may not connect 3.3V sensors to that 5V I2C bus. In that case you need a level converter.
The total value of all pullup resistors in parallel should not be too high (more sensitive for electrical noise, longer wires are not possible) and not be too low. The I2C specificiation is maximum 3 mA pulling of down current to get the signal low.
Everything that is connected to the I2C bus must have proper power supply. If one sensor has a power supply that fails, then that sensor will probably pull down the SCL and SDA signals.
A test with a breadboard might fail, due to bad contacts of the breadboard.

**Software**
The Arduino Wire library is often used in a wrong way.
If one of the sensors is an Arduino board as a I2C slave, then the code for the slave must be done right, because there are many ways to do it wrong.
You could check the return value of every Wire.endTransmissions for an error, and check every return value of Wire.requestFrom for the amount of data that is received.

If you tell us everything about the sensors, the wires (with photos), the logic level converters, the sketch, and so on, then we can tell you what the problem is.
> 2 votes

---
Tags: arduino-mega, i2c, communication
---


# Question
Title: How to get DHT11 temperature/humidity sensor to update on Arduino Uno
Trying to program a way to control my thermostat by interfacing it with my Arduino Uno. I am using a DHT11 to read temperatures and humidity. However, after making its first reading, it is not updating after that. I have included the reading in a loop that waits 2.5 seconds between readings to give the sensor time. However, its not updating. I tested the DHT11 with the example code that came with the DHT library and it is in itself functioning. To test it I have directed a warm hairdryer to the DHT sensor, but the readings dont change. However, when I reset it, the sensor will then show the higher reading initially but then wont update like before.

As well, the the photoresistor in the system will update its lux readings the whole time.

I have included the code below. Any help greatly appreciated! (sorry if the code is a bit messy, I am a novice programmer)

```
#include <LiquidCrystal.h>
#include <dht.h>

dht DHT;

#define DHT11_PIN 8
#define BOUNCE_DURATION 400
unsigned long checkLCD = 0;
volatile unsigned long bounceTime = 0;
unsigned long refreshBut = millis();
volatile int desiredTemp = 21;
boolean AC_on = true;
unsigned long checkBut = 0;
int temp = 0;
int humi = 0;
unsigned long lastTime = 0;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 10, 9);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  Serial.begin(9600);
  // Print a message to the LCD.
  lcd.print("DHT test");
  Serial.println("DHT TEST Type,\tstatus,\tHumidity (%),\tTemperature (C)");
  pinMode(3, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  pinMode(A1, INPUT_PULLUP);
  testDHT(); // testing DHT sensor

}

void loop() {
   if (millis() > lastTime)
  {
    temp = DHT.temperature;
    humi = DHT.humidity;
    lastTime = millis() + 2500;
    Serial.println(temp);
  }

  int luxSEND = -0.066433 * analogRead(A0) + 81.467234; //lux reading
  unsigned long refreshLCD = millis();
  int upBut = digitalRead(2); //up button
  int downBut = digitalRead(3); //down button
  int changeAC_send = digitalRead(A1);//read button for change between heating and AC
  unsigned long refreshBut = millis(); //for button for change between heating and AC

  displayReadings(humi, temp, luxSEND, refreshLCD, desiredTemp); //display on LCD - humidity, temperature, lux

  attachInterrupt(digitalPinToInterrupt(2), upButtonOn, FALLING);//Up in desired temp
  attachInterrupt(digitalPinToInterrupt(3), downButtonOn, FALLING);//Down in desired temp

  changeAC_on (changeAC_send, refreshBut); //change between heating and AC

  if ((temp > desiredTemp) && (AC_on == true)) { //AC structure
    digitalWrite(13, HIGH);

  }
  else if ((temp < desiredTemp) && (AC_on == false)) { //Heat Structure
    digitalWrite(13, HIGH);

  }
  else {
    digitalWrite(13, LOW);

  }
}

void displayReadings (int h, int t, int lux, unsigned long refreshL, int desiT) {
  if (refreshL >= (1000 + checkLCD)) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("T:");
    lcd.print(t);
    lcd.print("C  ");
    lcd.print("H:");
    lcd.print(h);
    lcd.print("%");
    Serial.print(h, 1);
    Serial.print(",\t");
    Serial.print(t, 1);
    Serial.print(",\t");
    lcd.setCursor(0, 1);
    lcd.print("L:");
    lcd.print(lux);
    lcd.print("   ");
    Serial.println(lux);
    Serial.print(",\t");
    lcd.print("Des.T:");
    lcd.print(desiT);
    lcd.print("C");
    checkLCD = refreshL;
  }

}

void testDHT () {
  // READ DATA
  lcd.clear();
  Serial.print("DHT11, \t");
  int chk = DHT.read11(DHT11_PIN);
  switch (chk)
  {
    case DHTLIB_OK:
      Serial.print("OK,\t");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.print("Checksum error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.print("Time out error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
    default:
      Serial.print("Unknown error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
  }
}

void upButtonOn () {
  if (millis() > bounceTime) {
    Serial.println("Up Pressed");
    desiredTemp = desiredTemp + 1;
    bounceTime = millis() + BOUNCE_DURATION;
  }
}

void downButtonOn () {
  if (millis() > bounceTime) {
    Serial.println("Down Pressed");
    desiredTemp = desiredTemp - 1;
    bounceTime = millis() + BOUNCE_DURATION;
  }

}

void changeAC_on (int changeAC, unsigned long refL) {
  if (refL >= (200 + checkBut)) {

    if ((changeAC == LOW) && (AC_on == true)) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("HEATING MODE");
      Serial.println("Heat On");
      AC_on = false;
      checkBut = refL;
    }

    else if ((changeAC == LOW) && (AC_on == false)) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("A/C MODE");
      Serial.println("AC On");
      AC_on = true;
      checkBut = refL;
    }
    else {
      checkBut = refL;
    }
  }
}

```

Additionally, here is a sample of the output from the serial monitor, while a hairdryer is being directed at it:

```
    DHT TEST Type,  status, Humidity (%),   Temperature (C)
DHT11,  OK, Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 52
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 51
,   40, 29, 52
,   Current read temperature is: 29
40, 29, 52
,   40, 29, 52
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54

```

# Answer
> 2 votes
DHT.read11 reads the temperature from the sensor. You call that once from setup function but not from the loop function. Therefor the DHT11 sensor is read just once during startup.

You should not use millis like that. The blink without delay example shows how to use millis.

---
Tags: arduino-uno, temperature-sensor
---


# Question
Title: for loop reads pots, passes value to PWM pins, can this be in the same for loop?
In the code below I am using a `for` loop to iterate over analog pins (potentiometers) and pass their value, after being mapped, to `PWM` enabled analog output pins (currently controlling LED brightness). While this works as is, I am curious about the following: would it be better to split the `analogRead` and `analogWrite` lines into separate `for` loops, or would that simply be redundant from a code standpoint? My concern is accidentally mixing up the pot values due to difficult-to-perceive timing issues.

The code:

```
static const uint8_t analog_pins[] = {A0, A1, A2, A3};
static const uint8_t digital_pins[] = {3, 5, 6, 9};
int pot_vals[] = {0, 0, 0, 0};
int val[] = {0, 0, 0, 0};

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

  // setup inputs, outputs
  for ( int i = 0; i < 4; i++ ) {
    pinMode( analog_pins[i], INPUT );
    pinMode( digital_pins[i], OUTPUT );
  }
}

void loop() {
  for (int i = 0; i < 4; i++) {
    val[i] = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map( val[i], 0, 1023, 0, 255 ));
  }
  delay(2);
}

```

# Answer
Having both the `analogRead()` and `analogWrite()` in the same loop is perfectly fine. That would be be my preferred choice if only for one reason: less RAM consumption. If you split them in two loops, you have to store somewhere the readings of the four channels, either before or after mapping. If you keep them in the same loop, you don't need the `pot_vals[]` nor `val[]` arrays. You would use a local variable instead, which consumes no RAM:

```
void loop() {
  for (int i = 0; i < 4; i++) {
    int val = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map(val, 0, 1023, 0, 255));
  }
  delay(2);
}

```

> My concern is accidentally mixing up the pot values due to difficult-to-perceive timing issues.

“Difficult to perceive”? I would call these issues “imaginary” instead. You have no risk of “mixing” any values here. Maybe, if you can elaborate on the kind of issues you imagine you could have, we could help you clear some misunderstanding about how the microcontroller executes your code.

---

**Edit**: To expand on Andrew's comment, the `for` loop can be optimized as

```
for (int i = 0; i < 4; i++) {
  unsigned int val = analogRead(analog_pins[i]);
  analogWrite(digital_pins[i], val / 4);
}

```

Dividing the value by 4 is the best way to map the input range to the output range. It gives a more uniform mapping than the `map()` call above, as every output value is mapped to exactly 4 input values. It could be noted, though, that `map(val, 0, 1024, 0, 256)` gives the same uniform mapping.

The division by 4, however, is optimized by the compiler into a bit shift, which is orders of magnitude faster than `map()`, and likely to consume less stack space. There is one caveat to be aware of: this optimization is only possible if `val` is unsigned. If it is signed, then it is compiled into a call to a division routine, which is quite expensive.

One could be tempted to go even further and get rid of the temporary `val` variable, like:

```
for (int i = 0; i < 4; i++) {
  analogWrite(digital_pins[i], (unsigned int) analogRead(analog_pins[i]) / 4);
}

```

However, there is zero benefit from doing so: from the point of view of an optimizing compiler, this form is exactly equivalent to the previous one. I prefer the former which I deem more readable.
> 3 votes

# Answer
Obviously you can. Except that in most cases your loop execution is much faster than your own period so that you end up changing the duty cycles multiple times in one period.

Not an advisable aporoach. If you have to do it think about configuring the pwm center aligned.
> 1 votes

---
Tags: pwm, analogread, analogwrite, performance
---


title: Are global variables evil in Arduino?

text:
# Question
Title: Are global variables evil in Arduino?
I'm relatively new at programming and many of the coding best practices I'm reading effectively state that there are very few good reasons to use a global variable (or that the best code has no globals at all).

I've done my best to keep this in mind, when writing software to make an Arduino interface with an SD card, talk to a computer and run a motor controller.

I currently have 46 globals for about 1100 lines of "beginner level," code (no line having more than one action). Is this a good ratio or should I look at reducing it more? Also what practices can I employ to reduce the number of globals further?

I'm asking this here because I'm specifically concerned with best practices for coding on Arduino products rather than computer programming in general.

# Answer
> 41 votes
They aren't *evil* per se, but they do tend to get overused where there is no good reason to use them.

There are plenty of times when global variables are advantageous. Especially since programming an Arduino is, under the hood, vastly different to programming a PC.

The biggest benefit to global variables is static allocation. Especially with large and complex variables such as class instances. Dynamic allocation (the use of `new` etc) is frowned upon due to lack of resources.

Also you don't get a single call tree like you do in a normal C program (single `main()` function calling other functions) - instead you effectively get two separate trees (`setup()` calling functions, then `loop()` calling functions), which means that sometimes global variables are the only way to achieve your goal (i.e., if you want to use it in both `setup()` and `loop()`).

So no, they're not evil, and on an Arduino they have more and better uses than on a PC.

# Answer
> 24 votes
It's very difficult to give a definitive answer without seeing your actual code.

Global variables are not evil, and they often make sense in an embedded environment where you typically do a lot of hardware access. You have only four UARTS, only one I2C port, etc. So it makes sense to use globals for variables tied to specific hardware resources. And indeed, the Arduino core library does that: `Serial`, `Serial1`, etc. are global variables. Also, a variable representing the global state of the program is typically a global.

> I currently have 46 globals for about 1100 lines of \[code\]. Is this a good ratio \[...\]

Is not about the numbers. The right question you should ask yourself is, for each of these globals, whether it makes sense to have it in global scope.

Still, 46 global seems a bit high to me. If some of these hold constant values, qualify them as `const`: the compiler will usually optimize out their storage. If any of those variables is only used inside a single function, make it local. If you want its value to persist between calls to the function, qualify it as `static`. You could also reduce the number of “visible” globals by grouping variables together inside an class, and having one global instance of this class. But only do so when it makes sense to put stuff together. Making a big `GlobalStuff` class for the sake of having only one global variable will not help make your code clearer.

# Answer
> 6 votes
The main issue with global variables is code maintenance. When reading a line of code, it is easy to find declaration of variables passed as parameter or declared locally. It is not so easy to find declaration of global variables (often it requires and IDE).

When you have many global variables (40 is already a lot), it becomes difficult to have an explicit name that is not too long. Using namespace is a way to clarify role of global variables.

A poor way to mimic namespaces in C is:

```
static struct {
    int motor1, motor2;
    bool sensor;
} arm;

```

On intel or arm processor, access to global variables is slower than other variables. It is probably the opposite on arduino.

# Answer
> 5 votes
As with everything (other than gotos which are truly evil) globals have their place.

e.g. If you have a debug serial port or a log file that you need be to able to write to from everywhere then it often makes sense to make it global. Similarly if you have some critical piece of system status information then making it global is often the easiest solution. There is no point in having a value that you have to pass to every single function in the program.

As others have said 46 seems a lot for only just over 1000 lines of code but without knowing the details of what you are doing it's hard to say if you are over using them or not.

However for every global ask yourself a few important questions:

Is the name clear and specific so that I don't accidentally try to use the same name somewhere else? If not change the name.

Does this need to ever change? If not then consider making it a const.

Does this need to be visible everywhere or is it only global so that the value is maintained between function calls? Is so consider making it local to the function and using the keyword static.

Will things really screw up badly if this gets changed by a piece of code when I'm not being careful? e.g. if you have two related variables, say name and ID number, that are global (see previous note on using global when you need some information almost everywhere) then if one of them gets changed without the other nasty things could happen. Yes you could just be careful but sometimes it's good to enforce carefulness a little. e.g put them in a different .c file and then define functions that set both of them at the same time and allow you to read them. You then only include the functions in the associated header file, that way the rest of your code can only access the variables through the defined functions and so can't mess things up. This is basically a pure c way of doing what a c++ class would allow but without having to learn how to define and create classes so you aren't learning too much at once.

-- update -- I just realized that you had asked about Arduino specific best practice rather than general coding and this is more of a general coding reply. But honestly there isn't much difference, good practice is good practice. The `startup()` and `loop()` structure of Arduino means that you have to use globals a little more than other platforms in some situations but that doesn't really change much, you always end up aiming for the best you can do within the limitations of the platform no matter what the platform is.

# Answer
> 5 votes
Although I wouldn't use them when programming for a PC, for the Arduino they have some benefits. Most if it has already been said:

* No dynamic memory usage (creating gaps in the limited heap space of an Arduino)
* Available everywhere, thus no need to pass them as arguments (which costs stack space)

Also, in some cases, especially performance-wise it can be good to use global variables, instead of creating elements when needed:

* To decrease gaps in heap space
* Dynamically allocating and/or freeing memory can take substantial time
* Variables can be 'reused', like a list of elements of a global list that are used for multiple reasons, e.g. once as a buffer for the SD, and later as a temporary string buffer.

# Answer
> 5 votes
Are they evil? Maybe. The problem with globals is that they may be accessed and modified at any point in time by any function or piece of code being executed, without restrictions. This may lead to situations that are, let's say, difficult to trace back and explain. Minimizing the amount of globals, if possible bringing the amount back to zero, is therefore desirable.

Can they be avoided? Almost always yes. The problem with Arduino is, that they force you into this two function approach in which they assume you `setup()` and you `loop()`. In this particular case you have no access to the scope of the caller function of these two functions (probably `main()`). If you had, you would be able to rid yourself of all globals and use locals instead.

Picture the following:

```
int main() {
  setup();

  while (true) {
    loop();
  }
  return 0;
}

```

This is probably more or less what the main function of an Arduino program looks like. Variables you need in both the `setup()` and the `loop()` function would then preferably be declared inside the scope of the `main()` function rather than the global scope. They could then be made accessible to the two other functions by means of passing them as arguments (using pointers if necessary).

For example:

```
int main() {
  int myVariable = 0;
  setup(&myVariable);

  while (true) {
    loop(&myVariable);
  }
  return 0;
}

```

Note that in this case you also need to change the signature of both functions.

As this might not be feasible nor desirable, I see really only one way to remove most globals from an Arduino program without modifying the forced upon program structure.

If I recall correctly, you're perfectly able to use C++ while programming for Arduino, rather than C. If you're not familiar (yet) with OOP (Object Oriented Programming) or C++, it might take some getting used to and some reading.

My proposal would be to create a Program class and create a single global instance of this class. A class should be considered the blueprint for objects.

Consider the following example program:

```
class Program {
public:
  Program();

  void setup();
  void loop();

private:
  int myFirstSampleVariable;
  int mySecondSampleVariable;
};

Program::Program() :
  myFirstSampleVariable(0),
  mySecondSampleVariable(0)
{

}

void Program::setup() {
  // your setup code goes here
}

void Program::loop() {
  // your loop code goes here
}

Program program; // your single global

void setup() {
  program.setup();
}

void loop() {
  program.loop();
}

```

Voilà, we've rid ourselves of almost all globals. The functions in which you would start adding your application logic would be the `Program::setup()` and `Program::loop()` functions. These functions have access to the instance specific member variables `myFirstSampleVariable` and `mySecondSampleVariable` whereas the traditional `setup()` and `loop()` functions do not have access as these variables have been marked class private. This concept is called data encapsulation or data hiding.

Teaching you OOP and/or C++ is a bit out of scope of the answer to this question so I'll stop here.

To summarize: globals should be avoided and it's almost always possible to drastically reduce the amount of globals. Also when you're programming for Arduino.

Most importantly I hope my answer is somewhat useful to you :)

# Answer
> 4 votes
Global variables are never *evil*. A general rule against them is just a crutch to let you survive long enough to gain the experience to make better decisions.

What a global variable is, is an inherent assumption that there is only one of a thing (it doesn't matter if we're talking about a global array or map that might contain multiple things, that still contains the assumption that there is only *one* such list or mapping, and not multiple independent ones).

So before you make use of a global, you want to ask yourself: is it conceivable that I will ever want to use more than one of this thing? If it turns out to be true down the line, you will have to modify the code to un-globalize that thing, and you'll probably find out along the way that other parts of your code depend on that assumption of uniqueness, so you'll have to fix them as well, and the process becomes tedious and error-prone. "Don't use globals" is taught because usually it's a pretty small cost to avoid globals from the beginning, and it avoids the potential of having to pay a large cost later on.

But the simplifying assumptions that globals allow also make your code smaller, faster, and use less memory, because it doesn't have to pass around a notion of which thing it's using, doesn't have to do indirection, doesn't have to consider the possibility of the desired thing maybe not existing, etc. On embedded you're more likely to be constrained for code size and/or CPU time and/or memory than you are on a PC, so these savings can matter. And many embedded applications also have more rigidity in the requirements — you *know* that your chip only has one of a certain peripheral, the user can't just plug another one into a USB port or something.

Another common reason for wanting more than one of something that seems unique is testing — testing the interaction between two components is easier when you can just pass a testing instance of some component to a function, whereas trying to modify the behavior of a global component is a trickier proposition. But testing in the embedded world tends to be very different from elsewhere, so this may not apply to you. As far as I know, Arduino has no test culture whatsoever.

So go ahead and use globals when they seem worthwhile. The code police won't come and get you. Just know that the wrong choice could lead to a lot more work for you down the road, so if you're not sure...

# Answer
> 0 votes
> Are Global Variables Evil in Arduino?

nothing is inherently evil, including global variables. I would characterize it as a "necessary evil" - it can make your life much easier but it should be approached with caution.

> Also what practices can I employ to reduce the number of globals further?

use wrapper functions to access your global variables. so you at least are managing it from the scope perspective.

---
Tags: arduino-mega, coding-standards
---


title: Controllino Debugging

text:
# Question
Title: Controllino Debugging
Its a well known fact, that you can debug your arduino board with the help of an Atmel Ice. However, you might know the Controllino which is an arduino compatible device.

It has an ATmega2560 on it.

Do you have an idea how to debug a controllino? I neither see any ICSP port nor did I found anything useful around this topic.

Any help is greatly appreciated!

# Answer
Connector X1 has the pins you want.

ICSP is shared with the SPI pins. Wire those to your ICE in the same way as you wire the SPI pins of the ICSP header on a normal Arduino to an ICE.
> 2 votes

---
Tags: debugging, atmega2560
---


title: Rotary encoder I2C LCD menu

text:
# Question
Title: Rotary encoder I2C LCD menu
I am trying to make a menu for a monitoring/control system. I am not sure how to make this without interrupting my current code which needs to be monitoring my system at all times to shut off if it reads overload. It is mostly `swtich ()` and `case x:` stuff. I have looked into attachInteruupt and rotary encoder examples, but none have really helped me figure out how to display a multiple layer menu where I can select to see the system readings as well as edit outputs.

There are a lot of posts here on rotary encoders with LCDs, but I can't seem to find a good skeleton menu code that works well and uses current libraries. My biggest problem right now is making the menu layers without interrupting my monitoring code running in the background.

# Answer
> 1 votes
you might want to consider timed routines or interrupts.

For timers https://playground.arduino.cc/Code/Timer1 or similar can help.

When using interrupts be sure to be minimalistic because atmegas do not behave well when interrupts take too long to process.

About menus there are several, most of them dynamic and some requiring user display + nav code.

This open-source menu lib (https://github.com/neu-rah/ArduinoMenu) is static, that is good for bigger projects because it stores a lot on flash.

* (-) you can not change menu at runtime (however it support value fields)
* (+) requires no user code base
* (-) setup involves several parts (inputs/output)
* (+) non blocking polled mode. Just call the poll function on your code loop, the menu will just return if it has no input or output
* (+) supports a lot of display devices, including i2c lcd
* (+) supports encoder (interrupts (PCINT) or timed driver)
* (-) atmega2560 interrupts (PCINT) only on 3 ports, PCINT might require pin mappings (not sure), but if needed the PCINT library examples can print one for you.

---
Tags: i2c, lcd, interrupt, rotary-encoder, atmega2560
---


# Question
Title: Trouble using a TSSP77038 with an Arduino
I have a Vishay TSSP77038 IR receiver that I would like to read the output of. It is connected as shown in the picture - Vs to 5V, GND to GND and the output to a pin on the Arduino.

My problem is that the reading is constantly low (it is active low so says it is receiving a IR signal), even when i completely cover the sensor or I am in a dark room. Can someone please tell help? Thanks a lot in advance :)

# Answer
> 1 votes
Gerben is correct it looks like you need a pull up resistor so that the pin is high unless the receiver drives it low.

I found this, which was the closest to useful information I found. Have a look at the proximity sensor section, it is similar to what you are using.

You'll want to know a value, I haven't got a clue. I use 4.7K for I2C pull ups. It's probably easier to start high (weaker) and work your way down, because if you put a 100K resistor in and the signal is low, then the resistor is too strong and you need a smaller one.

# Answer
> 0 votes
Because this part has an internal pull-up resistor, seeing the data line consistently low is most likely cause by one of:

* Reversed installation on the circuit board. This part can actually be installed in two orientations, with the lenses up or to the side, so there are more opportunities than usual to get the orientation of the contacts wrong.
* Electrical damage from past misuse
* A wiring problem, short, or additional device holding the data line low

---
Tags: arduino-uno, sensors, ir
---


# Question
Title: DHT11 is not reading Temperature and Humidity when Arduino is powered on using DC power Supply (12V)
I am facing one problem. I have code which read temperature and humidity using DHT11 sensor. I uploaded following code using Arduino via USB serial, I can read values of temp, humidity. Values are being read as long as Arduino is connected to same laptop via USB.

TEMPERATURE AND HUMIDITY are being read as 0 when I power on Arduino using DC12v, 700MA adapter.

I want to deploy Arduino with DHT sensors connected with it in Greenhouse to read greenhouse environmental condition but when I power on using DC adapter or battery, it is giving "0" output.

PLEASE HELP TO SOLVE THIS PROBLEM.

```
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

```

# Answer
> 1 votes
You haven't really provided enough information to answer. What are you reading the temperatures with. You code just assigns a variable to the readings but does not output that to anything.

I would suggest reading along with this tutorial, for example, and trying out the code they provide: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/

---
Tags: arduino-uno, temperature-sensor
---


title: time delayed LEDs

text:
# Question
Title: time delayed LEDs
I have two LEDs an I want the first one getting linear brighter and the second one do the exact same thing just one ore two seconds later. When one LED has reached 100, it should getting darker until there's no light and then start again from the beginning. I#m trying now for quite a long time but couldn't get it going.

```
int LED = 11;
int LED2 = 10;
void setup() {

Serial.begin(9600);
}
int x;
int x2;
void loop() {

for(x = 0; x<=100;x++)
{
while(x > 30)
{
for(x2 = 0; x2<=100;x2++)
{
analogWrite(LED2,x2);
delay(100);
}
}

analogWrite(LED,x);
delay(100);
Serial.println(x);

}
}

```

I just wanted to do the beginning but it isn't working. Can somebody pleas help me?

# Answer
Note: I think you will need to adjust the timings.

Hope this help:

```
int LED = 11;
int LED2 = 10;

unsigned long start;

int lum = 0;  // Light level LED
int step = 1;
int lum2 = 0; // Light level LED2
int step2 = 1;

void setup() {
  Serial.begin(9600);
  start = millis();
}

void loop() {
  unsigned long now = millis();

  if (now % 100 == 0) {
    // Every 100 ms, light goes up/down 1 notch.
    light(LED, &lum, &step);

    if (now - start > 2000) {
      //  Time to start with LED2
      light(LED2, &lum2, &step2);
    }
  }
}

/*
 * Light up/down one notch on a pin.
 */
void light(int pin, int* p_lum, int* p_step) {
  analogWrite(pin, *p_lum);
  *p_lum += *p_step;

  if (*p_lum == 100) {
    *p_step = -1;
  }
  if (*p_lum == 0) {
    *p_step = 1;
  }
}

```
> 1 votes

# Answer
Here is one way to do it.

1. Set up two output compare channels. They are identical except that they have slight different periods.
2. In their respective isr, flip the led

The next effect is that the duty cycle on the led goes from 0 to 100 and then 0 and then ....

The periods determine how long the 0 to 100 to 0 cycle is. The period differential determines how fast the led goes on and off.

You can do that to the other led, either in the same isr or through two other channels.
> 0 votes

---
Tags: led
---