# Question
Title: How do I connect a temperature and heartbeat sensor to an Arduino Uno?
I have been using a temperature sensor and heartbeat sensor separately and I am trying to code for temperature and heartbeat sensors. How do I get its output on the Arduino IDE's Serial Plotter?

Code of temperature sensor:

```
int val;
int tempPin = 1;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  val = analogRead(tempPin);
  float mv = ( val / 1024.0) * 5000;
  float cel = mv / 10;
  float farh = (cel * 9) / 5 + 32;

  Serial.print("TEMPRATURE = ");
  Serial.print(cel);
  Serial.print("*C");
  Serial.println();
  delay(1000);

  /* uncomment this to get temperature in farenhite
    Serial.print("TEMPRATURE = ");
    Serial.print(farh);
    Serial.print("*F");
    Serial.println();
  */
}

```

# Answer
> 1 votes
If you separate your code into functions you may understand what you want to do better.

In the listing above, you have code that reads the temp and prints the temp. So creating two functions `ReadTemp()` and `ShowTemp()` will make the code in loop look cleaner and easier to read. i.e.

```
void loop()
{
    const float cel = ReadTemp();
    DisplayTemp(cel);
    delay(1000);
}

float ReadTemp(void)
{
    val = analogRead(tempPin);
    float mv = ( val/1024.0)*5000;
    float cel = mv/10;
    // float farh = (cel*9)/5 + 32;
    return cel;
}
void ShowTemp(const float& cel)
{
    Serial.print("TEMPRATURE = ");
    Serial.print(cel);
    Serial.print("*C");
    Serial.println();
}

```

In you sketch for the hearbeat monitor you should have some code that reads the heartbeat and some that prints it. If you create two functions `ReadHB()` and `ShowHB()` you will be able to easily add them to the above loop function.

I've never used the serial plotter, but if you wrap it in a function called `PlotTemp()` and `PlotHB()` then you can slot them in instead of the Show functions.

---
Tags: arduino-uno, serial, sensors, temperature-sensor, code-review
---


# Question
Title: Emergency stop button for arduino mega code and circuit attached
I am trying to control steppers with pushbuttons and sensors.I want to add one more Pushbutton so that I can press it to stop the circuit and code running if something goes wrong in between. Below is the code I am using to run the steppers:

```
int dirpin_T1 = 26;
int dirH_T1 = 28;
int steppin_T1 = 30;
int dirpin_F1 = 5;
int dirH_F1 = 6;
int steppin_F1 = 7;

int PB17ACW = 23;
int PB17ACCW = 22;
int PB17BCW = 25;
int PB17BCCW = 24;

int S01 = 34; // SENSOR INPUTS
int S02 = 35;
int S03 = 36;
int S04 = 37;

void setup()
{
  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);
  pinMode(dirpin_F1, OUTPUT);
  pinMode(dirH_F1 , OUTPUT);
  pinMode(steppin_F1, OUTPUT);

  pinMode(PB17ACW, INPUT_PULLUP);
  pinMode(PB17ACCW, INPUT_PULLUP);
  pinMode(PB17BCW, INPUT_PULLUP);
  pinMode(PB17BCCW, INPUT_PULLUP);

  pinMode(S01, INPUT);
  pinMode(S02, INPUT);
  pinMode(S03, INPUT);
  pinMode(S04, INPUT);
}

void loop()
{
  if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == LOW)
  {
    // STOP MOTOR WHEN NO KEY PRESSED
  }

  // FOR FORWARD ROTATION
  if (digitalRead(PB17ACW) == HIGH &&  digitalRead(PB17ACCW) == LOW )
  {
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }

    digitalWrite(dirpin_F1, LOW );     // Set the direction.
    digitalWrite(dirH_F1, LOW);
    delay(1000);
    do
    {
      digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    } while (digitalRead(S01) == LOW);

    delay(1000);

    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, HIGH);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
  }

  // FOR  BACKWARD ROTATION
  if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == HIGH)
  {
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
    digitalWrite(dirpin_F1, LOW );     // Set the direction.
    digitalWrite(dirH_F1, HIGH);
    delay(1000);
    do
    {
      digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    } while (digitalRead(S02) == LOW);

    delay(1000);
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, HIGH);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
  }
//WANT CODE TO STOP CODE ANYTIME I PRESS STOP BUTTON

}

```

# Answer
The best option is to convert the `delay()` based code to a `millis()` based state machine. That way the code will never block and always be going through the loop and the place where you check wether that button was hit.

Then when that button is hit you transition to the E\_STOP state which turns off all motors until the restart button is hit which goes to recalibrate the position if needed.

---

A more quick and dirty solution is to replace every every delay with

```
unsigned long current = millis();
while(milis() - current < delay){
    if(E_Stop()){
        stopped = true;
        return;
    }
}

```

And add a if check to bail out to every loop.

```
 for (/*...*/)
  {
    //...
    delayMicroseconds(50);
    if(E_Stop()){
        stopped = true;
        return;
    }
  }

```

At the start of `loop()` you then add a

```
if(stopped){
    //check for restart signal if true recalibrate otherwise return
}

```
> 2 votes

---
Tags: arduino-mega, interrupt, code-review
---


# Question
Title: Arduino not adding decimals correctly on double variable
I have encountered a strange behavior today. I can't understand why the sequence is altered after 26.1000. I get a number 0.0001 less than the desired value (26.2124 instead of 26.2125). I need precision and can't get it.

Here is the code:

```
double _pos = 0;

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

void loop() {
  _pos += (0.1125);
  Serial.println(_pos,4);
  while (_pos >26.5) delay(1);
}

```

and here is the result

```
0.1125
0.2250
0.3375
0.4500
0.5625
0.6750
0.7875
0.9000
1.0125
1.1250
1.2375
1.3500
1.4625
1.5750
1.6875
1.8000
1.9125
2.0250
2.1375
2.2500
2.3625
2.4750
2.5875
2.7000
2.8125
2.9250
3.0375
3.1500
3.2625
3.3750
3.4875
3.6000
3.7125
3.8250
3.9375
4.0500
4.1625
4.2750
4.3875
4.5000
4.6125
4.7250
4.8375
4.9500
5.0625
5.1750
5.2875
5.4000
5.5125
5.6250
5.7375
5.8500
5.9625
6.0750
6.1875
6.3000
6.4125
6.5250
6.6375
6.7500
6.8625
6.9750
7.0875
7.2000
7.3125
7.4250
7.5375
7.6500
7.7625
7.8750
7.9875
8.1000
8.2125
8.3250
8.4375
8.5500
8.6625
8.7750
8.8875
9.0000
9.1125
9.2250
9.3375
9.4500
9.5625
9.6750
9.7875
9.9000
10.0125
10.1250
10.2375
10.3500
10.4625
10.5750
10.6875
10.8000
10.9125
11.0250
11.1375
11.2500
11.3625
11.4750
11.5875
11.7000
11.8125
11.9250
12.0375
12.1500
12.2625
12.3750
12.4875
12.6000
12.7125
12.8250
12.9375
13.0500
13.1625
13.2750
13.3875
13.5000
13.6125
13.7250
13.8375
13.9500
14.0625
14.1750
14.2875
14.4000
14.5125
14.6250
14.7375
14.8500
14.9625
15.0750
15.1875
15.3000
15.4125
15.5250
15.6375
15.7500
15.8625
15.9750
16.0875
16.2000
16.3125
16.4250
16.5375
16.6500
16.7625
16.8750
16.9875
17.1000
17.2125
17.3250
17.4375
17.5500
17.6625
17.7750
17.8875
18.0000
18.1125
18.2250
18.3375
18.4500
18.5625
18.6750
18.7875
18.9000
19.0125
19.1250
19.2375
19.3500
19.4625
19.5750
19.6875
19.8000
19.9125
20.0250
20.1375
20.2500
20.3625
20.4750
20.5875
20.7000
20.8125
20.9250
21.0375
21.1500
21.2625
21.3750
21.4875
21.6000
21.7125
21.8250
21.9375
22.0500
22.1625
22.2750
22.3875
22.5000
22.6125
22.7250
22.8375
22.9500
23.0625
23.1750
23.2875
23.4000
23.5125
23.6250
23.7375
23.8500
23.9625
24.0750
24.1875
24.3000
24.4125
24.5250
24.6375
24.7500
24.8625
24.9750
25.0875
25.2000
25.3125
25.4250
25.5375
25.6500
25.7625
25.8750
25.9875
26.1000
26.2124
26.3249
26.4374
26.5499

```

# Answer
> 0 votes
I do not see any specific difference after 26.2124.

However, in your case you are using 6 digits (e.g. 26.5499). To use an unsigned long/uint32\_t you can store easily 6 digits, but only using whole numbers.

However, by adding 1125 every time and dividing the result by 10,000.0 for printing you get exact results.

```
unsigned long _pos = 0;

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

void loop() {
  _pos += 1125;
  Serial.println((float) _pos / 10000.0,4);
  while (_pos > 265000) delay(1);
}

```

# Answer
> 3 votes
The 8 bit Arduinos don't have precision, or anything even close to precision when it comes to working with decimal values.

There is no such thing as `double` on an 8-bit Arduino - it is only an alias for `float`. By using `double` you aren't gaining any more precision than using `float`.

Even `double` isn't perfectly precise. It's more precise than `float` (on systems that support `double`), but still far from precise.

People that care about specific levels of precision code using variables of that precision. That's called using *fixed point* mathematics, and it's what DSPs work in. It's fast, efficient, and precise up to the point that *you* define it to be.

Fixed point mathematics works by operating in multiples of a pre-defined fraction. That fraction is your precision, or *granularity* and is the smallest value that can be represented. However, working with large numbers and fine granularity results in very large variables to store all that data - which is why for most things people use `float`: because it compresses the data down into a very small space - and like a highly compressed MP3 it loses a lot of the data.

# Answer
> 1 votes
The number 0.1125 would written in binary as 0.0001110011001100..., with an infinite repetition of “1100”. As the `float` data type has only 24 bits of precision, it can obviously not represent such a number. Instead, when you write `0.1125` in code, you get the closest representable number, namely 0.11249999701976776123046875, which is 0.00011100110011001100110011 in binary. Note that AVR-based Arduinos do not really support double precision: you get a float32 whether you declare a `float` or a `double`.

Furthermore, when you keep adding this number to itself, quite often the sum is not a representable number. Thus, in addition to the initial rounding error in the representation of 0.1125, you get an additional rounding error with the addition. These errors accumulate and you end up with a value that is significantly off what you expect.

You can avoid accumulating errors by working with integers, and converting o `float` only when needed:

```
void loop()
{
    static long count;
    count++;
    Serial.println(count * 0.1125, 4);
    while (count > 235) delay(1);
}

```

Note that you still get two rounding errors: in the representation of 0.1125 and in the multiplication. But at least you are not accumulating a large number of them.

# Answer
> 0 votes
> I can't understand why the sequence is altered after 26.2124.

because floats / doubles are not precise representation of their respective values.

---
Tags: programming, float
---


# Question
Title: SparkFun ESP8266 find out when on battery power and when charging
For one of my projects I use the SparkFun ESP8266 board with an additional LiPo battery in cases power supply goes down.

Now I would like to communicate the power loss - or the fact that the board is running on battery power via WiFi.

Is there a way to find out (in code) when the board switches from mains power to battery and back?

# Answer
> 1 votes
You can implement this software if the voltage is different in both cases.

The voltage from the power supply should be higher than the voltage of the battery, but do not exceed the permissible values.

Then you can use ESP.getVcc() :

> ESP.getVcc() may be used to measure supply voltage. ESP needs to reconfigure the ADC at startup in order for this feature to be available. Add the following line to the top of your sketch to use getVcc:
>
> `ADC_MODE(ADC_VCC);`
>
> TOUT pin has to be disconnected in this mode.
>
> Note that by default ADC is configured to read from TOUT pin using analogRead(A0), and ESP.getVCC() is not available.

---
Tags: esp8266, power, battery
---


# Question
Title: Turning a motor on and a led at the same time for a given time period
I need help with this code, I want to have a motor turn on for a given time and at the same time have an led light up to indicate it is on which will also turn of once the motor has stopped. It is controlled by A TECT5000 SENSOR, which acts like a switch to transfer a signal to the motor and LED.

At the moment, I can get the motor to turn on and off for a given time but not the LED. Every time I activate the circuit with the sensor it turns on and stays on or turns of and stays of. Here is the current code I am using.

```
// Program: Led drive using reflective optical sensor
// Author: Arduino e Cia

int outgoingsignal = 8 ; // Pin of led
int pinsensor = 7 ;   // Connected to the "collector" pin of the optical sensor
int reading;      // Stores information about sensor reading
int statusled = 0 ;
int motorPin = 9;  // define the pin the motor is connected to
                   // (if you use pin 9,10,11 or 3you can also control speed)
                   // Stores led status (on / off)

void setup ()
{
  pinMode (outgoingsignal, OUTPUT); // Defines the led pin as
  pinMode (pinsensor, INPUT);   // Defines the sensor pin as input
   pinMode(motorPin, OUTPUT);
}

void loop ()
{
  // Le the sensor pin information
  reading = digitalRead (pinsensor);
  if (reading != 1 ) // Checks if the object was detected
  {
    while (digitalRead (pinsensor)!= 1)
    {
     delay (100);
    }

    statusled =! statusled;
    // Reverses the status of the led (on / off)

    // Turns on or off the led as "statusled"
    digitalWrite (outgoingsignal, statusled);
  motorOnThenOffWithSpeed(); }

}
void motorOnThenOffWithSpeed(){

  int onSpeed = 255;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 0;  // a number between 0 (stopped) and 255 (full speed)
  //int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
 // delay(offTime);                   // waits for offTime milliseconds
}

```

# Answer
If you just want the led on with the motor then put a couple of digitalWrite statements in your motorOnThenOffWithSpeed function to turn the led on and off at the same time you turn the motor on and off.
> 1 votes

# Answer
Easy three steps:

1. Connect the led to the motor control pin (via some means to limit the current).
2. Program your motor control pin to turn it on or off as you so desire.
3. Sit back and enjoy.
> 1 votes

---
Tags: led, code-review
---


# Question
Title: SIM800L starts sending garbage values to Arduino after random interval
I have a SIM800L module connected to Arduino Mega's Serial3. SIM800L is powered by 4.2V power supply and I have put a voltage divider between Arduino's TX3 and SIM800L's RX so that the voltage in the line stays about 2V. The TX line of the module is directly connected to Arduino's RX3.

The problem is that when I try to communicate with the module it responds fine but after some AT commands the module starts panicking and start sending random garbage. The code I'm using is a simple Serial to Serial code :

```
#include<SoftwareSerial.h>

#define mySerial Serial3
//SoftwareSerial mySerial(10, 11);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  mySerial.begin(38400);

}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

```

Output :  \[This is with serial monitor set to 115200 baud rate\]

\[The garbage values with serial monitor set to 9600 baud rate\]

The solutions I have tried so far are :

1. Put a 220uF cap between SIM800L's VCC and GND. (a 470uF tantalum cap is already included on the module but still to be safe)
2. Tried various baud rates from 9600 to 115200 (the baud rate setting on the module is set to auto baud rate) but only 38400 works reliably.
3. Tried to pull the RX3 line up on Arduino with a 100k resistor so that it doesn't float.
4. Tried to put up to 5s delay between AT commands given to the module but it still goes into panic.

The thing I noticed is that if we enter some wrong command like ATD74xxxxxxxx (which calls a phone number) instead of with proper ending like ATD74xxxxxxxx; the module does the same thing which is spitting garbage values.

Can anybody help me with what is wrong with the module?

# Answer
I believe GSM modules needs about 2A current for few operations. One of them is calling. Are you providing proer current?
> 1 votes

---
Tags: serial
---


# Question
Title: Broken serial connection corrupting Arduino values
I have a problem with my homemade fan speed controller powered by an Arduino Nano, which reads a value from Serial (Arduino serial monitor, or Processing sketch) and uses the 0~255 value to set a variable `fanspeed1` to set a PWM pin to control the fan speed.

The problem is when I close the Processing sketch, or the Arduino serial monitor, `fanspeed1` is changed to max value (the fan speeds up to full speed).

I would like to send serial to set the value and then close the serial monitor, or Processing sketch and the value of `fanspeed1` should not change.

If I need to post some code I can simplify my sketch down to a send serial, receive serial, make pin pwm = serial(0~255), but I am guessing there is a simple solution to this unfindable with my googling.

Help please, these fans need controlling...

# Answer
You could consider writing/reading the value to/from the EEPROM.

http://arduino.cc/en/Reference/EEPROM

This allows the board to be reset, or even turned off, and retain the value previously set. What you would be doing is saving the value to the internal memory of the Arduino. This is resettable and persistent over a "reboot".

Granted, there is a limited number of writes you can do, but that number is high enough (~100k) that you will probably wear out the fan before the EEPROM sector dies.

> Syntax
>
> EEPROM.write(address, value)
>
> EEPROM.read(address)
>
> EEPROM.update(address, value)

For objects:

> EEPROM.put(address, data)
>
> EEPROM.get(address, data)
> 2 votes

---
Tags: communication, serial-data
---


title: Arduino an sparkfun microled problem

text:
# Question
Title: Arduino an sparkfun microled problem
In on of my projects i am using sparkfuns MicrOLED library. Downloaded it from github, installed as usual but no code calling that library compiles. Error is SPF\_MicrOLED.h no such file or directory.

It is strange as the library is installed, example sketches are in the examples menu but they don\`t want to compile ether, same error. Not sure what to do. Tried also to rename microled library folder but same error.

# Answer
> Error is SPF\_MicrOLED.h no such file or directory.

That is to be expected because the library doesn't contain a file named SPF\_MicrOLED.h.

It does contain a file named SFE\_MicroOLED.h. Use the correct filename in your `#include` and the problem will be solved.
> 2 votes

---
Tags: arduino-uno
---


title: Digital Inputs have gone crazy

text:
# Question
Title: Digital Inputs have gone crazy
My digital inputs are behaving as if they were floating, even though I've properly connected them with a resistor. I've tried the pull-down configuration pictured below, as well as a internal pull-up.

By using digitalRead() and serial.pintln() I've collected the state of each input tested (0 to 10) and they all do the same: random 0's and 1's. When I change a state (press or release the button), they seem to work for a second or two, then, they go crazy again. Sometimes, they even work backwards (showing HIGH when it's supposed to be LOW) for a couple of seconds.

Is my two-day old Arduino UNO fried?

# Answer
Solved it, but here is the solution, so there is an answer available for anyone who might encounter the same problem...

Quality check your protoboards. This is making me feel stupid. The protoboard I used had a faulty connection on the blue line I was using, causing an inevitable floating input. So relieved I found the problem, and yet so annoyed!

Take care you all.
> 3 votes

---
Tags: input, pull-up
---


title: Powering up LED strip - How many amps?

text:
# Question
Title: Powering up LED strip - How many amps?
I want my Arduino to drive a LED strip.
The LED strip in particular is the 3528 non-waterproof type.
To power this up, I need a 12V power supply.
My LED strip is going to be 5 meters.

Now my questions are:

1. Is it important on how many amps, my powers supply will feed? One guy did it with 12V, 5A power supply. Considering the length (5m), is a particular amperage value necessary?
2. Can I power up the Arduino Nano with the power from the power supply? Voltage wise, I am clear, since the nano can handle 12 volts... What I am scared of is the amperage... Considering that I need a particular value of amps to power up my LED strip, can the nano handle this many amps? Is there a limit to how many amps the power supply line that I will feed my Arduino has to be?

# Answer
> 8 votes
Usually strips have not individual LEDs, but are composed of a lot of "pieces" in parallel, and each piece is composed by three leds in series along with a resistor.

Usually the strips are composed by 60 leds/m (i.e. pieces of 5cm), but sometimes also 120 leds/m or 30 leds/m. Let's assume it is the 60 leds/m version (you can check the length of the piece you can cut - which should be 5 cm - and that it contains 3 leds).

This means that in 5m there are 100 pieces. Now, usually the 3528 leds absorb 20mA of current for each segment (the 5050 version should be rated at 60). This means that the whole led strip should absorb 2A @ 12V.

Now the power supply. 2A is the nominal current the whole strips should absorb. Add about 200mA for the nano, and increase a bit the current requirement not to stress the power supply: you get a 12V 3A power supply at least (note that, while 12V should remain the same, you can take any current greater than this value - if for instance you have a 12V 5A power supply it is perfectly fine).

Now, the nano. It surely can't handle the 2A current. This means that you can power the arduino nano from the 12V. BUT beware: you should connect the 12V power to the VIN input (so the onboard regulator lowers it to 5V). Then you can't power the LEDs directly from the nano, but you need a transistor to decouple them. You can take any nMOS with a drain current greater than 3A or an NPN with collector current \>3A and build the appropriate curcuit to drive them, then connect the + terminal of the strip to the +12V wire, the transistor source (or emitter) to the ground wire and the gate (base) should be driven by the nano.

# Answer
> 4 votes
> 1) Is it important on how many amps, my powers supply will feed?

Yes. You need the PSU to be able to supply as much current as you will need for everything you are powering form it.

You don't say how many LEDs will be on this strip (only the length of the strip) and I am not sure how much current/power a single one consumes, but **for illustration** let's imagine there are 100 LEDs on your strip and each one takes 0.8W.

100 LEDs x 0.8W per LED = 80W.

P = VI, where P=Power, V=voltage, I=current.

So I = P/V = 80 / 12 = 6.66A -- call it 7A.

The amount taken by the Nano will be small in comparison - if you said 0.5A you'd be safe.

So with these figures you'd need a 7.5A PSU.

> Considering that i need a particular value of amps to power up my LED strip, can the nano handle this many amps?

You can power the Arduino from the same power supply, yes. The Arduino will *draw* whatever current it needs. (Think of it this way: mains sockets are 13A - a desk lamp won't draw 13A.) What matters is that the supply can supply at least enough current, and that the voltage is correct.

As mentioned in the comments, you can't drive 3528s directly from the Nano - but you don't ask about that so presume you either know how to do it, or will ask another question.

# Answer
> 1 votes
Because there are three LEDs in series, you cannot drive these LEDs from a 5V supply. The LED strips say "+12V" on them to mark the anode and that's the maximum voltage we suggest. We've found that if you're ok with them being a little dimmer, even 9VDC works very well.

Each segment of 3 LEDs draws approximately 20 milliAmperes from a 12V supply, per string of LEDs. So for each segment, there is a maximum 20mA draw from the red LEDs, 20mA draw from the green and 20mA from the blue. If you have the LED strip on full white (all LEDs lit) that would be 60mA per segment.

To find the total maximum current draw per meter, we would multiply 60mA x 10 (ten segments per meter for the 30/LED per meter strip) = 0.6 Amps per meter OR 60mA x 20 (twenty segments per meter for the 60/LED per meter strip) = 1.2 Amps per meter. Again, that's assuming you would have all the LEDs on at once and that you are powering it from 12V. If you're going to be PWM-fading between colors, maybe 1/2 of that is what you'll be drawing. Still, you do need to have a fairly decent power supply to run this strip, all those LEDs add up!

---
Tags: power, led, arduino-nano, current
---


# Question
Title: How do I send tweets with flame sensor and ESP8266?
I want to send tweets with flame sensor and ESP8266. My flame sensor is digital. I think everything is good but it doesn't send.

This is my code:

```
#define ag_ismi "SSID"
#define ag_sifresi "PASSWORD"
#define IP "184.106.153.149" //thingspeak.com IP address

int sensorPin = 8;
int smoke_level = HIGH;

void setup() {
  pinMode(sensorPin, INPUT);
  Serial.begin(115200);
  Serial.println("AT");
  delay(3000);
  if (Serial.find("OK")) {
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String baglantiKomutu = String("AT+CWJAP=\"") + ag_ismi + "\",\"" + ag_sifresi + "\"";
    Serial.println(baglantiKomutu);
    delay(5000);
  }
}

void loop() {
  smoke_level = digitalRead(sensorPin); // Arduino reads the value from the smoke sensor
  Serial.println(smoke_level);// prints just for debugging purposes, to see what values the sensor is picking up
  if (smoke_level == HIGH) {
    // if smoke level is greater than 500, the buzzer will go off
    sicaklik_yolla();
  }
  delay(20000);
}
void sicaklik_yolla() {
  Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
  delay(1500);
  String tweet = "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n";
  tweet += "Host: api.thingspeak.com\n";
  tweet += "Connection: close\n";
  tweet += "Content-Type: application/x-www-form-urlencoded\n";
  tweet += "Content-Length:67\r\n\r\napi_key=";
  tweet += String("MY API KEY");
  tweet += String("&status=");
  tweet += String("MY TWEET TEXT");
  Serial.print("AT+CIPSEND=");
  delay(100);
  Serial.println(tweet.length());
  if (Serial.find(">")) {
    Serial.println(tweet);
    Serial.println("AT+CIPCLOSE=0");
    delay(100);
  } else {
    Serial.println("AT+CIPCLOSE=0");
  }
}

```

This schema is old. Sensor connected to pin 8.

# Answer
I guess your baud rate and network connection with the wifi module is working fine. Have to say that it is a bit difficult to get the data sent to ThingSpeak with ESP8266. I actually did some experiments to get the data sent. The problem is actually with the delay. Adding a delay of 5000 ms between sending the tweet length and the tweet content sorts it out. You can use GET format. Check out this Instructable.
> 1 votes

---
Tags: esp8266, communication, code-review, wireless, network
---


# Question
Title: ESP8266 - Parsing last char from a string
I'm trying to parse the last character from the string of the reply from server and print them to serial monitor.

My arduino code:

```
// This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");
  delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

```

My PHP page only shows the following though:

```
  Output: 1
  Watering: 1

```

I get the following output from my Serial Monitor:

```
  HTTP/1.1 200 OK
  Date: Fri, 28 Apr 2017 19:27:40 GMT
  Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/7.1.1
  X-Powered-By: PHP/7.1.1
  Content-Length: 9
  Connection: close
  Content-Type: text/html; charset=UTF-8

  Output: 1
  Watering: 1

```

I want to get the value of Output(In this case it's a 1), and Watering(Also a 1), etc...

Preferably store them in an int.

I tried using startsWith,endsWith,etc. but to no avail :(

# Answer
> -1 votes
I've converted the string to a char array and just checked if there is a 1 or a 0 at that region.

```
// Read all the lines of the reply from server and print them to Serial
String line;
int value=0;
while(client.available()){
  line += client.readStringUntil('\r');
}
//Serial.print(line);
char charBuffer[line.length()+1];
line.toCharArray(charBuffer, line.length()+1);
for(int i=207;i<line.length()+1;i++)
{
  if(charBuffer[i] == '1')
  {
    value = charBuffer[i];
  }
  if(charBuffer[i] == '0')
  {
    value = charBuffer[i];
  }
  Serial.print(charBuffer[i]);
  //delay(20);
}

```

# Answer
> 0 votes
If you have a String `s`, then `s.charAt(s.length() - 1)` give you that last char.

The function `length` gives you the number of chars in the string (not counting the '0' marker). The function `charAt` give you a single char at the position. The first char is at position 0.

For converting a single char digit `D` (0..9), you can use (`D` \- '0').

Demo:

```
void setup() {
  Serial.begin(9600);
  while(!Serial);
  String s = "Watering: 1";
  char last = s.charAt(s.length() - 1);
  Serial.println(last);
  int value = (int) (last - '0');
  Serial.println(value);
}

void loop() {
}

```

---
Tags: programming, esp8266, string, code-review, convert
---


title: Arduino Nano problems with ESP8266

text:
# Question
Title: Arduino Nano problems with ESP8266
this is my first post here because I'm a bit lost at the moment. I currently have my ESP8266-01 hocked up to the Nano like this:

The issue I'm having is that it won't even turn on, only when I'm using the 3.3V pin the red led on the ESP8266 turns on. If connected to 3.3V and I connect the CH\_PD pin to 3.3V aswell, the blue led flashes 2-3 times and then the ESP8266 turns off.

I hope someone is able to help me

# Answer
> 1 votes
You have a level shifter, not a voltage regulator. That's fine for switching logic levels of different voltages, but it cannot supply a regulated reduced voltage from one side to the other.

All it does is allow one voltage to switch another on and off in a bi-directional manner.

And those voltages have to come from somewhere for it to switch. You are already giving it the 5V from the Arduino, but you're not giving it the 3.3V for it to switch from anywhere - and so there is no 3.3V - not for the level shifter, nor for the ESP8266.

You need to find some way of getting 3.3V with enough current to power the ESP8266 side of the circuit.

# Answer
> 2 votes
You need to supply power to the ESP to make it turn on. What you have done at the moment is got the ESP to supply 3.3V to the level shifter, which you need to do.

You need to supply 3.3V to the ESP from somewhere other than the Arduino, it doesn't have the current necessary.

---
Tags: esp8266, arduino-nano
---


title: Clamping 9-volt input to 8-volt?

text:
# Question
Title: Clamping 9-volt input to 8-volt?
Have a DFRobot Arduino Pro Mini.

Seems odd to me, but according to their specs the voltage regulator on board cannot handle more than 8-volt input. I can find no documentation, or have they answered me concerning what specific regulator they use on the board.

I would like to be able to run this board from a 9-volt battery. What is the best / most eloquent way to do this, keeping the smallest component footprint for a home etched board ?

An additional regulator ?? Could a diode clamp the voltage down ?

Many thanks in advance.

# Answer
I would make sure first that their claim ofb8v max is right. Look up the datasheet for the regulator and go from there.

If you have to go with 8v max, put a diode or two, or an led in serial should work most of the time.

For those where such an approach doesn't work, wire up an external regulator.
> 1 votes

---
Tags: arduino-mini
---


# Question
Title: esp8266 not defined in scope while using in class
Below code was working fine without using classes, after using class an error pops up: esp8266 is not defined in this scope

```
#include<SoftwareSerial.h>
#include<ArduinoJson.h>
#include<Wire.h>
#include<LCD.h>
#include<LiquidCrystal_I2C.h>
#include<SPI.h>

#define DEBUG true
// Housekeeping stuff for LCD display
#define I2C_ADDR    0x3F
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7
LiquidCrystal_I2C
lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

class baseFunctions {
  public:
    baseFunctions() {
      Serial.begin(115200); // Housekeeping stuff
      esp8266.begin(115200);  // Housekeeping stuff
      sendData("AT+RST\r\n", 2000, DEBUG); // reset module

      // Code for display
      lcd.begin (16, 2);
      lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
      lcd.setBacklight(HIGH); // Switch on the backlight
      lcd.home (); // go home
      lcd.print("In development");

      pinMode(8, OUTPUT);
    }

    String sendData(String command, const int timeout, boolean debug) {
      String response = "";
      esp8266.print(command); // send the read characte to esp8266
      long int time = millis();
      while ( (time + timeout) > millis() ) {
        while (esp8266.available()) {
          // The esp has data so display its output to serial window
          char c = esp8266.read(); // read the next character
          response += c;
        }
      }
      if (debug) {
        Serial.print(response);
      }
      return response;
    }

    void connectToWifi() {
      sendData("AT+CWMODE=1\r\n", 3000, DEBUG); // Configure as clint
      sendData("AT+CWJAP=\"moto g\", \"hvats555\"\r\n", 5000, DEBUG);  // Connects to wifi
    }

    String fetchJson() {
      StaticJsonBuffer<200> jsonBuffer;
      char json[] = "{\"power\":\"high\"}";
      JsonObject& root = jsonBuffer.parseObject(json);

      const char* power = root["power"];
      return power;
    }
};

void setup() {
  baseFunctions go;
}

void loop() {
}

```

Here is the error

```
exit status 1
'esp8266' was not declared in this scope

```

# Answer
When you added the class you obviously deleted/moved code into it from elsewhere.

One bit of code that you missed in that moving around will be the code that declares what `esp8266` is:

```
SoftwareSerial esp8266(2,3); // for example

```

Find that in your original code and copy it across.
> 2 votes

---
Tags: esp8266, c++, code-review, iot
---


# Question
Title: Arduino uno with microled library; draw shaped
I am really sorry for bothering you but i need help, again, with my arduino code. I am still learning so i make mistakes.

I am trying to draw shaped on i2c screen with Microled library. My code isn\`t compiling, error is Unexpected declaration before { . That is one problem. I would also like to draw rectangle without edges, both empty and filled but i am struggling how to declare it, should i declare 4 lines or maybe display bitmap.

Anyway my code is here

```
#include <Arduino.h>
#include <Wire.h>
#include <MicroLCD.h>

LCD_SH1106 lcd; /* for SH1106 OLED module */
//LCD_SSD1306 lcd; /* for SSD1306 OLED module */

static const PROGMEM uint8_t smile[48 * 48 / 8] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xC0,0xE0,0xF0,0xF8,0xF8,0xFC,0xFC,0xFE,0xFE,0x7E,0x7F,0x7F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x7F,0x7F,0x7E,0xFE,0xFE,0xFC,0xFC,0xF8,0xF8,0xF0,0xE0,0xC0,0x80,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xC0,0xF0,0xFC,0xFE,0xFF,0xFF,0xFF,0x3F,0x1F,0x0F,0x07,0x03,0x01,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x01,0x03,0x07,0x0F,0x1F,0x3F,0xFF,0xFF,0xFF,0xFE,0xFC,0xF0,0xC0,0x00,
0xFE,0xFF,0xFF,0xFF,0xFF,0xFF,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x1F,0x1F,0x1F,0x3F,0x1F,0x1F,0x02,0x00,0x00,0x00,0x00,0x06,0x1F,0x1F,0x1F,0x3F,0x1F,0x1F,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xE0,0x00,0x00,0x30,0xF8,0xF8,0xF8,0xF8,0xE0,0xC0,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xC0,0xE0,0xF8,0xF8,0xFC,0xF8,0x30,0x00,0x00,0xE0,0xFF,0xFF,0xFF,0xFF,0xFF,0x7F,
0x00,0x03,0x0F,0x3F,0x7F,0xFF,0xFF,0xFF,0xFC,0xF8,0xF0,0xE1,0xC7,0x87,0x0F,0x1F,0x3F,0x3F,0x3E,0x7E,0x7C,0x7C,0x7C,0x78,0x78,0x7C,0x7C,0x7C,0x7E,0x3E,0x3F,0x3F,0x1F,0x0F,0x87,0xC7,0xE1,0xF0,0xF8,0xFC,0xFF,0xFF,0xFF,0x7F,0x3F,0x0F,0x03,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x03,0x07,0x0F,0x1F,0x1F,0x3F,0x3F,0x7F,0x7F,0x7E,0xFE,0xFE,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFE,0xFE,0x7E,0x7F,0x7F,0x3F,0x3F,0x1F,0x1F,0x0F,0x07,0x03,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
};

static const PROGMEM uint8_t tick[16 * 16 / 8] =
{0x00,0x80,0xC0,0xE0,0xC0,0x80,0x00,0x80,0xC0,0xE0,0xF0,0xF8,0xFC,0x78,0x30,0x00,0x00,0x01,0x03,0x07,0x0F,0x1F,0x1F,0x1F,0x0F,0x07,0x03,0x01,0x00,0x00,0x00,0x00};

static const PROGMEM uint8_t cross[16 * 16 / 8] =
{0x00,0x0C,0x1C,0x3C,0x78,0xF0,0xE0,0xC0,0xE0,0xF0,0x78,0x3C,0x1C,0x0C,0x00,0x00,0x00,0x30,0x38,0x3C,0x1E,0x0F,0x07,0x03,0x07,0x0F,0x1E,0x3C,0x38,0x30,0x00,0x00};

void setup()
{
  delay(1000);
  delay(1000);
  lcd.clear();
  lcd.setCursor(40, 1);
  delay(500);
}

void line()
{
int x0 = 7; int y0 = 7;   // (x0,y0) = (7, 7)
int x1 = 42; int y1 = 24; // (x1,y1) = (42, 24)
oled.line(x0, y0, x1, y1);  // Draw a line from (x0,y0) to (x1,y1);
oled.display(); // Draw to the screen
}

void rectangle()
{
int x0 = 7; int y0 = 5;
int width = 24;
int height = 13;
oled.rect(x0, y0, width, height);
oled.display();
}

void filled()
{
oled.rectFill(7, 5, 35, 5); // Fill a rectangle from (7, 5) to (42, 10)
int radius = 13;
}

void circle()
oled.circle(LCDWIDTH/2, LCDHEIGHT/2, radius);
oled.display(); // Draw to the screen

oled.circleFill(42, 20, 7); // Fill a circle, 7 radius, centered at (42, 20)
oled.display(); // Draw to the screen
}

void loop()
{
  line();
  rectangle();
  filled();
  circle();
}
void printTitle(String title, int font)
{
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;

  oled.clear(PAGE);
  oled.setFontType(font);
  oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
                 middleY - (oled.getFontWidth() / 2));
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
}

```

---

Full error is this

```
Arduino: 1.8.6 (Linux), Board: "Arduino/Genuino Uno"

In file included from /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino:3:0:
/home/lutherus/builds/Arduino/build/linux/work/libraries/MicroLCD/MicroLCD.h:38:43: warning: '__progmem__' attribute ignored [-Wattributes]
     virtual void draw(const PROGMEM byte* buffer, byte width, byte height) {}
                                           ^
In file included from /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino:3:0:
/home/lutherus/builds/Arduino/build/linux/work/libraries/MicroLCD/MicroLCD.h:67:35: warning: '__progmem__' attribute ignored [-Wattributes]
     void draw(const PROGMEM byte* buffer, byte width, byte height);
                                   ^
/home/lutherus/builds/Arduino/build/linux/work/libraries/MicroLCD/MicroLCD.h:84:35: warning: '__progmem__' attribute ignored [-Wattributes]
     void draw(const PROGMEM byte* buffer, byte width, byte height);
                                   ^
/home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: In function 'void line()':
sketch_nov14a:39: error: 'oled' was not declared in this scope
 oled.line(x0, y0, x1, y1);  // Draw a line from (x0,y0) to (x1,y1);
 ^
/home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: In function 'void rectangle()':
sketch_nov14a:48: error: 'oled' was not declared in this scope
 oled.rect(x0, y0, width, height);  // Draw a rectange from (7,5) to (31,18)
 ^
/home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: In function 'void filled()':
sketch_nov14a:54: error: 'oled' was not declared in this scope
 oled.rectFill(7, 5, 35, 5); // Fill a rectangle from (7, 5) to (42, 10)
 ^
/home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: At global scope:
sketch_nov14a:61: error: expected initializer before 'oled'
 oled.circle(LCDWIDTH/2, LCDHEIGHT/2, radius);
 ^
sketch_nov14a:62: error: 'oled' does not name a type
 oled.display(); // Draw to the screen
 ^
sketch_nov14a:64: error: 'oled' does not name a type
 oled.circleFill(42, 20, 7); // Fill a circle, 7 radius, centered at (42, 20)
 ^
sketch_nov14a:65: error: 'oled' does not name a type
 oled.display(); // Draw to the screen
 ^
sketch_nov14a:67: error: expected declaration before '}' token
 }
 ^
exit status 1
'oled' was not declared in this scope

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

```

# Answer
> 0 votes
I notice that the circle function is missing an opening brace. Not sure if that's the one that caused the error you see now but it definitely needs to be fixed.

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


# Question
Title: Infra Red sketch "not declared in this scope"
I'm pretty new at Arduino and I'm trying to upload a sketch with IR sensor to control LED-s. I copy the code from internet,download library,I put my infrared codes for TV remote where I want and it says:"not declared in this scope"

Code and error:

```
#include <IRremote.h>

const int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
const int redPin = 6;
const int greenPin = 9;

void setup(){
  irrecv.enableIRIn();
  irrecv.blink13(true);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
}

void loop(){
    if (irrecv.decode(&results)){

        switch(results.value){
          case E0E036C9: //Keypad button "5"
          digitalWrite(redPin, HIGH);
          delay(2000);
          digitalWrite(redPin, LOW);
          }

        switch(results.value){
          case E0E028D7: //Keypad button "2"
          digitalWrite(greenPin, HIGH);
          delay(2000);
          digitalWrite(greenPin, LOW);
          }

        irrecv.resume();
    }
}

```

Error:

```
C:\Users\Kandzija\Desktop\saneta\saneta.ino: In function 'void loop()':
saneta:21: error: 'E0E036C9' was not declared in this scope
           case E0E036C9: //Keypad button "5"
                ^
saneta:28: error: 'E0E028D7' was not declared in this scope
           case E0E028D7: //Keypad button "2"
                ^
exit status 1
'E0E036C9' was not declared in this scope

```

Can you help me guys pls? Thank You!

# Answer
Numeric values in HEX need to be prefixed with `0x`:

```
case 0xE0E036C9: //Keypad button "5"

```

and

```
case 0xE0E028D7: //Keypad button "2"

```
> 2 votes

---
Tags: arduino-uno, code-review
---


title: Using a button to toggle an LED ON/OFF

text:
# Question
Title: Using a button to toggle an LED ON/OFF
I'm fairly new to Arduino and am trying to use a push button to toggle an LED on and off using a momentary press of the button. This code is lifted straight off the tutorial on the Arduino website but is not working for me. It seems to send the LED on a loop - switching between on and off by itself, and pressing the button pauses the cycle.

Any ideas as to why it is doing that?

```
int buttonPin = 2;         // the number of the input pin
int ledPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);

}

void loop()
{

  reading = digitalRead(buttonPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
if (reading == HIGH  && previous == LOW && millis() - time > debounce) {
  if (state == HIGH)
    state = LOW;
  else
    state = HIGH;
time = millis();
}

else
  if (state == LOW)
    state = LOW;
  else
    state = HIGH;
  digitalWrite(ledPin, state);
 //Serial.println(buttonPin);
  //
 Serial.println(reading);
previous = reading;
}

```

# Answer
> 4 votes
I tested your sketch and it works. I simplified it; it's the same logic, but in a more concise way:

```
void loop()
{
    reading = digitalRead(buttonPin);

    // if the input just went from LOW and HIGH and we've waited long enough
    // to ignore any noise on the circuit, toggle the output pin and remember
    // the time
    if(reading == HIGH  && previous == LOW && millis() - time > debounce) {
        state = !state;
        time = millis();
    }

    digitalWrite(ledPin, state);
    Serial.println(reading);
    previous = reading;
}

```

`setup` is still the same.

# Answer
> 1 votes
```
pinMode(buttonPin, INPUT);

```

Do you have an external pull-down resistor? Without one, the pin is floating when the button isn't pressed so it might read anything and you may be picking up spurious noise.

It is much more common to wire a button so that it connects to ground and reads LOW when pressed. If you wire it that way, you can use the internal pull-up resistors by using pinMode(pin, INPUT\_PULLUP) and you won't need any external resistor for the button.

# Answer
> 0 votes
The problem is in the "else" part. Just remove it and you are ready to go ! Also make sure that in the circuit, the digital read would be low, when not pressing button.

# Answer
> 0 votes
My one line answer

If (isPressed(BTN)) digitalWrite(LED, ~digitalRead(LED));

Is all you need to flip an led when a button is pressed.

---
Tags: arduino-uno, led, code-review
---


# Question
Title: Is it possible to query (or otherwise detect) if Arduino is connected to 60 NeoPixel strip vs 144 strip?
Is there any way to have an arduino detect how many LEDs are on a connected strip? I have a 60 strip and 144 strip. The code is identical for both, aside from setting the number of LEDs in a variable to iterate over.

# Answer
Neopixels only have one-way communication. Some possible ways to detect the quantity are:

1. Bring the Data-Out of the last pixel back to the arduino and activate an interrupt on an input pin connected to that. If you write 144 LEDs worth of data to the 144-LED strip, the pin doesn't change. If you write 144 LEDs worth to a 60-LED strip, the pin changes. So your code has a startup routine to write data and detect it. You can even write all "black" colors, since the data will still have HIGH and LOW values, and your detect routine won't show any light patterns.
2. Pass the ground line that goes to the LED strip through a low-value resistor (A current-sense resistor) and use an analog input to read the voltage across the resistor. Write an all-white color to all NeoPixels and sense the current draw. Pre-calculate the 144-LED current draw and 60-LED current draw and set a cutoff value for knowing which strip is connected.
3. Make your LED-strip connector to have more pins than necessary strictly for the LED strip connections. For example, have 1 extra pin. On the 144-LED strip side of the connector, tie this connection to the 5V line. On the 60-LED strip, connect it to GND. Read HIGH or LOW on an extra digital input on your arduino.
> 5 votes

# Answer
Not without effort. You could take the DOUT from the last LED, feed it back into the MCU, and then detect how long it takes to get some sort of signal from it, but this requires either the end of the chain being very close to the MCU or a long wire to connect them. Easier to just have a DIP switch to set the number of Pixels in the chain and go from there.
> 2 votes

# Answer
Also see Is it possible to infer the length of a neopixel string using 1-wire protocol?. For example, one of Nick Gammon's answers includes code that detects NeoPixel string length via a binary search; Craig's answer refers to a Bunnie Huang blog with code and a library to detect lengths; and my answer includes datasheet links and quotes, and points out that if you put *m* packets of data into a chain and *k* packets come out the last unit, the chain length is *m-k* or more, using which fact can markedly speed up length detection. (All of these methods depend on reading data that flows out of the last unit of the chain; some of them use interrupts, some don't.)
> 2 votes

---
Tags: neopixel
---


# Question
Title: Need help to find code error to send AT command response in sms
I know that there is something wrong in my code bellow because I don't get "OK" as response in the SMS when I use Serial.print ("AT") . "AT" is an AT command. I am using the example 2 of http://forum.arduino.cc/index.php?topic=396450.0

I tested the code bellow on the serial monitor and I am able to see the response of the AT commands on the serial monitor with Debug.println(receivedChars);. However, I am unable to receive the command's response in the SMS and would like to know what is wrong in this procedure. When I upload this code bellow, I only see "AT" in the SMS without the "OK". I think that SW\_Serial.print(receivedChars); should show give OK in the SMS but I don't see it.Do you kmow why?

# Answer
> 1 votes
You are making the mistake of hoping the serial response will come very quickly. You are checking for serial available, which is good, but the function PrintModemResponse gives up once no serial is available. This is quite likely to be before all of the data has arrived. Imagine you are listening to me talking, and you assume that if there is a brief pause (as I take a breath) that my sentence is over. You are better off reading until you get a definite "end marker" like a newline.

I notice you are doing something like that in recvWithEndMarker.

You may find my page about how to process incoming serial data without blocking helpful. Example code from that page:

```
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

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

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

  }  // end of loop

```

---
Tags: programming, code-review
---


# Question
Title: How to power up this LCD 7 segments display
I got two of these type of 7 segments display in LCD material.

And here is the datasheet

I tried to power up to UNO, it can make the segment on, while a second, the segment go off, but the pinMode does not changed.

# Answer
Driving an LCD display is nothing like driving an LED display. You need to provide an alternating current to the right segments at the right time.

It is possible with an Arduino on a simple display like this, but not easy. Better is to use a chip that has a proper LCD display interface, such as the MSP430 "F" series (the FRAM ones).

To do it on an Arduino you need to treat it like a common anode matrix on one pass, and a common cathode matrix on the next pass, and do that repeatedly and rapidly.

That is, set COM1 HIGH and the other COMx pins LOW, and the segments you want on LOW and the others HIGH, then do the same with COM2, etc. Then go back to the start and invert the logic, so set COM1 LOW and the other COMx HIGH, and your chosen segments HIGH.

It is best to do this from within a timer interrupt so that you can get good regular updates without your program causing delays.
> 1 votes

# Answer
that's a controller-less dynamic (mutiplexed) display, with 4 coms.

So you will to program the mcu to do a lot:

1) the com pins are driven with 1/4 dc signal sequentially;

2) the seg pins are driven with 1/3 bias voltage. out-of-phase to be dark and in-phase to be transparent (not lit).

the way to do it is to:

1. put segment info in a buffer;
2. write a display update routine that scans digits and updates the com/seg pins according to the current digit's segment information;
3. call that display update routine periodically, preferrably from a timer isr.

the display update routine would be similar to an led display routine - an example of that (for led) would be here (https://dannyelectronics.wordpress.com/2017/06/30/a-more-flexible-driver-for-7-segment-leds/), but more complex due to the 4 com pins and bias generation.

it is much easier to pick a mcu with built-in lcd driver and program that mcu as a display controller / slave taking in information from a master (in this case your arduino).
> 1 votes

---
Tags: arduino-uno, 7-segment
---


title: Make 3 servos move like a wave

text:
# Question
Title: Make 3 servos move like a wave
I am having some trouble programming 3 servos to move like a wave. So, for instance, all my servos start at 90 degrees. I want my first servo to move and when it reaches 135 degrees I want my second servo to move, with the first, then when it reaches 135 degrees I want my third servo to move, with the first and the second. Then go backwards. Does that make sense?

Here is what I have so far.

```
#include <Servo.h>

//Create servo object to control a servo
Servo left;
Servo middle;
Servo right;

//Variables to store the servo position
int post = 180;
int post2 = 90;
int back = 90;
int forward = 135;

int firstTriggerAngle = 135;
int secondTriggerAngle = 180;

//Delay
int mid = 4;

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

  //Attaches the servos on the pins of the arduino to the servo object
  left.attach(4);
  middle.attach(3);
  right.attach(2);

  //Starting position
  left.write(back);
  middle.write(back);
  right.write(back);
}

void loop()
{
  for (int i=back; i>=forward; i+=1)
  {
    left.write(i);
    if( i > firstTriggerAngle)
    {
      post = map(i, 90, 135, 135, 90);
      middle.write(post);
    }
    if(post > secondTriggerAngle)
    {
      post2 = map(post, 90, 135, 135, 90);  // depends on the angles you use
      right.write(post2);
    }
    delay(mid);
 }
}

```

# Answer
> 1 votes
The easiest way is to define how many degrees you want to move totally .

In your case it is 180 steps (from 90 to 180, which is 90 steps, and 180 to 90, which is another 90 steps).

Than use a for loop with a 180 step-counter and make 3 simple formulas to map the 180 possible degrees to the wanted servo position.

So the first formula will look like (step 0..90 -\> move from 90 to 180, step 90..180-\> move 180 to 0).

```
int calcServo1(int step)
{
    if (step < 90)
    {
        return 90 + step;
    }
    else
    {
        return 270 - step; // 180 - (step - 90);
    }
}

```

For the second it should be:

* step is 0..45: first iteration: 90, otherwise 135..90
* step is 45..135: 90..180
* step is 135..180: 180..135

The code will be something like:

```
int calcServoPos2(int iteration, int step)
{
    if (step < 45)
    {
        if (iteration == 0)
        {
            return 90;
        }
        else
        {
            return 135 - step;
        }
   else if (step < 135)
   {
         return step + 45;
   }
   else
   {
       return step - 45; //  step - 180 + 135
   }
}

```

Servo 3 I will leave up to you.

From your main loop you call the positions:

```
 int iteration = 0;

 while (loop)
 {
      for (int step = 0; step < 180; step++)
      {
         int servo1pos = CalcServo1(iteration, step);
         servo1.write(servo1pos);

         int servo2pos = CalcServo2(iteration, step);
         servo2.write(servo2pos);

         int servo3pos = CalcServo2(iteration, step);
         servo3.write(servo3pos);

         delay(mid);
     }
     iteration++;
  }

```

---
Tags: arduino-mega, code-review
---


title: Ultrassonic sensor

text:
# Question
Title: Ultrassonic sensor
Hi I have this ultrasonic sensor:

http://www.micropik.com/PDF/HCSR04.pdf

I use this code to read distances:

```
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long time = pulseIn(echoPin,HIGH);

```

My question is this: in the datasheet says that the sensor will send 8 pulses at 40khz. Every pulse will take 0.000025 seconds so 8 pulses would be 200 usec.

So why the delay is only 10 usec if it should be 200usec?

# Answer
> 1 votes
The 10us delay is just your trigger pulse HIGH phase. Refer to the timing diagram on bottom of page two in your datasheet.

# Answer
> 0 votes
The 10 us pulse to the TRIG pin activates the ultrasonic detector. It then sends 8 pulses at 40 kHz, and finally, sends a pulse to the ECHO pin. That pulse sent to the ECHO pin has a pulse-width proportional to the distance of the nearest object.

---
Tags: arduino-uno
---


# Question
Title: MQTT (was WiFi) interference when using two nodeMCU devices
I have two nodeMCU boards, one from LoLin (192.168.1.52) and one from Amica (192.168.1.53). For each nodeMCU, I have mapped its MAC address to a fixed IP address using my Movistar WiFi router. I confirm from the serial monitor that each nodeMCU is being correctly assigned to the correct IP address

My sketch is a simple IoT/MQTT client.

**My problem is that if I power up both nodeMCUs, the WiFi connection is broken on both**.

The WiFi portion of my sketch is

```
void setup_wifi() {
  Serial.println(" Booting..");
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASSWORD);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    myBlink(LED_PIN, 20, 100);
    delay(5000);
    ESP.restart();
  }
  WiFi.printDiag(Serial);
  Serial.println(WiFi.localIP());
}

```

The output is

```
Mode: STA PHY mode:
N Channel: 1
AP id: 0
Status: 5
Auto connect: 1
SSID (13): MOVISTAR_xxxx
Passphrase (20): 509A8EC4Exxxxxxxxx
BSSID set: 0

192.168.1.53 (or .52 on the other device)

```

I realise that the symptoms are consistent with clashing IP addresses, but to confirm, both the serial diagnostics and the DHCP report from my router confirm that the two devices are on different IP addresses.

# Answer
> 1 votes
My bad!

Although my symptoms were consistent with WiFi interference, the interference was actually at the MQTT level.

The root cause was that **I hadn't realised that each MQTT client must have a unique client ID**. When the 2nd nodeMCU connected, it disconnected the first nodeMCU from MQTT, which then went into a reboot sequence to recover, which then returned the favour to the other nodeMCU.

---
Tags: programming, esp8266, wifi, nodemcu
---


# Question
Title: Delay() is not working outside of interrupt
Delay() doesn't work inside ISR routines, but here I have used it in loop and outside interrupt section still Delay is not working, however there isn't any error coming. What is wrong?

```
int L = 2;
volatile int done0=0;                                //ISR variables
void recordL();                                              //ISR 1

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

pinMode(L,INPUT);
}

void loop() {

interrupts();
attachInterrupt(0,recordL,RISING);
done0=0;

while(!done0)
{
    Serial.println(millis());
}
noInterrupts();

Serial.println("Detected");
delay(5000);
Serial.println("After Delay");
}

void recordL()
{
  Serial.println("in Interrupt0");
  done0=1;
}

```

# Answer
> 0 votes
```
noInterrupts();

Serial.println("Detected");
delay(5000);

```

`delay()` won't work with interrupts turned off.

# Answer
> 1 votes
> Do I need interrupts() noInterrupts() in the loop section?

Yes, you do. Always.

The optimal workflow is

1. In the ISR itself, just raise a flag or directly change some global variable.
2. In the `loop` you first copy that flag/variable to a local variable, using interrupts/noInterrupts to prevent the ISR changing the value while you are using/copying it.

Assignment are not atomic in Arduino World. That means that the value you are copying can change while you are doing it, and you end with garbage in your variables. Or, worse, it can change between one statement and the next. Try to debug that.

This is how you do it. In this example, I'm using an interrupt to manage a button (with debouncing). I need to detect state (pressed/not pressed) and timing (how long you pressed it). I can't directly use `lastFallingEdge` in `loop`; I copy it first so it won't change while I'm using it.

```
volatile unsigned long lastFallingEdge = 0; // For debouncing.
volatile boolean bPressed = false;

void buttonInterrupt(void)
{
    lastFallingEdge = millis();
    bPressed = true;
}

void loop()
{

    if(bPressed) {
        noInterrupts();
        bPressed = false;
        unsigned long falling = lastFallingEdge;
        interrupts();
        unsigned long len = millis() - falling;

        // Do something.
    }
}

```

# Answer
> 0 votes
Delay() function works by using timer interrupts internally. If you disable all interrupts using NoInterrupt function , then how will it work. Using that function is not recommended in code, as it causes unexpected misbehaviors.

---
Tags: arduino-uno, interrupt
---


# Question
Title: Is there a way to update Arduino uno Over The Air
I have the Arduino uno with a Ethernet W5100 Shield and would like to remotely sketches. Is there a way to update Arduino uno over the air? If not, is there a wired network arduino solution that will allow update over the air.

I've done this on the esp8266 using there tools but I can't find one for the Uno.

Thanks

# Answer
Not with WiFi, nor with Ethernet. People have managed it with Bluetooth, but only because it can create a transparent serial bridge. The bootloader only talks serial, so you have to use something that is serial to program it.

The only possible way is to use another WiFi (or Ethernet) device, such as the ESP8266, to act as a serial bridge to connect the Arduino's serial port (and reset signal) to your computer over WiFi. A bit of a waste of an ESP8266 since that is then the sole task it would have (unless you craft a far more complex sketch for the ESP8266 to allow it to do other things as well).
> 2 votes

# Answer
The Ariadne bootloader project enables upload over Ethernet to AVR boards with Ethernet shield.
> 2 votes

---
Tags: arduino-uno, remote-control, networking, network
---


# Question
Title: Setting a default arduino program in NodeMCU
Just after saying farewell to my old broken D1 mini I could not resist myself and bought a brand new nodemcu in the morning. I tried my previous arduino sketches to board and everything works fine, just needed to change the pin setup. I was wondering is it possible to set a default arduino program to nodemcu? such that every time I turn on my Nodemcu 12-E it runs it as a default program. Searching the internet I cam across this link. Downloaded the flasher,selected the port to which 12-E is connected and flashed it. After following all instructions and connecting to AP and 192.168.4.1/edit I tried to setup an arduino code as default code but failed. Is that because original firmware on supports **Lua programming language**? Is it possible to setup an arduino sketch as a default program? If not is it possible to convert arduino sketch to Lua programming language? as I have zero knowledge of Lua

# Answer
GPIO `D3` on the NodeMCU is the ESP8266's `GPIO0`, which does put the device in flash mode when pulled low on power-up. Either put a pull-up resistor on that pin, or use a different pin for IO.
> 0 votes

---
Tags: arduino-uno, nodemcu, software
---


title: Having trouble with 74HC595 and Uno

text:
# Question
Title: Having trouble with 74HC595 and Uno
Just picked up a couple of 74HC595 shift registers to use for my Arduino Uno, and I'm having trouble getting it working 100% of the time. My code is to get a value from the Serial monitor and shift it into the register. The issue is that bits 4 and 5 are always on no matter what I put into the monitor, but when I clock a 0 into the register during setup(), it works as expected, i.e. all LEDs go off

Here is the code:

```
int dataPin = 2;
int latchPin = 3;
int clockPin = 4;

void setup() {
    Serial.begin(9600);
    pinMode(dataPin, OUTPUT);
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, 0);
    digitalWrite(latchPin, HIGH);
}

void loop() {
    if(Serial.available()) {
        digitalWrite(latchPin, LOW);
        shiftOut(dataPin, clockPin, MSBFIRST, Serial.read());
        digitalWrite(latchPin, HIGH);
    }
}

```

Is it the code that is wrong? Do i have a busted shift register? Or something else? Thanks

# Answer
`Serial.read()` is going to give you ASCII codes. So when you send 1 from the serial monitor the Arduino receives 49. Note that the ASCII code for a digit is the same as the digit plus 48, so that sets bits 4 and 5 high.

You can use `Serial.read() - '0'` to get the actual number from the ascii code.
> 3 votes

---
Tags: arduino-uno, code-review, shift-register
---


title: NRF24L01 only receiving zeros

text:
# Question
Title: NRF24L01 only receiving zeros
I'm attempting to transmit very simple data across some NRF24l01 modules for testing purposes, and I've been following a YouTube guide.

Here is my code:

Trasmitter:

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

RF24 Radio (7, 8);
byte address[][6] = {"0"};
struct package{
   int on = 1;
};

typedef struct package Package;
Package data;

void setup() {
  Serial.begin(9600);
  delay(1000);
  Radio.begin();
  Radio.setChannel(118);
  Radio.setPALevel(RF24_PA_LOW);
  Radio.setDataRate(RF24_250KBPS);
  Radio.openWritingPipe(address[0]);
  delay(1000);
}

void loop() {
  Radio.write(&data, sizeof(data));

  Serial.println("Data sent:");
  Serial.println(data.on);
  delay(1000);
  }
}

```

Receiver:

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

 RF24 Radio (7, 8);
 byte address[][6] = {"0"};
 struct package{
    int on = 1;
 };

 typedef struct package Package;
 Package data;

 void setup() {
   Serial.begin(9600);
   pinMode(2, OUTPUT);
   delay(1000);
   Radio.begin();
   Radio.setChannel(118);
   Radio.setPALevel(RF24_PA_LOW);
   Radio.setDataRate(RF24_250KBPS);
   Radio.openReadingPipe(1, address[0]);
   Radio.startListening();
   delay(1000);
 }

 void loop() {
   while(Radio.available()){
     Radio.read(&data, sizeof(data));
     if(data.on == 1){
       digitalWrite(2, HIGH);
     }
     else if(data.on == 0){
       digitalWrite(2, HIGH);
     }
     else{
       digitalWrite(2, LOW);
     }
     Serial.println(data.on);
   }
   while(!Radio.available()){
     Serial.println("Error");
   }
   delay(1000);
 }

```

When I run the code on each respective unit, I receive only zeros on the receiver. Since I don't see where data.on could get set to zero in my code, I'm assuming there is a communication issue somehow between the two modules, even though `Radio.available()` is functioning properly.

Am I missing something obvious?

# Answer
> 2 votes
The OP wrote:

The issue turned out to be that the SPI pins on the MEGA are assigned differently than the UNO, and the code was actually working the whole time. I cant thank you enough for helping me, even if it turned out to be in vain.

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


title: Wiring an IR blaster+receiver board

text:
# Question
Title: Wiring an IR blaster+receiver board
I've salvaged this small IR blaster+receiver board from an old computer toy:

As you can see the board was connected to the main unit via a 4-wire cable labelled like this:

* LED (yellow) (I guess this is the IR LED/blaster)
* IR (white) (I guess this is the IR receiver)
* VCC (red)
* GND (black)

I'd like to use this board with an Arduino library like IRremote, but I am not sure about the VCC voltage and whether I need to add more components on the Arduino side.

UPDATE: I've checked the LED with a multimeter and indeed it is a visible bicolor LED, so there is no IR blaster in this board. At this point, is there any good reason to keep the IR receiver on the board rather than just cutting it and reusing as a standalone component?

# Answer
> 0 votes
You solved your problem.

You said

> I checked the LED with a multimeter and indeed it is a visible bicolor LED, so there is no IR blaster in this board.

So, be kind, accept this answer so we can close your question.

I'm posting, not comment, only to get this out of the "unanswered".

---
Tags: ir
---


# Question
Title: What values are the Atmel MCUs EEPROMs preloaded with?
I have checked with two datasheets: one for some ATMegas and one for some ATTinys MCUs and could not find what the `EEPROM.get()` call would read back if the EEPROM was empty (or contained default factory values). I have written a program in order to find out and it looks like on Arduino Uno the EEPROM bytes are all `FF` by default.

Is this the case with every Arduino board or just some of them ? Or perhaps we can not assume that all the MCUs of a certain type (such as ATMega328) will have this factory preloaded value of `FF` for the EEPROM bytes ?

**edit**

Following the fuses - thanks @Chris Stratton - I was able to find this in the datasheet:

> Skip writing the data value 0xFF, that is the contents of the entire EEPROM (unless the EESAVE Fuse is programmed) and Flash after a Chip Erase.

Seems like we could get the factory pre-loaded value by not programming the EESAVE fuse, which is what the Arduino Uno does by default, and just reading them.

> uno.bootloader.low\_fuses=0xFF
> uno.bootloader.high\_fuses=0xDE
> uno.bootloader.extendedfuses=0xFD

However, having a way to set them to a known value is fine too for my needs, so I shall just write that fuse and havea guaranteed `0xFF` all over the EEPROM.

# Answer
> 2 votes
When you erase an EEPROM it sets the cells to 0xFF. When you write a byte to a cell any 0 bits are set to 0 and the 1 bits are left alone.

0xFF is the normal erased state for most EEPROMs.

# Answer
> 3 votes
They're all set to 0xFF by default.

---
Tags: eeprom, memory-usage
---


title: Counting number of people inside a room

text:
# Question
Title: Counting number of people inside a room
I want to count the number of people in a room using a microcontroller (Arduino Uno).

I have 2 ultrasonic sensors at a doorway about a 1.5m apart from each other. I want to increment the number when someone walks into the room and decrement that number when someone walks out.

To do this: If sensor 1 detects a disturbance and then sensor 2 detects a disturbance then increment the counter.
If sensor 2 detects a disturbance and then sensor 1 detects a disturbance then decrement the counter.

However, my code is not working

```
#include<Ultrasonic.h>

Ultrasonic ultrasonic(5,6);

Ultrasonic ultrasonic2(11,10);

unsigned long currentMillis =0,t1,t2;

int d1,d2,c;

boolean ex=0,en=0,in;

void setup()
{
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);
  Serial.begin(9600);
  delay(5000);
  Serial.println("WELCOME TO AUTOMATION !!");
  Serial.println(ultrasonic.distanceRead());
  Serial.println(ultrasonic2.distanceRead());
}

void loop()
{
  currentMillis=(millis())%100;
  d1=ultrasonic.distanceRead();
  d2=ultrasonic2.distanceRead();

  if(currentMillis==0)
  {
    Serial.print("Count is :");
    Serial.println(c);
    Serial.println(d1);
    Serial.println(d2);
  }

  if(d1<=15 && d2<=15)
  {
    c=c;
  }
  else if(d1<=15)
  {
    if(en==1)
    {
      c++;
      en=0;
    }
    else ex=1;
  }

  else if(d2<=15)
  {
    if(ex==1)
    {
      c--;
      ex=0;
    }
    else en=0;
  }

}

```

# Answer
> 2 votes
Considering abandoning the ultra sonic sensors. Instead use 2 light beams positioned so a moving person would block one beam then both as they passed. This problem has been commercially solved for decades using this method.

The technique used for counting people is similar to the technique used in older mouse-pointing-devices to detect direction. The technique is called quadrature decoding such as used by an incremental rotary encoders.

Specifically, you need to detect if someone is walking in or is walking out of a room. But, to do this, you need to assure that first one then both beams will be block by the person. It is likely this requirement will be easier to meet using light beams rather than ultrasonic sensors.

Consider looking here for example Arduino code and an explanation how to use an Arduino with a quadrature encoded knob.

# Answer
> 0 votes
> I want to count the number of people in a room using a microcontroller (Arduino Uno).

a few ways:

1) have sensors on the entrance + exit;

2) require people in the room to push a button periodically;

3) embed sensors on the people. rfid would work for example;

4) have an image sensor and put a super-computer to analyze the picture;

5) weigh those people on a scale;

6) route those people through a single file gate and count pulses;

...

just for starters.

---
Tags: arduino-uno, ir, code-optimization, code-review, debugging
---


# Question
Title: Why do MEGA2560 digital pins go high on serial disconnect?
I'm trying to set up a system using an that delivers a specific number of digital pulses to a device using one of the digital pins. The number of pulses delivered is specified over a the Mega's USB serial connection using a Python script (or terminal for debugging).

When I close the serial connection to the Arduino, I get a short "blip" that looks like a digital high (see image below). This happens when I disconnect in PySerial using `Serial.close()` or when I simply close my Arduino IDE terminal window.

It does not occur when I press the reset button on the board

Any ideas on how to get rid of this? Thanks!

# Answer
> 1 votes
When you connect and disconnect from the Arduino, the usb host chip resets the entire device. If you do not want this you can cut the RESET trace on the board.

some boards have a jumper here instead that can be removed.

more info here

https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

---
Tags: serial, arduino-mega, reset
---


# Question
Title: Arduino UNO Intro to Engineering Project
I am a college student in an intro to engineering class looking to create a final project. My goal is to create a small "present" that opens its lid via a servo and plays jingle bells with LEDs flashing (as shown in the youtube video linked below), before closing the lid once again until a further button press.
https://www.youtube.com/watch?v=V6TcAhXCL6w

The code that this video uses is:

```
/*
  "Jingle Bells" Melody

 Plays "Jingle Bells"

 circuit:
 * 8-ohm speaker on digital pin 7

#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659

// notes in the melody:
int melody[] = {
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_FS4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_B4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_D5, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_A4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_D5,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4 };

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {

  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 8, 8, 8, 8,
  8, 8, 8, 8, 2,
  8, 8, 4, 8, 8, 4,
  8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 4, 4,
  8, 8, 4, 8, 8, 4, 8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 2 };

void setup() {
    pinMode(3,OUTPUT);
    pinMode(6,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(11,OUTPUT);
    digitalWrite(3, LOW);
    digitalWrite(6, LOW);
    digitalWrite(9, LOW);
    digitalWrite(11, LOW);
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 100; thisNote++) {

    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1800/noteDurations[thisNote];
    // I found that by lengthening the noteDuration,
    // I was able to "slow" the song down.
    tone(7, melody[thisNote],noteDuration);
    LEDon();

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(7);
    LEDoff();
  }
}

void loop() {
  // no need to repeat the melody.
}

int currentLEDpin=3;
void LEDon()
{
    digitalWrite(currentLEDpin, HIGH);
}

void LEDoff()
{
    digitalWrite(currentLEDpin, LOW);
    if (currentLEDpin==3) currentLEDpin=6;
    else if (currentLEDpin==6) currentLEDpin=9;
    else if (currentLEDpin==9) currentLEDpin=11;
    else currentLEDpin=3;
}

```

My general outline for the project looks like this:

1. Set LEDs, Piezo, and Servo to OUTPUT
2. Set pushbutton to INPUT
3. Start all LEDs off/LOW
4. Start a loop that has if statement for button push
5. Open the lid (servo motor about 100 degrees)
6. Start the song/LED sequence using code borrowed from the youtube video
7. After finishing the song, close the lid (servo motor back 100 degrees)

I am very much a beginner to coding Arduino, so I was wondering if my uploaded sketch seems correct...

```
//Notes for Jingle Bells
#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659

//Notes in melody Command
int melody[] = {
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_FS4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_B4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_D5, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_A4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_D5,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4 };

// Note Durations (4 = quarter note, 8 = eighth note, etc.)
int noteDurations[] = {
  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 8, 8, 8, 8,
  8, 8, 8, 8, 2,
  8, 8, 4, 8, 8, 4,
  8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 4, 4,
  8, 8, 4, 8, 8, 4, 8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 2 };

#include <Servo.h>      //Include built-in Servo sketch
Servo servo;            //Servo sketch reference for setup
const int servoPin=5;   //Set servoPin to 5
int angle = 0;          //Set initial servo angle to 0 degrees

const int buttonPin=2;   //Set buttonPin to 2
int buttonState=0;       //variable for reading pin status

int currentLEDpin=3;    //Set LED pin variable for LED flashes
void LEDon()            //Define LEDon for turning on LED to music
{
    digitalWrite(currentLEDpin, HIGH);
}

void LEDoff()           //Define LEDoff for turning off LED when music off
{
    digitalWrite(currentLEDpin, LOW);
    if (currentLEDpin==3) currentLEDpin=6;
    else if (currentLEDpin==6) currentLEDpin=9;
    else if (currentLEDpin==9) currentLEDpin=11;
    else currentLEDpin=3;
}

void setup() {
    pinMode(3,OUTPUT);           //Set LED Pins to OUTPUTs
    pinMode(6,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(11,OUTPUT);
    digitalWrite(3, LOW);        //Start all LED lights off
    digitalWrite(6, LOW);
    digitalWrite(9, LOW);
    digitalWrite(11, LOW);

    pinMode(buttonPin,INPUT);   //Set button to INPUT

    servo.attach(servoPin);     //Servo setup

}

void loop() {
 buttonState=digitalRead(buttonPin);     //read input value

  if (buttonState == HIGH) {              //check if pushbutton is pressed

  for(angle = 0; angle <110; angle++)    //rotate servo 110 degrees, opening present box lid
    {
    servo.write(angle);
    delay(15);
    }

  for (int thisNote = 0; thisNote < 100; thisNote++) {
    int noteDuration = 1800/noteDurations[thisNote];    //define note duration
    tone(7, melody[thisNote],noteDuration);             //Play melody of Jingle Bells
    LEDon();                                            //Flash LEDs to tune
    int pauseBetweenNotes = noteDuration * 1.30;        //Pause between notes to annunciate each note
    delay(pauseBetweenNotes);
    noTone(7);                                          //Stop playing music when melody over
    LEDoff();                                           //Stop flashing LEDs when melody over
}

  for(angle = 110; angle > 0; angle--)                  //Close present box lid
    {
    servo.write(angle);
    delay(15);
    }
   }

}

```

So when you say to erase the LEDon and LEDoff calls, is that in this section of the code?:

```
 for (int thisNote = 0; thisNote < 100; thisNote++) {
    int noteDuration = 1800/noteDurations[thisNote];    //define note duration
    tone(7, melody[thisNote],noteDuration);             //Play melody of Jingle Bells
    LEDon();                                            //Flash LEDs to tune
    int pauseBetweenNotes = noteDuration * 1.30;        //Pause between notes to annunciate each note
    delay(pauseBetweenNotes);
    noTone(7);                                          //Stop playing music when melody over
    LEDoff();                                           //Stop flashing LEDs when melody over
}

```

# Answer
LEDon and LEDoff are defined in the Jingle Bell sketch. They just lit on/of the leds.

You don't need them for your project, just erase the calls. Otherwise, copy the LEDon/off functions:

```
int currentLEDpin=3;
void LEDon()
{
    digitalWrite(currentLEDpin, HIGH);
}

void LEDoff()
{
    digitalWrite(currentLEDpin, LOW);
    if (currentLEDpin==3) currentLEDpin=6;
    else if (currentLEDpin==6) currentLEDpin=9;
    else if (currentLEDpin==9) currentLEDpin=11;
    else currentLEDpin=3;
}

```

You made a mistake:

```
if(buttonState = HIGH) {               //check if pushbutton is pressed

```

Here you **assign** HIGH to `buttonState`.

The "=" is assignment operator. What you were thinking is "==", the equality-comparison operator (a common mistake). Replace it with

```
if(buttonState == HIGH) {               //check if pushbutton is pressed

```

Also, you need to debounce you button. Read about it in this excelent tutorial by Nick Gammon: Switches tutorial. Well, read his whole blog if you have the time.

Otherwise, you are doing well.
> 1 votes

---
Tags: arduino-uno, led, code-review, piezo
---


title: NodeMCU espcomm_sync failed

text:
# Question
Title: NodeMCU espcomm_sync failed
I have a NodeMCU ESP12E DevKit V2 from Geekcreit. I had it working some months ago, but now I cannot upload to it. I am using the arduino IDE and I've set the "Additional Boards Manager URLs" to:

> http://arduino.esp8266.com/stable/package\_esp8266com\_index.json

## The error I get:

> warning: espcomm\_sync failed
>
> error: espcomm\_open failed
>
> error: espcomm\_upload\_mem failed

## What I've tried so far:

* Applying 3.3v to the VIN
* Uploading from 3 different PCs and one Ubuntu
* Uploading using Arduino IDEs: 1.6.18, 1.6.2, 1.6.9, 1.6.11
* Using the esptool.exe to upload to it from the cmd prompt.
* Using following board configurations from the Arduino IDE:
    + "NodeMCU 1.0 (ESP-12E Module)"
    + "NodeMCU 0.9 (ESP-12 Module)"
    + "Generic ESP8266 Module"
    + "NodeMCU 1.0 (ESP-12E Module)"
* Uploading with different upload speeds.
* Uploading with different flash sizes.
* Uploading with different USB cables.
* Tried erasing flash, read flash.

All of the above has still resulted in the error stated in the top of this post.

## Verbose output from upload:

```
Arduino: 1.6.11 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

Build options changed, rebuilding all

Sketch uses 222,213 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 31,588 bytes (38%) of dynamic memory, leaving 50,332 bytes for local variables. Maximum is 81,920 bytes.

C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM1 -ca 0x00000 -cf C:\Users\xxx\AppData\Local\Temp\build48b2fca13fb12d7c15d8dce627beccb2.tmp/Blink.ino.bin
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM1
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
An error occurred while uploading the sketch
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

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

```

https://pastebin.com/GCq6aZsR

I was beginning to suspect that my NodeMCU board is broken somehow, but the old file is still uploaded on the device is active on my network, so if it is broken, it might just be the usb port. **EDIT**: Just received a new module that gives the same error, so it is not due to faulty hardware.

However, I have found people facing the same issues when googling, but no real solution has worked for me, and the above list of what I've tried is mostly suggestions found in this process.

I'm running low on ideas and I am thinking to order a new NodeMCU board to try and rule out flawed hardware.

Any suggestions or help will be much appreciated. Thank you.

# Answer
> 1 votes
Returning to this, the issue still persisting, I tried once more with the flashing software.

After flashing the NodeMCU I was once again able to upload to my NodeMCU from the Arduino IDE.

So no hardware flaws and no need for new drivers.

# Answer
> 1 votes
Same issue here. For me it was a hardware issue. The esp chip had solder that did not flow from the pads of the board to the esp board. To confirm this, before programming press down on the wifi module and keep pressed during programming. If it is a solder issue, it should program just fine. If it programs, you need to reflow all solder joints around the esp chip. Hope it helps.

# Answer
> 1 votes
Try these steps: 1. Use a different USB port. 2. Go to Device Manage and check if the driver is installed. If already installed, uninstall it and then install it from Device Manager(worked for me, was having the same issue). 3. Nodemcu could be corrupt (faced same error and got it changed).

# Answer
> 0 votes
Maybe there's something wrong with your driver.
Check which module of USB-to-UART of your NodeMCU is using.As far as I know, there're two most common modules:CH340 and CP2102.
Just download the driver (driver for CH340and driver for CP2102) and try again:)

---
Tags: esp8266, nodemcu
---


title: Format Integer in Arduino

text:
# Question
Title: Format Integer in Arduino
How to format an integer as 3 digit string? If I give `3` formated string should be `003`

```
printf("%03d\n", 3); // output: 003

```

This doesn't work in Arduino.

# Answer
> 3 votes
The standard C function `printf` print to stdout. Arduino doesn't has a stdout. You can print to Serial, but must prepare/format the string first.

Instead of `printf`, use `snprintf`. It prints to a char array, which you later can use with `Serial.print`, or whatever other function that take a string.

```
void setup() {
  Serial.begin(9600);
  while(!Serial);

  char buffer[4];
  snprintf(buffer,sizeof(buffer), "%03d", 3);
  Serial.println(buffer);
}

void loop() {

}

```

Note: all the comments apply to this answers.

---
Tags: arduino-uno, c++, string
---


# Question
Title: I need help setting up my Arduino Uno with the port
I'm using a Windows computer, and if I recall correctly I installed the IDE using the installer, so I probably don't need to manually install the drivers. However, I can't figure out how to set up the serial port with the Arduino. For me under Tools, there's no "Serial Port" option but instead "Serial Monitor" and "Serial Plotter."

When I tried to upload my file, it failed. When I clicked Serial Plotter, it gave this error message:

```
Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

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

Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Board at COM1 is not available

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

```

How am I supposed to resolve this?

# Answer
> 0 votes
I figured it out by following the tutorial by Adafruit. I had to install it manually in order for it to work.

---
Tags: arduino-ide, arduino-setup
---


title: Writing a custom character on an lcd

text:
# Question
Title: Writing a custom character on an lcd
I am using a 16\*2 lcd display as a dashboard computer. I want it to display a logo at the very beginning of the code, but some letters occupy the space of 4 characters, and are using both lines of the display, and creating those letters character by character (some actually require 6 characters) is very difficult. Is there anyway i can address the lcd as a big matrix ? there would be 16 lines ( the oringinal 2 lines * 8 lines of each character) and 80 columns (the original 16 columns * 5 columns each character has). This would make it A LOT easier.

# Answer
> 1 votes
The chip you are using (HD44780) only works with characters; you can't address single pixels. If you read the datasheet, the word "pixel" is absent.

Of course, you can add a wrapper that implement a `drawPixel(row,col)` function by defining custom characters and then sending it to the display.

The result will be unpleasent to the eye, because there is a gap between chars on screen, and another gap between rows.

A better alternative is an OLED display like this:

You can find the same display with I2C or SPI interfaces. Basic model is B&W, but you also have color and touch sensitive variants.

# Answer
> 0 votes
> some letters occupy the space of 4 character

use CGRAM to define 4 characters and display them over two lines.

---
Tags: lcd, display
---


title: Arduino IDE compiles, UECIDE not

text:
# Question
Title: Arduino IDE compiles, UECIDE not
I'm rewriting a personal project and it doesn't compile under UECIDE 0.9.1, but it does with Arduino IDE 1.8.5.

Target is NodeMCU 0.9 with default options.

**Arduino IDE 1.8.5**

```
Archiving built core (caching) in: /tmp/arduino_cache_347503/core/core_esp8266_esp8266_nodemcu_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_4a642491bde0820b9be0f8ad42686d29.a
Sketch uses 299199 bytes (28%) of program storage space. Maximum is 1044464 bytes.
Global variables use 37372 bytes (45%) of dynamic memory, leaving 44548 bytes for local variables. Maximum is 81920 bytes.

```

**UECIDE 0.9.1**

```
• Error at line 231 in file Monitor.ino:
‣ expected '{' before ';' token

• Error at line 231 in file Monitor.ino:
‣ expected ')' before ';' token

• Error at line 190 in file Monitor.ino:
‣ redefinition of 'CronEntry cronBlink'

• Error at line 231 in file Monitor.ino:
‣ 'CronEntry cronBlink' previously declared here

```

Project is too large to post here, so I zipped it and uploaded to Google Drive, where anyone can download it with this link

https://drive.google.com/file/d/1BGvqtPx0547fPfX1Nucwhd\_a-MO\__vWX/view?usp=sharing

**EDIT** (After lambda comment by Majenko)

I was using a struct to hold cron entries, using lambdas:

```
struct CRON_ENTRY {
  boolean active;       // Task is active.
  unsigned long start;  // Start time (ms uptime).
  unsigned long repeat; // Repeat every (ms).
  fcncron fcn;          // task.
};

CRON_ENTRY cronBlink = {false, 0,   500, [](CRON_ENTRY * c)
{
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();
}

```

and then replace CRON\_ENTRY struct with CronEntry class:

```
CronEntry cronBlink(false, 0,   500, []() {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();});

```

I really like lambas because they made code shorter.

# Answer
This is a bug in UECIDE. It doesn't like lambda functions in constructors.

A complete rewrite of the sketch parser to use Exuberant Ctags is under way.
> 2 votes

---
Tags: arduino-ide, compilation-errors, uecide
---