# Question
Title: Buffer overflow error in ESP8266_SoftwareSerial library
I am running into buffer issues when running the Firmware.ino example here.

The output from my Arduino serial log on baudrate 115200 (I put the ESP on baudrate 9600):

```
Begin
01:17:15.538 -> Baudrate set success
01:17:15.585 -> Station + softAP - OK
01:17:18.631 -> Joining AP successful, IP: 192.168 r⸮+@⸮
01:17:18.991 -> Single Mode OK
01:17:18.991 -> Sending Request to www.google.com
01:17:19.084 -> create tcp - OK
01:17:19.710 -> not sentbuffer is full!
01:17:20.022 -> HZiw93GUFmVJYFz-yRmahGURP_UBbRb4EF0Ahwzx8MJ1GOyC5Z0dns8UD41G8kUqnL0oxNPxa6xF9nAqNF3X3B_hKW11zoyaBPn8trvUNt-69qbFCNOZwNjgoaloKbOQs7NN-B3tpmwFKpHfKsfKyZfiMdhulN3SgZMhewYBg9c; expires=Wed, 05-Feb-2020 05:17:18 GMT; path=/; domain=.google.com; HttpOnly
01:17:20.162 -> Accept-Ranges: none
01:17:20.162 -> Vary: Accept-Encoding
01:17:20.209 -> ConnecS,
01:17:24.179 -> Sending Request to www.google.com
01:17:24.774 -> create tcp - ERROR
01:17:28.759 -> Sending Request to www.google.com
01:17:29.432 -> create tcp - ERROR
01:17:33.402 -> Sending Request to www.google.com
01:17:34.021 -> create tcp - ERROR
01:17:38.028 -> Sending Request to www.google.com
01:17:38.669 -> create tcp - ERROR
01:17:42.681 -> Sending Request to www.google.com
01:17:43.294 -> create tcp - ERROR
01:17:47.298 -> Sending Request to www.google.com
01:17:47.954 -> create tcp - ERROR
01:17:51.925 -> Sending Request to www.google.com
01:17:52.595 -> create tcp - ERROR
01:17:56.563 -> Sending Request to www.google.com
01:17:57.204 -> create tcp - ERROR
01:18:01.222 -> Sending Request to www.google.com
01:18:01.871 -> create tcp - ERROR
01:18:05.839 -> Sending Request to www.google.com
01:18:06.460 -> create tcp - ERROR
01:18:10.456 -> Sending Request to www.google.com
01:18:10.596 -> create tcp - OK
01:18:11.049 -> buffer is full!
01:18:11.049 ->
01:18:11.049 ->
01:18:11.049 -> +IPD,1430:HTTP/1.1 200 OK
01:18:11.096 -> Date: Tue, 06 Aug 2019 05:18:09 GMT
01:18:11.096 -> Expires: -1
01:18:11.096 -> Cache-Control: private, max-age=0
01:18:11.143 -> Content-Type: text/ht
l; charset=ISO-8859-1
01:18:11.143 -> P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
01:18:11.190 -> Server: gws
01:18:11.190 -> X-XSS-Protection: 0
01:18:11.190 -> X-Frame-Options: SAMEORIGIN
01:18:11.224 -> Set-CooS,
01:18:15.192 -> Sending Request to www.google.com
01:18:15.822 -> create tcp - ERROR
01:18:19.849 -> Sending Request to www.google.com
01:18:20.473 -> create tcp - ERROR

```

As you can see, at first it starts ok, gives a buffer error, runs in error for a while, then runs OK again. This happens a couple times, then it runs only in error. I imagine this is some issue with the buffer of the ESP or the Arduino, but I'm not sure how to diagnose it further.

Things I have tried to fix the error: \- As mentioned in the Firmware.ino example comments, I uncommented #define ESP8266\_USE\_SOFTWARE\_SERIAL \- Also as mentioned in the comment, I changed line 42 from 64 to 256. It didn't work either time. \- There is a MAX\_BUFFER\_SIZE in the included ESP8266.h library that I also changed, from 300 to 256, because I thought that might help, but the error persisted.

# Answer
There's some heavy `String` usage in that library, would not recommend it for anything you want to be stable, especially with an Uno.

The library seems to create a connection by first clearing the `SoftwareSerial` buffer and then issuing the right AT command. It waits for 500ms for a response before giving up. I suspect the wait interval is sometimes not long enough for the module to receive, parse and handle the command before responding. So you should try increasing it to 2000 ms at line 773.

The `buffer is full` message just refers to the library's own buffer for holding received data, which is 300 bytes by default. The buffer's getting filled so quickly (and the `SoftwareSerial` internal buffer likely overrun too) because you're loading a webpage like Google's which has more than 300 bytes in the response header alone. It's even possible that by the time the next request commences with another AT command, the ESP8266 is still dumping the response from the previous request, and so the command's response is still way down the queue and so doesn't get read before the timeout.

Instead, try loading a simple webpage like `httpbin.org/ip`. That is, at lines 952, 954:

```
char* request =  "GET /ip HTTP/1.1\r\nHost: www.httpbin.org\r\nConnection: close\r\n\r\n";

if (createTCP("www.httpbin.org", 80))

```
> 1 votes

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


title: AI A7 Thinker connection with Arduino

text:
# Question
Title: AI A7 Thinker connection with Arduino
I am trying to connect my A7 to my Arduino Uno but I can't find a way to communicate with it. I searched a lot on the internet to find some schemes but not one of them worked. Here is my actual setup:

```
ARDUINO              A7

PIN 6      <=>       URXD
PIN 7      <=>       UTXD
GND        <=>       GND
5V         <=>       5V

```

Here is my code:

```
#include<SoftwareSerial.h>
SoftwareSerial myserial(6,7);//RX,TX

void setup() {
  Serial.begin(9600);
  myserial.begin(115200);
  Serial.println("Starting...");
}

void loop() {
   delay(1000);
   myserial.println("AT");
   Serial.println(myserial.read());
}

```

I tried by connecting USB instead of 5V, both of them, connecting the POWER pin, or interchange 6 and 7, pressing the power button, with different delays, different baud rates, but I always get the same output on my computer:

```
Starting...
-1
-1
-1
-1
...

```

Sometimes it goes 0 when I plug the USB and press the power button. The LED on the A7 is responding when I press the button and sometimes it powers up the circuit.

I also tried this solution with really simple code:

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

void loop() {
}

```

Again with different bauds rates but the compiler outputs an error:

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

```

So I don't know what is wrong. Maybe the board is not working but it's most certainly my mistake, so I am asking for your help to solve this puzzle.

Thank you!

# Answer
I'm dealing with the exact same thing right now trying to get mine to work. The only help I can give so far is that that avrdude error was solved for me when i stopped trying to upload code to the uno with the a7 powered. think it has to do with the programmer using the same RX/TX ports.
> 1 votes

# Answer
You said...

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

```

Those errors are occurring because you are attempting to upload to your Arduino using the same Tx/Rx wires that the software is using and trying to upload on.

**A Possible Fix**

You need to power down the A7. Possibly pull the ground wire from it when you go to upload your program. There are alternatives to doing this that are better, but the point is that the A7 is using those wires and keeping them busy. If the A7 if off then the upload should work. After uploading, then re-connect the A7 ground wire so it gets power.
> 0 votes

---
Tags: arduino-uno, serial, gsm, gps
---


title: Programming ESP32 MCUs for production

text:
# Question
Title: Programming ESP32 MCUs for production
Before committing to learning about the ESP32 and how to program it, I would like to know if the ESP can be programme the same way for production as it can on évaluation boards (with the Arduino IDE).

Since it obviusly much easier than most for microcontrollers, I was wondering if a product is eventually mass produced, if the code used to program the evaluation board (such as this one https://makeradvisor.com/tools/esp32-dev-board-wi-fi-bluetooth/) could be used on the final product.

# Answer
Yes. Most manufacturers would just require a binary (or HEX depending on MCU) file of your compiled code. If it's not a system they already know how to handle you will also need to provide a procedure for them to follow to program the device. What form that takes depends on the manufacturer.

You can also generally order pre-programmed MCUs and modules direct from the manufacturer where they (for a small fee) will program the chips for you before they are then sent to the board manufacturer for population.

If there is no facility on the MCU manufacturer's website then just email their sales department and I am sure they would be happy to quote you. Again, all they will require is a HEX or BIN file (depending on manufacturer) for programming.
> 3 votes

---
Tags: nodemcu, esp32
---


# Question
Title: Powering Motor shield and Arduino Mega Separately
I'm trying to build a fire fighting robot, that uses 2 BO DC motors, 2 Servos - MG996R and SG90. For them I'm using Motor Shield v1 of Adafruit's make that uses 2 L293D IC's and a 74HC595 shift registers.

Now, I'm placing the motor shield over Arduino Mega and trying to connect other components such as Flame Sensor, Ultrasonic Sensor and submersible DC Water Pump. As soon as I try to power up ultrasonic sensor, the power indicating LED's on both the shield and Mega goes off.

I've been testing this with simple USB connected power supply and to my understanding the power being supplied is insufficient. Since **it would be a moving cart, I would like to know whether there is any way to power up Shield and Mega separately by a 9v Battery?**

# Answer
On the side of the DC Motor Shield v1, there is an external power - + 2 pin terminal.

This can be used to supplement the shield with power.

Adafruit: "The motor controllers on this shield are designed to run from 4.5V to 25V. MOST 1.5-3V MOTORS WILL NOT WORK"

If you are lucky to have the motor specs and ratings on hand, you will be able to account for how much power your motor(s) will need in your application.

Adafruit: "The motor driver chips that come with the kit are designed to provide up to 600 mA per motor, with 1.2A peak current. Note that once you head towards 1A you'll probably want to put a heatsink on the motor driver, otherwise you will get thermal failure, possibly burning out the chip."

Here is an important tid-bit for your scenario... (So no 9v Batteries for the motors!):

Adafruit: "You can't run motors off of a 9V battery so don't even waste your time/batteries! Use a big Lead Acid or NiMH battery pack. Its also very much suggested that you set up two power supplies (split supply) one for the Arduino and one for the motors. 99% of 'weird motor problems' are due to noise on the power line from sharing power supplies and/or not having a powerful enough supply!"

...

So makes sense, get the Arduino powered, by itself, then get another power source for your motor shield.

Your sensors might be able to hop on the Arduino power supply if it's providing enough power. I'd keep them separate from the motor power line, due to noise interference as suggested.

Try this, and see if the Arduino stays powered.

There is a lot of helpful info here, some new things I've learned just now. https://learn.adafruit.com/adafruit-motor-shield/power-requirements
> 2 votes

---
Tags: arduino-mega, power, arduino-motor-shield
---


title: esp8266- how to use GPIO0 as an input?

text:
# Question
Title: esp8266- how to use GPIO0 as an input?
First, my setup: I have an Arduino Uno with an Adafruit Audio Shield. I have a Wemos D1 Mini controlling the project.

I need for the D1 to know when a file is playing.

I have a GPIO pin on the Uno programmed to be high when a file is playing. Low otherwise. I have two GPIO pins on the Wemos that are unused, D3 and D4 (GPIO0 and GPIO2). (I use a divider circuit of a 10K over a 20K resistor to bring the 5V from the Uno down to 3v3 for the Wemos). D4 is already a problem because it has to be high to boot and the GPIO from the Uno is normally low. D3 (GPIO0) has to be high to boot and has an internal pullup.

Here's my problem. How do I turn off the pullup on GPIO0? Even when the Uno GPIO is low (0V), the GPIO0 measures 2.4V, which my sketch sees as a logical 1.

Any tips would be appreciated. (I thought of reversing the polarity on the Uno so that low=true, but even when the Uno is driving the pin low, the Wemos GPIO0 pin is still at 2.4V, so low-true logic won't work either.).

# Answer
> 1 votes
Don't use the voltage divider and never set the Uno pin HIGH.

Pull io 0 of esp8266 LOW with pinMode of the Uno pin.

```
pinMode(TO_ESP_IO0, OUTPUT); // sets the pin LOW

pinMode(TO_ESP_IO0, INPUT); // let it to the io0 pull-up resistor

```

---
Tags: arduino-uno
---


# Question
Title: Difficulties programming Arduino uno for 24 hour cycle
I am trying to program my Arduino Uno board for a 24 hour cycle. I have the Arduino board and two relays. The aim is; every 24 hours relay 1 has to switch on for 5 seconds, and 1 second later relay 2 has to switch on for 15 seconds. I have a sketch for a 12 hour cycle, and that works fine, but when I try for a 24 hour cycle, by changing the const unsigned int totalTime from 43200 seconds to 86400 seconds, everything goes wrong.

24 hour sketch - what is wrong?

```
//turn relays on and off at certain times.
//when the digital output pin is HIGH, then the relay is off.
//when the digital output pin is LOW, then the relay is on.

enum actioEnum {
  RELAY1_ON,
  RELAY1_OFF,
  RELAY2_ON,
  RELAY2_OFF,
};

struct tableStruct{
  unsigned int time;
  actionEnum action;
}
const table [] = {
  {0,RELAY1_ON},
  {5,RELAY1_OFF},
  // remaining 86395 for a total of 86400.
  {0,RELAY2_OFF}, // not needed, it is already off.
  {6,RELAY2_ON},
  {6+15,RELAY2_OFF},
  // remaining 86379 for a total of 86400.
};

const unsigned int totalTime = 86400; // total amount for sequence
unsigned int seconds;

unsigned long previousMillis;
const unsigned long interval = 1000; // 1000 ms; // 1000 ms is one second

const int relay1Pin = 2;
const int relay2Pin = 3;

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

  // the relay is off when the pin is high.
  // turn output high before setting the pinMode.
  // then the output changes from a floating pin to high,
  // and the relays will not be activated.
  digitalWrite (relay1Pin, HIGH);
  pinMode (relay1Pin, OUTPUT);
  digitalWrite (relay2Pin, HIGH);
  pinMode (relay2Pin, OUTPUT);
}

void loop () {
  // a one second timer with millis
  if (millis() - previousMillis >= interval) {
    previousMillis += interval;
    // scan table
    for ( int i = 0; i < int (sizeof(table) / sizeof (tableStruct)); i++) {
      if (table [i] . time == seconds) {
        switch (table [i] . action) {
          case RELAY1_ON:
            Serial.println("Relay 1 on");
            digitalWrite (relay1Pin, LOW); // low is relay on.
            break;
          case RELAY1_OFF:
            Serial.println("Relay 1 off");
            digitalWrite (relay1Pin, HIGH); // high is relay off.
            break;
          case RELAY2_ON:
            Serial.println("Relay 2 on");
            digitalWrite (relay2Pin, LOW); // low is relay on.
            break;
          case RELAY2_OFF:
            Serial.println ("Relay 2 off");
            digitalWrite (relay2Pin, HIGH); // high is relay off.
            break;
          default:
            Serial.println ("Error, a bug in the scketch");
        }
      }
    }
    seconds++;
    if (seconds >= totalTime) {
      seconds = 0;
    }
  }
}

```

# Answer
> 5 votes
On the Uno `unsigned int` is a 16 bit number. That means, that it can hold values between (and including) 0 and 65535. If you try to write a bigger value to this variable, it will cut of the higher bits, so that the rest fits into 16 bits. That gives you a totally different value, which is significantly small than 24h.

The solution is to use a bigger variable type for `totalTime`. You can use `unsigned long`, which has 32 bits and can hold way bigger values ( 0 to 4,294,967,295 (2^32 - 1)). That should be plenty enough for all your cases.

---
Tags: arduino-uno
---


# Question
Title: I2C master/slave maximum requestEvent message size
Using a `NodeMCU` master and an `Arduino` slave (`Wire.h` on both sides), is there a maximum message size (32 bytes?) for the answer that the slave sends from `requestEvent()`?

If so, is there any solution to circumvent such a restriction WITHOUT the use of other libraries (like `I2C_Anything`, for example)?

# Answer
The I2C protocol itself does not have a transmission size restriction. But the implementation in the Wire library only reserves a specific amount of RAM for the buffers. This site mentiones 32 bytes for normal Arduinos (couldn't find the source code currently) and I found 128 bytes for the ESP8266 in the source code.

You cannot have unlimited message length, since the buffer has to hold the whole message and the RAM on normal Arduinos is very limited.

But you can make the buffers of the libraries bigger by changing the corresponding defines in the header files to a bigger value. Keep in mind, that the actual used memory space is with a factor 2, since the buffer size gets used for both send and receive buffer.

---

If you need bigger messages, than is fitting in the available RAM, you should either change to a board with more RAM, or develop a way to process one part of a message, deleting it and then process the next part (multi part message). Though that raises the question, why the messages have to be that big in the first place.
> 1 votes

---
Tags: arduino-nano, i2c, nodemcu
---


title: ESP8266 doesn't detect WiFi

text:
# Question
Title: ESP8266 doesn't detect WiFi
I try to connect my NodeMCU Amica to my WiFi network, but it doesn't detect any networks around. I chose Board "NodeMCU 1.0 (ESP - 12E Module)", upload speed of 115200 and I have the correct port selected.

When I try the blink sketch, it works perfectly, but when I try to use the WiFiScan example, I only get the message "no networks found" and I don't.

I did pay attention that the upload speed in the sketch and monitor are always the same as the one I selected. Also, I tried out different upload speeds, without any succes either.

I already changed my network to 2.4 GHz, and also tried to downgrade the libraries to older versions, but nothing helped till now.

About any help, I would be really glad.

# Answer
Firstly try to set it up as AP and check whether is it working ? If not, there is issue with power supply. Because WiFi Scan requires more current... than normal WiFi connection operation.
> 1 votes

# Answer
1. Make sure you have entered correct ssid and password for that. It is very much case sensitive.
2. Second reason for this can be insufficient amount of power supply supplied to it so make sure you are using good quality of power adapter for it. 3.https://tttapa.github.io/ESP8266/Chap07%20-%20Wi-Fi%20Connections.html Then try refering this link step by step... Hope this will help Thanks
> 0 votes

---
Tags: esp8266, wifi
---


# Question
Title: how to use keypad button multiple integer value input
I have been working on water flow sensor which measures volume then i need to restrict the amount of water which disperse from depend on the user input form the keypad so how can i store the input form the keypad into a variable.

# Answer
When you use the keypad library, there is a command to read a key:

```
 myKeypad.getKey();

```

Store these keys in a (string) buffer, and after a certain key is pressed (e.g. #), parse the string buffer to retrieve the integer (with the c function `atoi`, see here for a description).
> 0 votes

---
Tags: keypad
---


# Question
Title: please tell me how do I fix this code down here(please tell in my easy English)
```
 LiquidCrystal 1cd(12, 11, 5, 4, 3, 2);

 void setup() {
   1cd.begin(16, 2);
   1cd.print"abbu, kya, chalrelaye!");
 }

 void loop() {

 }

```

# Answer
> 4 votes
Variable names MUST NOT start with a digit. Only '\_' and a-z are allowed!

`1cd` really should be `lcd` with an 'ell' instead of a one (1).

# Answer
> 3 votes
I suggest you modify the LiquidCrystal "Hello World" sketch:

Here is the example code:

```
// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

```

Good luck!

---
Tags: arduino-uno
---


# Question
Title: Programming the ATMega328P without Arduino board always returns the error: avrdude: stk500_recv(): programmer is not responding
I have a microcontroller: `ATMega328P`. I don't have any `Arduino Uno board`.

I want to program the `ATMega328P` using my `FTDI programmer`.

But when I try to program the `ATMega328P` without `Arduino` board I always get this **error**:

`avrdude: stk500_recv(): programmer is not responding`

I've followed this YouTube Tutorial to build this.

And ended up with this diagram:

All the connections seems OK.

I choose the board: `"Arduino Pro or Pro Mini"` because only with this one I can choose the correct processor: `"ATMega328P (5V, 16MHz)"`

The port is correct: `"/dev/ttyUSB0"`

And as for the the programmer I've choose: `"USBasp"`, which I don't know if this is correct. I've used this `FTDI programmer` to program the `STM32 microcontroller` and the programmer was `"Serial"`, which I don't see the very same option here.

I'm lost, what am I missing up here?

BTW I've seen this, this and this but couldn't get it fixed.

# Answer
> 2 votes
A new chip cannot be programmed in that manner until it has the Bootloader installed. The Bootloader starts after a reset and monitors the serial interface to see if something is attempting to download code via the serial port.

Selecting a Programmer has no effect on serial download, that only comes into play when Programming via the SPI pins SCK/MOSI/MISO/Reset/Power/Gnd.

Your "design" needs a couple more parts: 0.1uF caps between VCC and Gnd, and AVCC and Gnd.

The Cryslal and 22pF caps could also be a lot closer to the device - like right next to it.

I can't read the FTDI markings, so I can't tell if you have Rx and Tx swapped there.

---
Tags: arduino-uno, programming, atmega328, avrdude, ftdi
---


title: 3.3v pin on a 5v Pro Micro?

text:
# Question
Title: 3.3v pin on a 5v Pro Micro?
I have a arduino pro micro that runs on 5v. I also have a Max4466 that needs 3.3v, however the pro micro doesn't seem to have a 3.3v VCC. Is there any way to attach the max4466 to the Board?

# Answer
> 1 votes
You need to add an external 3.3V voltage regulator. You can get these quite cheap on eBay (etc) as a module - some even come in a breadboard friendly format.

Power it from the 5V from the Arduino, then power your MAX4466.

However, the MAX4466 can run at up to 5.5V, so I fail to see why you think you need 3.3V.

---
Tags: power, arduino-pro-micro, voltage
---


# Question
Title: TSX0108 logic level converter not working
Am trying to setup logic level converter with arduino for eps8266 WiFi module. Am using this logic level converter but it’s not working not sure what am doing am not getting any output.

My circuit

```
Red wire : 3.3v power source
Orange wire : 5v power source
Blue wire : ground.
Yellow wire : arduino TX1 on B2
White wire : output on A2

```

**Multi meter it red wire : 3.3 v showing on display**

**Multi meter it orange wire : 4.68 v showing on display**

**Multi meter it yellow wire : 4.36 v showing on display**

\**Multi meter it white wire : no voltage showing on display ??? \**

Update : have set OE pin to enable and swapped red and orange. Still no output for yellow wire

# Answer
> 1 votes
When the output-enable(OE) input is low, all outputs are placed in the high-impedance (Hi-Z) state. You must connect the OE pin to logic high to enable the outputs.

---
Tags: arduino-uno
---


# Question
Title: Non-blocking incrementation with single button pressure
I am looking for a way to increment a variable by one each time a button is pressed. Current approach is the following :

```
    if (redButton.isPressed())
    {
        a++;
        delay(100);
    }

```

`isPressed()` just return true if the pin state is HIGH.

`delay(100)` is used to compensate the small amount of time the button is being pressed. Otherwise `a` would be incremented multiple times in a single press. But it's blocking behavior, my program can't do anything else during that delay.

In short I'm looking to add a method in my Button class to detect if the button "has just been released".

# Answer
In your approach a button press will be detected every 100ms when you just keep the button pressed. So you have to set a flag when the button is pressed. When the button is **not** pressed while your flag is set, that's the event you're looking for. In this way you can detect both a button press and a release respectively. As @JRobert mentioned, there still has to be an amount of time between two calls to such a routine to provide some button debouncing.

```
bool pressed_flag=false;
bool button_timestamp=millis();
uint16_t button_period=100;

if(millis()-button_timestamp>button_period){
  button_timestamp=millis();
  if(redButton.isPressed() && !pressed_flag){
    // button has just been pressed
    // you can do sth. here
    pressed_flag=true;
  }
  else if(!redButton.isPressed() && pressed_flag){
    // button has just been released
    // you can do sth. here
    pressed_flag=false;
  }
}

```
> 1 votes

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


title: How to read a text file line by line

text:
# Question
Title: How to read a text file line by line
I am making an LED controller that reads instructions from a text file on my computer. I need to get the arduino to read this text file line by line and put each line into the appropriate variables. I'm using a sparkfun pro micro which is a knock off arduino pro micro. The pro micro is connected via USB

I've seen people use the SD library, but I don't know if this will work for my situation because I am reading directly from the computer and not an SD card. Is this the correct approach, or is there an additional/alternate library that I need to use?

# Answer
> 1 votes
What you can do is:

* Read character by character and copy it to a temporary buffer of the maximum length of one line.
* When you parsed an end of line symbol, you start parsing the (complete) line in the buffer.
* In this line parsing (preferably a separate function), you parse the line, using string to type conversion functions, like `atoi` (string to an inter) etc. Also you can use the C function `strtok` to split the string based on a symbol (e.g. comma).
* After parsing the line, clear the buffer (you already processed it), and continue filling the buffer again until it is full.
* Don't forget to check for end of file.

# Answer
> 0 votes
The Arduino cannot read data on the PC.

Instead the PC has to send the data to the Arduino, and the Arduino has to parse (interpret) that data.

You need two things:

1. A piece of software running on the PC that sends the file contents to the Arduino over serial
2. Software on the Arduino that accepts the stream of data coming in over the serial port and does something with it.

It is no different to handling commands that are manually typed by someone using the Serial Monitor - it's just they tend to come in a lot faster when being sent by the PC from a file.

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


# Question
Title: Serial connection two devices two power supplies
I'm trying to connect an ESP32-CAM to a 3d printer using a serial connection. When powering the ESP from the 5V rail on the 3D printer(and using 3.3V zener diodes between tx, rx & gnd), everything works fine. The ESP expects 3.3V on the serial pins, hence the diodes.

circuit diagram

Common ground not shown.

Then when I try to run the ESP32 from its own 5v power supply, I cannot establish a serial connection, regardless of whether I connect the gnd from the 5v from the 3d printer with that of the ESP power supply. In fact, the ESP doesn't function then.

Any suggestions?

PS: the ESP has its own power since it should trigger a relay to cut power to the printer.

# Answer
> 1 votes
The 3.3V zener diodes are connected backwards. The anode should be connected to ground and the cathode (banded end) to the GPIO signal. Zener diodes work in reverse bias...as you have them connected now they are forward biased and will clamp the signals to about 0.7V.

The zener diode on the line for data transmitted at 3.3V to a 5V input doesn't do any good. You need to **increase** that signal voltage to a proper 5V logic level. The best thing to do would be to get rid of the zener diodes altogether and use a proper logic level converter.

Also, you really should have resistors between GPIO output pins and the zener diodes, to limit the current through the zeners when the GPIO pin is at 5V.

---
Tags: serial, esp32
---


# Question
Title: How do I send multiple variables via stream to Unity?
So I currently have this for arduino.ino:

```
Serial.println(Variable1);

```

that does this in Unity:

```
string variable1 = stream.ReadLine();
float x = float.Parse(variable1);
transform.Rotate (0, -x/1000, 0);

```

My question is; How would I send 3 variables from the Arduino to Unity so I can put each value into the `transform.Rotate` function at once?

For example in pseudocode:

```
Arduino.ino
send(Variable1, Variable2, Variable3);

Unity
transform.Rotate(Variable1,Variable2,Variable3);

```

I hope this makes sense. Thank you.

# Answer
What you need to do is define a communication scheme/protocol. You appear to be using the Serial UART via USB.

Your first example has a simple scheme its simply the ASCII representation of the variable followed by a newline. i.e. :

```
float x = 123.45;
Serial.println(x);

```

this simply outputs

```
"123.45\n"

```

you could continue this pattern

```
float x, y, z,
... // assume x, y and z have values in them
Serial.print(x);
Serial.print(' ');
Serial.print(y);
Serial.print(' ');
Serial.println(z);

```

this outputs something like:

```
"123.43 23.34, 42.24\n"

```

then your receiving code will do do something like

```
string line = stream.ReadLine();
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
float x = float.Parse(parts[0]);
float y = float.Parse(parts[1]);
float z = float.Parse(parts[2]);

```

but this is very inefficient, since the arduino needs to convert the float to an ASCII string, then transmit that over the serial port, where its read on the other side, then parsed back into a float. One doesn't need to do this, you can do in binary, it won't be human readable, but it will use much less transmission space.

```
float x, y, z; // assume these are valid
Serial.write(&x, sizeof(float));
Serial.write(&y, sizeof(float));
Serial.write(&z, sizeof(float));
// n.b. one should write an end of message here or something else to frame the data

```

and on the other side

```
byte[] data = new byte[12];
stream.Read(data, 0, 12);

float x = BitConverter.ToSingle(data, 0);
float y = BitConverter.ToSingle(data, 4);
float z = BitConverter.ToSingle(data, 8);

```

You will generally also want some way to frame the data, so you might want to start with a simple message header, i.e.:

```
struct head
{
  int length;
  int code;
};

```

and you write it like:

```
head header; //assume this is valid
Serial.write(&header, sizeof(header));

```

then you can write you message.

You might also want to implement some sort of checksum, so you can verify that you got the data correctly.

You can create multiple message structures this way, i.e.

```
struct vect3d
{
  head header;
  float x;
  float y;
  float z;
}

```

just fill and send

```
vect3d v3;
v3.head.length = sizeof(vect3d); // one could subtract sizeof(head) off so the reader can always read the first 8 bytes and read the rest of the message from there
v3.head.code = VECT3D; // assume this is defined somewhere
v3.x = 123.5;
v3.y = 23.4;
v3.z = 42.24;

Serial.write(&v3, sizeof(v3));

```

On the other side one would read in the first 8 bytes, then read in the rest of the message based on the length, and parse it based on the code.
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: MPU6050 Gyroscope does not give reliable readings
It gives reliable readings for a couple of seconds and then it becomes unreliable.

My arduino code is this:

```
#include<Wire.h>
const int MPU6050_addr=0x68;
int16_t AccX,AccY,AccZ,Temp,GyroX,GyroY,GyroZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void sendVector(float x, float y, float z) {
  Serial.print(x, 4);
  Serial.print("|");
  Serial.print(y, 4);
  Serial.print("|");
  Serial.println(z, 4);
}

void loop(){
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU6050_addr,14,true);
  AccX=Wire.read()<<8|Wire.read();
  AccY=Wire.read()<<8|Wire.read();
  AccZ=Wire.read()<<8|Wire.read();
  Temp=Wire.read()<<8|Wire.read();
  GyroX=Wire.read()<<8|Wire.read();
  GyroY=Wire.read()<<8|Wire.read();
  GyroZ=Wire.read()<<8|Wire.read();
  //Serial.print(AccX);
  //Serial.print(AccY);
  //Serial.print(AccZ);
  //Serial.print(" || Temp = "); Serial.print(Temp/340.00+36.53);
  //Serial.print(" || GyroX = ");
  //Serial.println(GyroX);
  //Serial.print(" || GyroY = ");
  //Serial.println(GyroY);
  //Serial.print(" || GyroZ = ");
  //Serial.println(GyroZ);
  sendVector(GyroX, GyroY, GyroZ);
  delay(100);
}

```

The above sends data to unity which controls an object. The object works with the gyroscope and then due to the random readings it rotates quickly and randomly.

# Answer
> 1 votes
I don't think you have given enough information to help you debug this, but i can try to give some advice:

# First verify that the chip works correctly

Use the arduino plot monitor, and a sample program, to see the behavior of the chip and values over time; make sure its not a problem with the chip

# Second verify that you are interpreting the values correctly

The MPU6050 outputs 16-bit data, but doesn't have 16-bit resolution, this means that the lower bits of the data are random, meaningless noise, and should be ignored/discarded.

If you are assuming that all 16 bits contain valid data, and your code is sensitive enough to be affected by those lower bits, then you will see unstable random data.

# Third consider other (possible) obstacles

Try increasing the serial BAUD rate, you may be taking too much time and causing problems that way.

Maybe you are getting out of sync while reading from the chip, if there is additional data being sent, you could could build up a backlog in the buffer, and start interpreting messages incorrectly because you are reading part of one and part of another. Try using a library to talk to the chip, one that other people have used and is known to work; this could remove bugs you are blind to, or bugs that everyone will run into, but they have already been fixed in the library!

---
Tags: arduino-mega, mpu6050
---


# Question
Title: Arduino is incorrectly reading serial input from C# program
I am trying to create a program to operate my arduino based LED controller. I'm pretty sure that my C# program is outputting to serial port correctly as I double checked the output in Debug.WriteLine(). The program is supposed to send information to the arduino in the following format (newlines included):

```
mode
number of colors
blend speed
beats until color change
Red   <---
Green <---
Blue  <---
Brightness <---

```

the last 4 are the only ones that matter for now as I am trying to get the LED's to show up one solid color first before worrying about other modes or patterns. The debug writeline loop output of my last test looks like this

```
1
1
0
1
209
255
255
219

```

This should be translating to the relevant arduino variables the same way but instead, I only get white light that seems to randomly brighten or darken when I mess with the color/brightness sliders

My code for the arduino is below. I am very new to this so it's probably not even close to right. getData() at the bottom is the function that most likely is the culprit, but I'll put the rest in just in case:

```
#include <SPI.h>
#include <Adafruit_DotStar.h>

#define NUMPIXELS 60

Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DOTSTAR_BRG);

// Variables
int mode;
int numColors;
int fadeSpeed;
int BBCC;
int R;
int G;
int B;
int Bright;
String buff;

void setup() {
  strip.begin();
  strip.show();
  //Serial.begin(9600);
}

void loop() {
  getData();

  if (mode == 1)
  {
    //strip.setPixelColor(0, R, G, B);
    strip.setBrightness(Bright);
    strip.show();
  }
}

void getData()
{
 // if (Serial.available() > 0)
 // {
    buff = Serial.read();
    int result = buff.toInt();
   mode = result;
   if (mode != -1)
   {
    buff = Serial.read();
    int result = buff.toInt();
    numColors = result;
    buff = Serial.read();
    result = buff.toInt();
    fadeSpeed = result;
    buff = Serial.read();
    result = buff.toInt();
    BBCC = result;
    buff = Serial.read();
    result = buff.toInt();
    R = result;
    buff = Serial.read();
    result = buff.toInt();
    G = result;
    buff = Serial.read();
    result = buff.toInt();
    B = result;
    buff = Serial.read();
    result = buff.toInt();
    Bright = result;//Serial.read();
    strip.setPixelColor(0, R, 0, 0);
    //strip.setBrightness(Bright);
    strip.show();
   }
   else
   {
    strip.setPixelColor(0, R, 0, 0);
    //strip.setBrightness(Bright);
    strip.show();
   }
//  }
}

```

# Answer
Your Serial receive code is not correct in some ways:

1. You should only read from Serial, if there is really something to read. For the first read, that is not the problem, since you checked against the return value being -1 (which is the return code for "there is no new data in the buffer). But after that, you read without ever checking, if there is something to read. You need to understand, that the data is really send serially. The bytes come in one after another and there is no concept as messages on the Serial interface (which is actually called UART in non-Arduino environments). More over, there might be small pauses somewhere in the transmission, since you cannot foresee, when exactly the PC will send the data (the PC has a bunch of other tasks to do, too). So it might be, that you have received one byte, which will lead you into the `if` statement, but the rest of the data will arrive later. All data is then read as -1, since there is no data in the buffer.

You have to check, if there is actually data to read, before reading. This can be done with `Serial.available()`. It will return the number of new data bytes in the buffer. For example, if you want to read 8 bytes, you should wait, until at least 8 bytes are inside the buffer by using `if(Serial.available >= 8)`.
2. You are sending the data from the PC as ASCII encoded text. That means, that every number above 9 consists of multiple data bytes. The 4 values, that you are interested in, are all over 200, which means, that you need to read 3 bytes to get them. But you only call `Serial.read()` once for every value. That will give you the first digit, which is a 2 for all values in the shown data. More over, since you only read 1 byte, where there is the whole number (which may be multiple bytes) plus 1 or 2 bytes for the new line (depending on the chosen line ending `\n` or "\n\r"), The whole reading gets misaligned to the data structure. Now the read data (if there is any) is also dependent on how much data was send for the values before.

Keep in mind, that with ASCII encoded text, you may need multiple `Serial.read()` calls to actually read a full number. I will describe the way to go here in the next point.
3. As I already mentioned above, there is no message protocol on the Serial interface. Lost data would lead to misalignment and thus garbled data. But you can impose an own protocol onto the Serial stream of data. It is a good practice, to first receive a full message (maybe with multiple data values inside it) and then process it. For that I would suggest a new data structure

```
mode|number of colors|blend speed|beats until color change|Red|Green|Blue|Brightness\n

```

The new line is here realized only with a newline character (`\n`). The values are separated with a vertical dash. You should put an `if(Serial.available()>0)` into your loop function. Then inside that if statement, you read one character and add it to a buffer. If you read the `\n` character, you start to process the buffer. You can then convert one value after another from the buffer and save them into variables. After that, you clear the buffer. You can see this style in the `SerialEvent` example, that comes with the Arduino IDE. You should also read Majenko's blog article about reading the Serial interface on the Arduino.

---

That said, you should be cautious with using `String` object on the Arduino. Sure, `String`s are convenient, but they dynamically allocate the needed memory during the runtime. On microcontrollers, which normally have very limited RAM memory, that can lead to heap fragmentation (heap is the memory area for dynamic memory allocation). When using `String` objects, the underlying buffer get's often recreated. As buffers get allocated and deleted later, that can lead to small memory areas, which are unused, but to small to actually be used by the buffer. You can fill up your RAM very fast with that.

It is better to not use `String`, but directly a `char` array with a fixed length. Majenko also wrote an article about the `String` problem: The Evils of Arduino Strings
> 3 votes

# Answer
First off this is **NOT** how to read from the serial USART!

```
buff = Serial.read();
int result = buff.toInt();

```

`Serail.read` returns a single byte, you are treating it as a string, then trying to parse it; you will never see anything other than 0-9 if your lucky (its very unlikely that buff contains a valid string, chances are it will just keep going till it finds a \0, and return some random number, or just fail.

EDIT: It seems I was mistaken, the 'read()' returns an int, nominally only a byte is returned, but a 16-bit -1 (0xffff) is returned for an error; the documentation could be clearer here.

~~Second the arduino serial library has a huge flaw, -1 is used as a failure to read, but -1 (i.e. 255) could be a valid piece of data, this makes the return value useless, as you don't know if 255 is the correct value, or an error. The only way around this is with `Serial.available` so you must use this to control your code or you won't know whats going on.~~

Finally, you can write binary data in c# with `.Write(byte[] ...)` and then read it in binary back, so you don't have to parse it.
> 0 votes

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


# Question
Title: ESP8266 (Huzzah Feather) I2C scanner finds nothing
I am trying to address an I2C device on my Huzzah Feather (Adafruit) ESP8266, but the I2C scanner tool does not detect anything. All is sufficiently powered and quadruple checked the wiring.

Is there something I am missing for this board in regards to I2C connections?

I've had no issue on an Arduino, which uses the 2 pins on the Analog rail for I2C...

The Huzzah has no Analogue But the one pin, regardless, Huzzah Feather has different (still pin 4 & 5 tho) I2C, and not via A0 A1 like on the Uno.

Do I need to dig deep and change some pin configurations for the Huzzah?

Thought I would ask before wasting more time on trial and error experiments.

**Update Note:**

I failed to mention there is a Feather Neopixel board (4x32) hard soldered to the board. Which I suspect is not the culprit as this issue also persists on same board without the neopixel shield attached.

**Update**

The soldering job was good, but discovered a faulty wire. This allowed the I2C scanner to detect the i2C controller (LCD2004) at the address of 0x3F...

I checked with a I2c LCD library example, and I don't get any characters to come up... This is the same with both Huzzah Feather boards, one with Neopixel shield and the other is bare.

# Answer
This particular issue was due to a faulty wire on the I2C bus. I replaced the wire and I was able to scan and get an address to the I2C LCD controller.

I still cannot get text to the LCD. I will start a new question for that.

EDIT:

Upon scrapping my I2C\_LCD\_DISPLAY library, I downloaded one that was linked in a ESP32/8266 tutorial for the LCD, and finally got it working.
> 1 votes

---
Tags: feather
---


title: How can I program an ESP 10 module

text:
# Question
Title: How can I program an ESP 10 module
I buy an ESP-10 module and I want to upload custom room to its flash. The problem is that there is no way to access GPIO 0 pin! Is there some way around it to upload custom room without connecting GPIO 0 to the ground? How in the earth should I program it without this pin? here is an address to supplier's page which contains schematic and some other details. https://www.tindie.com/products/George/esp8266-esp-10-module/#product-description

# Answer
You can't. Not without physical modification to the PCB itself (remove the chip, scratch off a pad and trace, replace pad with fine enamelled copper wire tinned at the end, replace chip). All you can use is whatever firmware is currently installed in the module.
> 1 votes

---
Tags: esp8266
---


title: led chaser fill color effect

text:
# Question
Title: led chaser fill color effect
Please help. I am learning a lot about Arduino. Most all in lightning. I am a newbie. I play with nano and LED ws2812 and use fastled library.

What ask is to make effect like fill effect. For example with larson scanner/chaser.

```
for (int i = 0; i<NUM_LEDS; i++)
{
  leds[i]=CRGB::Red;
  FastLED.show();
  leds[i]=CRGB::Black;
  delay(50);
}

```

From that code above how to make LED stop and lit up and loop again and stop and lit up. I want every LED stop the LED lit up even LED looping start again from first LED. It like this:

> 10000 01000 00100 00010 00001 10001 01001 00101 00011 10011 01011 00111 10111 01111 11111

# Answer
> 1 votes
You need two counter for this, one to keep track of how far the LED bar is filled, and one about the current 'running' LED to eventually 'touch' the LEDs which are already moved to the right.

Every led (currentLed) will run from index 0 until the last filled index, while the last filled index is decreased with 1 after every loop.

(note: I haven't checked the code).

```
// Fill from the right, thus count backwards.
for (int filledLedIndex = NUM_LEDS; filledLed >= 0; filledLed--)
{
   // Now let a LED run from 0 upto filedLedIndex;
   for (int currentLed = 0; currentLed < filledLedIndex)
   {
      // Make previous LED black
      if (currentLed > 0)
      {
         leds[i - 1] = CRGB::Black;
      }

      // Make current LED red
      leds[i] = CRGB::Red;

      // Show.
      FastLED.show();
      delay(50);
   }
}

// Clear all LEDs.
for (int led = 0; led < NUM_LEDS; led++)
{
    leds[i] = CRGB::Black;
}

FastLED.show();
delay(50);

```

---
Tags: programming, arduino-nano, led
---


title: use of spec sensor in arduino uno

text:
# Question
Title: use of spec sensor in arduino uno
i have been trying to use NO2 spec senor in arduino UNO. how to write the code for it to get the output in terms of 'ppm' and how to give connection.with the helo of cross-sensitivity given in datasheet how to detect the interference gases from this sensor itself..the datasheet URL:

https://www.spec-sensors.com/wp-content/uploads/2016/10/3SP\_NO2\_5F-C-Package-110-508.pdf

# Answer
> 2 votes
In the specification sheet linked to in the post we find this:

> -30+/-10nA/ppm

This is a very small amount of current. The Arduino ADC is a voltage sensing device and (unless modified) has a range of 0 to the operating voltage of the Arduino. Usually 3.3V or 5V.

Converting nano Amps to that range of voltage will require additional hardware. A stock Arduino and code are unlikely to make use of such a sensor.

The conversion of such small amounts of current to voltages measurable by a stock Arduino is not trivial. And most answers do not fit into the short format of stack exchange. Here is an Engineering Design News article on the subject.

---
Tags: sensors
---


# Question
Title: Increasing range of a DC-offset signal (software)
I am trying to read a signal with a DC offset of 511 (as seen by the ADC). The signal's tiny with regards to the offset, and I'm feeding it to a library that does a Fourier transform on it. It comes from a 3.5mm audio jack with AC coupling and the offset so I can see the full signal.

How may I increase the range of the signal? I am thinking something like the input signal is (490-530) and I want an output of (400-630) or something (numbers solely for example). The issue is that I still need the resulting signal to be centered around 511 AND I don't know the exact amplitude of the input (since it varies based on volume and particular audio going in at the moment).

I can assume that the volume of the audio input is relatively fixed (I need to be able to adjust this gain later, but I'm assuming the volume will be constant at some value per time I'm running the project), so I don't need envelope-following or something, but I'm not sure how to do this even so.

# Answer
> 2 votes
You can't magic more resolution out of thin air (well, you can, but it slows down your sampling - you would "oversample" and average a number of sequential samples).

Instead you need to boost your signal *before* it gets to the ADC using an op-amp. The simplest circuit (which also inverts the signal, but you don't really care about that I suspect) is:

simulate this circuit – Schematic created using CircuitLab

That circuit will both invert the signal (if you care, just do a little bit of maths in your program to flip the signal, but for FFT you don't really care) and double the amplitude around the mid-point. The doubling is controlled by the ratio of R1 to R2 (20000:10000 = 2:1 = doubled). The mid-point offset is created by R3/R4 - you don't need to manually add your own offset.

---
Tags: analogread, analog-sampling
---


# Question
Title: Arduino Micro & Thin polymer lithium batteries
Is this battery:

> Polymer Lithium-ion Battery
>
> Model Number: PGEB014461
>
> https://www.powerstream.com/p/PGEB014461.pdf

Producing enough energy to power the following Arduino-micro project:

Battery (thin, flexible) to be worn. It will be safely encased (See below)

I would also be using a micro heart pulse sensor module:

> https://pulsesensor.com/
>
> https://cdn-shop.adafruit.com/product-files/1093/Pulse+Sensor+Data+Sheet-2018.pdf

and a transmission module

(bluetooth, WiFi, IR, etc... whichever is suggested or judged appropriate for an alpha project(Needs to be reliable for short range))

Edit: Clarifications about safety standards applied and "do not bend" comments...

> They do not have to be kept flat. The 0.5 mm cells can be flexed or bent into a cylinder, into a hat band, belt, etc.

As previously mentioned, the battery will be safely encased and will not go against these warnings...

> Do not immerse the battery in water or seawater, and keep the battery in a cool dry environment during stands by period.
>
> Do not use or leave the battery near a heat source such as fire or heater.
>
> When recharging, use the battery charger specifically for that purpose.
>
> Do not reverse the position (+) and negative (-) terminals.
>
> Do not connect the battery to an electrical outlet.
>
> Do not dispose the battery in fire or heat.
>
> Do not short-circuit the battery by directly connecting the positive (+) and negative (-) terminal with metal objects such as wire.
>
> Do not transport or store the battery together with metal objects such as necklaces, hairpins etc.
>
> Do not strike or throw the battery against hard surface.
>
> Do not directly solder the battery and pierce the battery with a nail or other sharp object.

# Answer
> 1 votes
The Arduino Micro requires 5V. It runs at 16MHz, and you can't run at 16MHz at voltages below about 4V.

To run off a 3.7V battery you need an Arduino board that runs at 8Mhz, such as the "3.3V Pro Micro" from Sparkfun.

To know if your battery is suitable for your project you need to work out the hourly average current draw. That is the proportion of "active" and "inactive" times for each of the devices (transmission duty cycle for your transmitter, sleep times for your MCU, etc). Until you know that you can't know the capacity (mAh) you need for your project to run for the desired amount of time between charges.

---

You can also drop the idea of an Arduino and branch out. A board that is probably tailor made for your project is the Adafruit Feather M0 Bluefruit LE which is designed to run from a Lithium Polymer batter (and even includes the charger) and has bluetooth built in.

# Answer
> 0 votes
In a word, no. You need to provide an Arduino Micro with either \> 6.5V unregulated into the barrel connector, or a regulated 5V supply directly to the 5V line.

You could use a buck/boost DC/DC converter to boost your 3.7V battery output to 5V and feed that directly into the 5V line on the Arduino (or better, feed it into the USB connector, since that will use the input switching on the Arduino.)

This one, for example:

https://www.banggood.com/DC-DC-3V-15V-to-5V-Fixed-Output-Automatic-Buck-Boost-Step-Up-Step-Down-Power-Supply-Module-p-1355829.html?gmcCountry=US&currency=USD&createTmp=1&utm\_source=googleshopping&utm\_medium=cpc\_bgs&utm\_content=frank&utm\_campaign=pla-elc2-us-pc-0720&ad\_id=368005069105&gclid=EAIaIQobChMI2pfb0Zj54wIVmeDICh2egQ\_iEAQYAyABEgLVgvD\_BwE&cur\_warehouse=CN

Or this one: https://www.digikey.com/reference-designs/en/ac-dc-and-dc-dc-conversion/dc-dc-smps-single-output/1592?utm\_adgroup=Converters&gclid=EAIaIQobChMIvM6-9pf54wIVxMDICh36XAxlEAAYASAAEgJsF\_D\_BwE

Or this one: https://www.adafruit.com/product/2190

---
Tags: sensors, battery, electronics, arduino-micro, electricity
---


# Question
Title: I´m trying to make a kind of videogame with Arduino UNO
it´s a school project, but I'm having some problems to create a menu selection. In the LCD, all the character are overwriting, I'm a beginer, so i dont have any idea of what i was doing wrong (ps.: sorry about my english, i'm a brazilian. Here goes the code: //A portable "atari" videogame project, including 3 games

```
#include <LiquidCrystal.h>
//define os pinos a ser utilizados no arduino uno,etc.
#define btcima 9
#define btbaixo 8
#define bttiro 10
#define menu 11

LiquidCrystal lcd(7,6,5,4,3,2);

int vel=100;
 int pxnave,pynave,pxaste,pyaste,pxtiro,pytiro;//px=posição x, py=posição y, etc
bool game1,game2,game3,vtiro;//vtiro=variavel de tiro
int pontos;
int maxpontos=15;
int vtela;
byte nave[8]={B00000,B01100,B00110,B11111,B00110,B01100,B00000,B00000};
byte asteroide[8]={B01110,B10111,B11111,B11101,B10111,B01110,B00000,B00000};
byte explosao[8]={B10101,B00010,B11000,B10101,B01010,B10110,B01101,B10011};
byte tiro3[8]={B00000,B00000,B11110,B11111,B11111,B11110,B00000,B00000};

int      line[4] = {0,1,2,3},
         line_bk[4],
         index,
         menu_number = 0;

boolean  menu_flag  = 0,
         enter_flag = 0,
         sub_menu = 0;

void readButts();
void list_menu();
void menu_select();

void setup()
{
  //--configuração do menu--
 pinMode(menu,  INPUT_PULLUP);
  pinMode(bttiro, INPUT_PULLUP);

 lcd.begin (16,4);
 //lcd.setBacklight(HIGH);--apenas para lcd i2c
 lcd.clear();
 lcd.setCursor(0,0);
 lcd.print(">");

pxnave=pynave=pyaste=pontos=pytiro=0;
pxtiro=-1;
pxaste=12;
vtela=0;
lcd.createChar(1,nave);
lcd.createChar(2,asteroide);
lcd.createChar(4,explosao);
lcd.createChar(6,tiro3);
//lcd.begin(16,2);
//lcd.clear();
game1=-false;
game2=false;
game3=false;
vtiro=false;
}

void loop(){

  if(!sub_menu)
  {
   lcd.clear();
    lcd.setCursor(1,line[0]);
    lcd.print("1) NAVE: THE GaMe       ");
    lcd.setCursor(1,line[1]);
    lcd.print("2) PING PONG       ");
    lcd.setCursor(1,line[2]);
    lcd.print("3) lula & dilma      ");
    lcd.setCursor(1,line[3]);
    lcd.print("4) Creditos     ");

  }

  readButts();

  if(game1){
    lcd.clear();
    vtela=0;

  if (digitalRead(btcima)==1){
    pynave=0;

  }
  if(digitalRead(btbaixo)==1){
    pynave=1;
  }
  if(digitalRead(bttiro)==1){
    pxtiro=1;
    vtiro=true;
pytiro=pynave;
  }
  pxaste-=1;
  desenhaNave(pxnave, pynave);
  desenhaAsteroide(pxaste, pyaste);
  if(vtiro){
    desenhaTiro3(pxtiro, pytiro);
    pxtiro+=1;
  }

  if(pxaste<0){
  pxaste=12;
  pyaste=random(0,2);
  }
  if(pxtiro>16){
    vtiro=false;
    pxtiro-=1;
  }
  if (((pxtiro==pxaste+1)&&(pytiro==pyaste))||((pxtiro==pxaste)&&(pytiro==pyaste))){
  vtiro=false;
  pxtiro=-1;
  desenhaExplosaoAsteroide(pxaste, pyaste);
  pyaste=random(0,2);
  pxaste=12;
  pontos+=5;
  if((pontos>=maxpontos)){
    game1=0;
    vtela=7;//rever
  }
}
if((pxnave==pxaste)&&(pynave==pyaste)){
game1=0;
desenhaExplosaoNave(pxnave, pynave);
vtela=6;
}

  delay(vel);

  }else{
    tela(vtela);
    if(digitalRead(bttiro)==1){
      reset1();
    }
  }
}

  void readButts()
{

   if(!digitalRead(menu))  menu_flag  = 0x01;
   if(!digitalRead(bttiro)) enter_flag = 0x01;

   if(digitalRead(menu) && menu_flag)
   {
       menu_flag = 0x00;
       list_menu();
       menu_number+=1;
       if(menu_number > 5) menu_number = 1;

   }

   if(digitalRead(bttiro) && enter_flag)
   {
      enter_flag = 0x00;
      sub_menu = !sub_menu;
      menu_select();

   }

}

void list_menu()
{
  for(int i=4; i>-1; i--)
  {
     index = i-1;
     line_bk[i] = line[i];

     if(index < 1) line[i] = line_bk[i+4];

     else line[i] = line[i-1];

  }

}

void menu_select()
{

    switch(menu_number)
    {
       case 1:
        vtela==0;
        game1= true;
        game2=false;
        game3=false;

               break;
       case 2:
            vtela==4;
              game1= false;
        game2=true;
        game3=false;
               break;
       case 3:
           vtela==5;
           game1= false;
        game2=false;
        game3=true;
               break;
       case 4:
               vtela==8;
               game1= false;
        game2=false;
        game3=false;
               break;
       //case 5: ---pensar---

    } //end switch

}
  void desenhaNave(int px, int py){
  lcd.setCursor(px,py);
  lcd.write(1);
}
void desenhaAsteroide(int px, int py){
  lcd.setCursor(px,py);
  lcd.write(2);
}

void desenhaTiro3(int px, int py){
  lcd.setCursor(px,py);
  lcd.write(6);
}
void desenhaExplosaoNave(int px, int py){
 lcd.clear();
  lcd.setCursor(px,py);
  lcd.write(4);
  delay(1000);
  lcd.clear();
}
void desenhaExplosaoAsteroide(int px, int py){
  lcd.setCursor(px,py);
  lcd.write(4);
  delay(1000);
  lcd.clear();
}
void reset1(){
  pontos=0;
  game1=true;
  vtela=0;
}
void reset2(){
  pontos=0;
  game2=true;
  vtela=0;
}
void reset3(){
  pontos=0;
  game3=true;
  vtela=0;
}

void tela(int cond){//0=jogo da nave 1=ganhou 2= perdeu 3= menu de seleção 4=jogo pingpong 5=jogo plataforma

if(cond<1){
   lcd.setCursor(3,0);
     lcd.print("Nave: THE GAmE");
     lcd.setCursor(0,1);
lcd.print("PRESSIONE START");
}
if(cond==6){
  lcd.setCursor(9,0);
  lcd.print("pts:");
  lcd.setCursor(13,0);
  lcd.print (pontos);
  lcd.setCursor(1,0);
  lcd.print("Perdeu");
lcd.setCursor(0,1);
lcd.print("PRESSIONE START");
}
if(cond==7){
  lcd.setCursor(9,0);
  lcd.print("pts:");
  lcd.setCursor(13,0);
  lcd.print (pontos);
  lcd.setCursor(1,0);
  lcd.print("Ganhou");
lcd.setCursor(0,1);
lcd.print("PRESSIONE START");
}
if (cond==3){
  sub_menu=true;
  lcd.clear();
}

if(cond==4)
{
  lcd.setCursor(3,0);
  lcd.print ("Ping Pong");
  lcd.setCursor(0,1);
  lcd.print ("PRESSIONE START");

}
if (cond==5)
{
  lcd.setCursor(3,0);
  lcd.print("Lula e Dilma");
  lcd.setCursor (0,1);
  lcd.print ("PRESSIONE START");
}
if (cond==8)
{
  lcd.setCursor(3,0);
  lcd.print("Equipe LULA Livre");
  lcd.setCursor(0,1);
  lcd.print("Obrigado por Jogar");
}
}`enter code here`

```

# Answer
Probably since you set the cursor at a position in the middle of a line, only the new text is overwritten over the old text. But if there are some characters from the previous text, those will stay.

So the easiest way is to either clear the screen (if you can do the updating of the screen from a single place), or rewrite the entire line (and probably having to add spaces before/after the text you want to write to overwrite the old text).

Some other tips:

* Write comments and variable names in English (I know it's not your mother language, but you can learn two languages at once, C and English).
* Align your code (make sure each { and } is aligned nicely; this will make life much easier and prevent mistakes.
* game1, game2 and game3 are booleans where only one can be true. For this the `enum` (enumeration) is invented. So make an enum `enum Game { game1, game2, game3 };` as a type, and declare a variable `Game currentGame = game1;`
* You use a switch statement for menu\_number, but why not for cond?
* You use a lot of text, all text also takes up precious SRAM, where you only have 2,048 bytes of. If for each string you add F in front (thus e.g. F("MENU"); this will be stored only in Flash.
> 1 votes

---
Tags: arduino-uno, programming, lcd, display, project
---


# Question
Title: Control speed of a dc motor with a 9v battery
Problem: I want to have a 9v battery that powers a dc motor. I want to control it with a bluetooth remote that has 3 buttons. 1st button is turn the motor with 1.5v, 2nd button is motor off and the 3rd button is full power (9v). Here is the problem normally I will change volt with my arduino using code, but it has a max voltage of 3.6v so I can't control the battery with the arduino. Also I would like the 9v battery to power the arduino and bluetooth module if that is possible, so I have only one battery that powers everything.

What I tried: I found a lot of different things on the internet. Pwm, Tip120 transistor, L298N and it only confuses me more I have no idea where to start. Spend 8 hours looking for stuff and no step further.

Result: I hope everything will work with a 9v battery and the bluetooth remote can switch between 3 different speeds.!\[enter image description here\]

# Answer
You have 3 problems here:

1. **Driver circuit the motor:** Since you only want to control the motors speed (not changing it's direction, where you would need a H-bridge like the L298N), a very simply driver circuit is sufficient. It can consist of a bipolar transistor or a MOSFET. The Arduino's digital output pin would set the transistor/MOSFET to conductive or non-conductive, which turns the motor on or off. The motor is connected (through the transistor/MOSFET) with the full supply voltage. For the needed circuit, you can google terms like "transistor as switch" or "MOSFET as switch". That should give you plenty of tutorials.
2. **Controlling the motor speed:** Normally the speed of a motor is not controlled through the voltage, since the speed behaves not linear with the voltage. Instead we use PWM (Pulse Width Modulation), where a squarewave voltage with a constant frequency is outputted at the Arduino's pin. To change the motor speed, you change the ratio between ON and OFF time of the pin (called "duty cycle"). So the motor basically get's turned on and off very fast. Since the motor is to slow, to follow the fast change, we are basically giving it small pushes very fast. If you only push half of the time (duty cycle 50%), the motor will run with about half the speed. In Arduino code you use `analogWrite(pin_number, x)` with `x` between 0 and 255 to output a PWM wave at the specified pin. Refer to the Arduino documentation for details.
3. **Powering the whole device:** First: A 9V block battery is actually like the worst choice for most cases (especially for devices with motors). It has a big series resistance, what means, that it cannot provide much current without dropping the voltage radically. They are meant for low-current devices. Better use multiple AA/AAA batteries in series.

You didn't state, what Arduino you actually use, but from the description, it has to be one of the 3.3V boards, like the Arduino Pro Mini 3.3V version. Most Arduino boards also have a small voltage regulator on them. The input for it is mostly marked with `Vin`. Please refer to the documentation of your Arduino board, to check, which voltages are suitable for that voltage regulator. If you don't have a voltage regulator on your Arduino or your battery voltage doesn't fit, you have to provide the power through your own external voltage regulator. You should use a switching regulator (far more efficient, than linear regulators), which can provide the needed power (depending on the Arduino and the bluetooth device maybe between 50mA and 300mA, difficult to say generally) plus a bit overhead.

You should then provide the motor with the full battery voltage, especially not through the Arduino's voltage regulator. Motors can draw quite much current. If you draw more current through a regulator, than possible, it will overheat, emergency shutdown or even burn out. If the battery voltage is not suitable, you should use a voltage regulator, that can safely provide the needed current.

---

Note: Depending on the size of the motor and it's load, you might want to add a flyback diode, that would safely let inductive reverse currents flow to ground, so that the inductive voltage is not piling up in the transistor/MOSFET.
> 1 votes

---
Tags: motor, bluetooth, battery
---


# Question
Title: Measure revolutions per second with reed switch
I'm trying to measure speed of a fly wheel with a reed switch with one magnet (1 pulse per full rotation). I have an 100nf cap connected to switch to help with debounce.

```
#include <Arduino.h>

int speedPin = 2; // switch is connected to pin 2
int ledPin = 13;

int debounceTime = 7;

long speedPulseTime = 0;
int speedPulseCount = 0;
int speed = 0;
long speedLastSample = 0;

long serialLastReport = 0;
int serialReportFreq = 40;

void speedPulse()
{
  long time = millis();
  if ((speedPulseTime + debounceTime) < time)
  {
    speedPulseCount++;
    speedPulseTime = time;
  }
}

void setup()
{
  pinMode(ledPin, OUTPUT);

  pinMode(speedPin, INPUT_PULLUP);     // Set the switch pin as input
  attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);

  Serial.begin(115200);
  Serial.println("Ready...");
}

void loop()
{
  long time = micros();
  if (speedPulseCount >= 4 || (speedLastSample + 1500000) < time)
  {
    detachInterrupt(speedPin);
    int tempSpeed = 1000000 / ((time - speedLastSample) / speedPulseCount);
    if (tempSpeed < 0)
    {
      speed = 0;
    }
    else
    {
      speed = tempSpeed;
    }

    //reset sample
    speedLastSample = time;
    speedPulseCount = 0;
    attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);
  }

  if ((serialLastReport + serialReportFreq) < millis())
  {
    Serial.print(millis());
    Serial.print(",");
    Serial.println(speed);
    serialLastReport = millis();
  }
}

```

Here the code I have so far. The problem I have it jumps around a little bit. What could I change to ensure more accurate readings?

# Answer
> 2 votes
It sounds like occasional "misses". Possible causes include:

* the magnet passing far enough from the reed switch to "only just" trigger it \[narrow the gap.\];
* the magnet's passage being too short for the reed switch/capacitor to respond \[use a wider magnet or move closer to the center of rotation\];
* Too much capacitance \[reduce it or debounce in software\];

Update:

> Would it be better to debounce in software and what would be the best way to do it.

If you have an oscilloscope available, you could look at the raw switch signal (no capacitor) to find out how long it bounces. I'm guessing that it will be around 10ms for such a small switch. If the entire \[make/break/make/break....\] sequence takes less than 50% (being conservative) of the wheel rotation time (1/max\_RPS), you can probably count the first pulse and ignore the switch for (0.5/max\_RPS), or 1/2 of the fastest rotation. You appear to be doing something like this already. If you want to be a little bit more rigorous, you might do:

```
see a HIGH;
ignore switch for debounce_time;
if still HIGH,
   count++;

```

Also, don't forget that variables shared between your Interrupt function and the main-line code need to be:

1. declared as `volatile`, to tell the compiler not to expect that this variable has the value it had last time the mainline code read it; and
2. Turn interrupts off briefly while reading or writing such a variable (if it is multi-byte) in your mainline, to prevent it being changed by the interrupt function between byte-reads/writes by the mainline.

---
Tags: serial, debounce, speed
---


# Question
Title: Ethernet.begin() conflicts with build-in LED on Arduino Nano
I have Arduino Nano "clone" which I would like to use with Ethernet ENC28J60 shield. I have noticed that when I include/use `UIPEthernet.h` library, build-in LED does not work properly. I have written the following sketch which I have uploaded to Arduino and run both *with* and *without* Ethernet shield with the same result: LED is not blinking. Once I comment out the line `Ethernet.begin(mac)`, LED starts blinking just fine.

Is there any way to overcome this conflict?

```
#include <UIPEthernet.h>

EthernetClient ethClient;

uint8_t mac[6] = { 0x90, 0xA2, 0xDA, 0x0D, 0xE2, 0xCD };

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

  // If this line is commented, LED starts blinking:
  Ethernet.begin(mac);

  pinMode(LED_BUILTIN, OUTPUT);

  Serial.println(F("setup() done."));
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
}

```

# Answer
> 2 votes
No, you can't.

The LED is on pin 13. Pin 13 is the clock pin for SPI. The ENC28J60 is an SPI device.

You either have control over pin 13, or you have SPI. You can't have both.

---
Tags: arduino-nano, led, ethernet-shield
---


# Question
Title: Control two stepper motors simulatenously?
I'm using Arduino Mega 2560, A4988 motor driver for 5 stepper motors. There are X1, X2, Y, Z, A axis, and if I control Y and Z at once, it works. But when I just change axis from Y&Z to X1&X2, only X1 stepper motor spins. X1&X2 need to move at once(simultaneously) due to they are connected in single bar.

My Arduino IDE code is,

==============================

```
const int X2step = 5;

const int X2dir = 4;

const int X1step = 3;

const int X1dir = 2;

void setup() {

    pinMode(X1step,OUTPUT);

    pinMode(X1dir,OUTPUT);

    pinMode(X2step,OUTPUT);

    pinMode(X2dir,OUTPUT);

}

void loop() {

    digitalWrite(X1dir,HIGH);

    digitalWrite(X2dir,HIGH);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    delay(1000);

    digitalWrite(X1dir,LOW);

    digitalWrite(X2dir,LOW);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    exit(0);

```

=================================================

Any suggestion would be helpful for me. Thanks.

# Answer
> 1 votes
You likely have other issues to boot based on what you said about only X1 moving, but first I suggest resolving the bug in your code. It appears to be that you have delays between your digital writes to x1, x2. And set their directions to the same.

At the very least you should be writing to X2 step every time you write to X1 step. If your wiring is *identical* and the motors are essentially attached *mirrored* on opposite sides of a shaft, don't forget to set the directions opposite before you start sending steps. (If they are on opposite sides of the shaft, one spinning counterclockwise means the other spins clockwise. You can also play wiring tricks with what coil goes where and how, but identical is simpler.)

```
digitalWrite(X1dir,HIGH);
digitalWrite(X2dir,LOW);

```

Or

```
digitalWrite(X1dir,LOW);
digitalWrite(X2dir,HIGH);

```

Then step it like

```
digitalWrite(X1step,HIGH);
digitalWrite(X2step,HIGH);

delayMicroseconds(2000);

digitalWrite(X1step,LOW);
digitalWrite(X2step,LOW);

delayMicroseconds(2000);
...

```

---
Tags: arduino-mega, arduino-ide, stepper-motor
---


# Question
Title: arithmetic operation outcome differs from the expected outcome
I am writing a function

```
void Sound_Play(int frequency,int millisec)

```

A part of this function is:

```
  counting=(millisec*frequency/1000);  //counting is type int
  Serial.println((String)"millisec="+millisec+" frequency="+frequency+" (millisec*frequency/1000)="+(millisec*frequency/1000)+" counting set to="+counting);

```

But when I call the function with millisec=500 and frequency=220, the result on the Serial Monitor is:

```
millisec=500 frequency=220 (millisec*frequency/1000)=-21 counting set to=-21

```

Shouldn't counting should be 110 instead.I tried casting the result to int but in vain. What am I doing wrong and how to correct it? Thanks! Bhuvnesh

# Answer
Once again an example to `Why should I learn C/C++ first before learning Arduino`.
The main point here is: know your data types.

Your calculation `millisec*frequency/1000` would work if it was a compile time constant that is evaluated by the pre processor. In any other case this is a runtime value and so the limitations of the datatype apply.

Unless stated otherwise I assume your variables `millisec`, `frequency` and `counting` are of type `int`. `int` has a platform specific width. On Arduino this is 16-bit. (Other platforms have other widths)

It is also signed, that is why it can hold values between -32768 and 32767. You calculation `millisec*frequency` evaluates to `500 * 220 = 110000` which is many times larger than the value that can be represented.

You can do two things:

* Use `long` which is 32-bit on Arduino. But actually I'd prefer to use a type with an obvious width. As you don't seem to need negative values I'd prefer `uint32_t`.
* If milliseconds is a constant, you can make it smarter by reducing your calculation to a division by two (or better a single right shift).
> 6 votes

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


# Question
Title: SparkFun BasicAHRS_I2C giving unstable readings
**SparkFun BasicAHRS\_I2C giving unstable readings.**

I am using the SparkFun Arduino Sketch from here.

It is giving me these results:

```
X-acceleration: 91.43 mg Y-acceleration: 249.51 mg Z-acceleration: 1042.05 mg
X-gyro rate: -0.549 degrees/sec Y-gyro rate: 0.557 degrees/sec Z-gyro rate: 1.595 degrees/sec
X-mag field: -164.35 mG Y-mag field: -240.16 mG Z-mag field: -20.73 mG
Temperature is 27.9 degrees C

```

and then the next result (when MPU9250 is still) is:

```
X-acceleration: 91.49 mg Y-acceleration: 252.75 mg Z-acceleration: 1039.49 mg
X-gyro rate: -0.076 degrees/sec Y-gyro rate: -0.130 degrees/sec Z-gyro rate: -0.008 degrees/sec
X-mag field: -175.07 mG Y-mag field: -222.24 mG Z-mag field: -27.64 mG
Temperature is 27.9 degrees C

```

Notice how the temperature has remained constant, acceleration has remained constant (although im not why there is a reading if the MPU9250 is stationary) and the mag field is fairly close. However, the Gyro values are not close.

Could I have a bad MPU9250?

I am using the Mega.

Edit: Added a complementary filter from here, however they have not added a comp filter for the z value as can be seen from my screenshot of the serial monitor:

I think this is because they have the MPU6050 and not the MPU9250. I believe the MPU9250 has the magnetometer which can be used to 'help' the drift?

How could I use the magnetometer to help counter the drift?

End goal: rotate a gameobject in unity with the MPU9250 with minimal drift and maximum accuracy.

# Answer
If you haven’t noticed the difference in the two is minuscule. For example, the change in degree is \<1. Also the acceleration is measured in g’s which is acceleration due to gravity. The data says the measures are in mg which is 0.01g. This is normal with accelerometers and all sensors when they pick up residual voltage from random vibrations or other sources of noise. It also could be with the error margin within SparkFun’s product since the product is more on the lower end of quality which once again is normal. TLDR: everything is working fine.
> 1 votes

# Answer
The values seem fine to me. Generally these MPU chips are really noisy, that is totally normal. Ti really use the data to the the current orientation, you have to use a filter to combine the data from accelerometer and gyroscope.

There are multiple possible filters, that can help. The easiest one to implement is a Complementary filter. It gives you pretty good results. You should be able to find corresponding tutorials on the web.

---

The code from your link does not use a complementary filter for the z axis. In the comment it says, that the accelerometer doesn't provide z angle data, and that is correct. Since gravity always goes down, you cannot distinguish the angles around that axis.

But - as you already stated - you can use the magnetometers data for this. But you will need the inclination angle of the earths magnetic field (the angle between ground and field vector). You can google the inclination angle for your place and use it as constant. But most likely you will want to use the device inside of buildings. The magnetic field can be very disturbed there due to much steel nearby. Thus it is better to do a calibration step before use, while the device lies flat on the ground.

When you have calculated the angle around the z axis from the magnetometer data, you can use it in a complementary filter, like it was done in the linked code with the accelerometer data.

Note: Due to all the steel, the inclination angle does not have to be constant, when moving around in a building. So this is better for use inside a small space range.
> 1 votes

---
Tags: arduino-mega, gyroscope
---


# Question
Title: What is the maximum power consumption of the Arduino Nano 3.0?
What is the maximum power consumption (in mW) of the Arduino Nano 3.0, when it is running in its default state (at 16MHz, no LEDs removed) and powered by an external regulated 5V supply so it bypasses the built in voltage regulator?

This will give us an upper bound on the power consumption of the Arduino Nano that can be used during estimates.

# Answer
> 15 votes
Well, it depends on what you have attached to the Arduino. If you are using the pins to do things you will definitely require more current.

If you **ONLY want to power the Arduino**, then I calculated what I think it should be below. (You should also check with someone who owns this device for an experimental value, and not just a calculated value. )

Based on the datasheet (fig 30-8, p 319), I would say the the processor will draw around 2.4 mA at 5 volts.
http://www.atmel.com/images/doc2545.pdf

The USB chip draws around 15 mA depending on several things (p 18) http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS\_FT232R.pdf

Then you have 2 LEDs with 680 ohm resistors. (Assuming 2 volt drop for each led) (5-2)/680 = around 4 mA per led.

So depending on how much you use the serial port, and the LEDs I would guess around (2.4 + 15 + 4\*4) = 33.4 mA

33.4 mA * 5V = 0.167 Watts

I suspect you want to know to the **total amount of power the Arduino can source**, which is a bit harder to calculate.

The pins can provide up to 200 mA. (p 303 http://www.atmel.com/images/doc2545.pdf) So 33.4 + 200 = 233.4

I would also add a 20% safety margin (around 50 mA)
So I would want a 280 mA supply, if I was going to attach the Arduino to different things.

**280 mA * 5 = 1.4 Watts**

Let me know if my numbers are way off.

P.S.: Be careful making your own supply. It is critical that the voltage be very stable. An unstable supply can/will destroy an Ardiuno. I suggest using a linear regulator, like the LM7805. or maybe the LM317

# Answer
> 1 votes
Yes, the i/o can source 40mA @ 5v (or 3v3) per pin, but the limit is'nt 40mA from each pin simultainiously but the limit is the processors dissipation. Read the 328A data sheet carefully and the truth will become clear.

# Answer
> 0 votes
From website https://store.arduino.cc/usa/arduino-nano: Each of the 14 digital pins on the Nano can be used as an input or output. They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA. Therefore i would assume maximum power consumption is 14 x 40mA x 5V = 2.8W, depends on the board effeciency %, for example let's say 80%, so input could be 3.5W, but again you rarely use all 14 pins at once as outputs hence it is way way lower than 3.5W.This is just a ballpoint figure.

# Answer
> 0 votes
"Each of the 14 digital pins on the Nano can be used as an input or output."

There are 6 analog input pins which are also digital pins, you must take those into account.

However, Note 3 under Table 32-2 of the '328P datasheet says: "Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:

3.1. The sum of all IOH, for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 100mA.

3.2. The sum of all IOH, for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 100mA.

(but ADC6 and ADC7 are analog input only, and should not be sourcing current)

So I would suggest that to keep your Nano healthy, 200mA x 5V = 1W be considered for the IO, and then the amounts noted above for the Power LED, L LED (which is driven by D13), and internal running of the chip be taken into account.

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


# Question
Title: I think I just bricked my Arduino. Any ideas how?
I think I have a short circuit in my Arduino Uno R3. The symptoms are:

* It does not seem to be responding as before.
* The orange "L" LED does not blink on boot-up, but just stays on continuously.
* If I plug in a 12V source, then the voltage between the 5V and GND pins starts out around 5V, but then starts dropping rapidly. In the meantime, the underside of the board heats up a lot. If I plug in the USB source, the voltage between the 5V and GND pins stabilizes at around 4.28V ... but again, nothing seems to work.
* After all this, I also checked continuity between the 5V and GND pins, and heard a beep. However, subsequent reading told me that this is not a reliable (or well-advised) test.

It seems like I have a short on my Arduino, right? Any idea of how this could have happened? I can only think of the following possibilities:

* I was running the Arduino off a lead-acid 12V battery. At some point, the negative terminal wire disconnected and there was some sparking at the battery when I reconnected it (the pattery was also powering other things). Could this have damaged the Arduino?
* I am using the Arduino to run 3 IR LED . To minimize wiring, I had wires these LED in series, rather than in parallel, which (at least at first) seemed to work. Is there any possibility this would have damaged it?

Thanks for any help.

# Answer
See my answer here. A 12V battery doesn't necessarily provide you with 12V any more than a 1.5V battery provides 1.5V.

See here for example. A 12V lead-acid battery may well provide 12.7V which is *out of spec* for the Uno.

See the page about the Uno.

You have too much voltage going into the voltage regulator, it tries to dissipate it, it gets hot and either shuts down or fails.

I suggested in the answer above to use a buck converter to down-convert the voltage, and my answer (which was accepted) said that "it is working like butter".
> 1 votes

# Answer
> If I plug in a 12V source, then the voltage between the 5V and GND pins starts out around 5V, but then starts dropping rapidly. In the meantime, the underside of the board heats up a lot. If I plug in the USB source, the voltage between the 5V and GND pins stabilizes at around 4.28V ... but again, nothing seems to work.

That sounds like the LDO is overheating and going into thermal shutdown.

> After all this, I also checked continuity between the 5V and GND pins, and heard a beep. However, subsequent reading told me that this is not a reliable (or well-advised) test.

If it's just a brief "pip" then it's just a capacitor charging or discharging. To qualify as a short it has to be a continuous "beeeeeeeeeeeeeeeeeeeeeee".

> I was running the Arduino off a lead-acid 12V battery. At some point, the negative terminal wire disconnected and there was some sparking at the battery when I reconnected it (the pattery was also powering other things). Could this have damaged the Arduino?

It sure could. If other things are connected both to the battery -ve and the Arduino then the power could have passed through the Arduino in many strange ways killing things internally.

Chances are it's dead, yes. It may just be the main MCU which (if it's a DIP version) you could pop off and replace (with one with the bootloader already installed). But there's no guarantee it's only that chip that's gone. The USB chips are also a common failure point, especially the cheap Chinese CH340G.

In the long run it's safer just to replace the entire board unless you've got plenty of spare components and the skills to diagnose and replace them as needed.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Possible to put the ESP8266 in bootloader mode without a FTDI?
I am trying to upload something directly to the ESP8266 using the ESP8266 IDE. I have configured the ESP8266 to communicate at 9600 using UART\_DEF and I have set the ESP8266 IDE at 9600. I see some tutorials that say to use a FTDI but I only have a Serial to TTL cable (note it even says at the bottom that it's not good for Arduinos :( ) and am making the following connections:

* ESP8266 RX - TTL cable TX
* ESP8266 TX - TTL cable RX
* ESP8266 GND - common GND
* ESP8266 VCC - External 3.3V
* GND from External 3.3V - common GND
* ESP8266 GPI0 (through a 10k resistor) - common GND
* ESP8266 GPI2 (through a 10k resistor) - External 3.3V
* EPS8266 CH\_PD - External 3.3V (sorry, that was wrong before)

However, when I upload that sketch I get an error that the board cannot be found. I have read online that the ESP has some bootloader mode that needs to be activated but haven't found great instructions on how to do that. Any advice would be appreciated.

FYI I also have an Uno if that is any help. I have communicated with the ESP8266 through the Uno before (connecting the Uno reset to ground) .

# Answer
The cable you point to is fine for programming the ESP8266. The only reason it's not "good" for an Arduino is the lack of a DTR signal to trigger a reset for you - which you can do manually anyway and still use it for an Arduino (if your reactions are fast enough).

You have no such problem with the ESP8266. Once you have it in bootloader mode it stays in bootloader mode until you tell it to exit bootloader mode.

First make sure that the ESP8266 is actually set up to run properly. That means:

* Connect CH\_PD to 3.3V, not GND, through a pull-up resistor.
* Connect GPIO0 to 3.3V via a pull-up resistor.
* Connect RST to 3.3V via a pull-up resistor.

Then for simplicity of programming:

* Connect a button between RST and GND
* Connect a button between GPIO0 and GND

To enter bootloader mode simply hold the GPIO0 button in, tap the RST button, then release the GPIO0 button. When you have successfully uploaded your firmware just tap the RST button to exit bootloader mode.

ESP8266 boards with a built-in USB interface usually use *both* the DTR *and* the RTS pins to control both those buttons virtually. That's somewhat complex to arrange for an external USB to TTL UART adaptor, so it's simpler to just press the buttons manually.

---

Here's a link to a website that details the circuit and operation using an ESP-01 as an example.
> 1 votes

---
Tags: arduino-uno, esp8266, ftdi
---


# Question
Title: Wifi module is not sending the data properly
I wrote a programm in c++ for Arduino Uno which is connected to a wifi module (ESP8266) and sends the calculated data to a server through wifi-Module with a http post request.

The problem is that the programm sends the data only 2 times throuth http and then it stops. I mean it goes to the loop but the http-send-request is not successful.

here is my program:

```
#include <MySignals.h>
#include "Wire.h"
#include "SPI.h"

unsigned long currentMillis;

const unsigned long period = 10000;

int a=1;

void setup()  {

Serial.begin(115200);

MySignals.begin();
 void httpBase(int); //Enable WiFi ESP8266 Power -> bit1:1           >      bitSet(MySignals.expanderState, EXP_ESP8266_POWER);
 MySignals.expanderWrite(MySignals.expanderState);

 MySignals.initSensorUART();

 MySignals.enableSensorUART(WIFI_ESP8266);   delay(1000);

// Checks if the WiFi module is started   int8_t answer =
sendATcommand("AT", "OK", 6000);   if (answer == 0)   {
MySignals.println("Error");
// waits for an answer from the module
while (answer == 0)
{
  // Send AT every two seconds and wait for the answer
  answer = sendATcommand("AT", "OK", 6000);
}   }   else if (answer == 1)   {

MySignals.println("WiFi succesfully working!");

if (sendATcommand("AT+CWMODE=1", "OK", 6000))
{
  MySignals.println("CWMODE OK");
}
else
{
  MySignals.println("CWMODE Error");

}

//Change here your WIFI_SSID and WIFI_PASSWORD
if (sendATcommand("AT+CWJAP=\"********\",\"****\"",
"OK", 20000))
{
  MySignals.println("Connected!");
}
else
{
  MySignals.println("Error");

}   }

 }

void loop()  {

delay(10);  // wait for a second

a=a+1;

httpBase(a);

 }

 void httpBase(int gsr) {

 String data="value1="+String(gsr); //String
 data="a="+String(gsr);
 String postString="POST /ardu.php HTTP/1.1\r\nHost:
 192.168.178.36\r\nContent-Type: application/x-www-form-
 urlencoded\r\nContent-Length:
 "+String(data.length())+"\r\n\r\n"+data+"\r\n"; char* post = new
 char[postString.length()+1]; strcpy(post,postString.c_str());

 String inf = "AT+CIPSEND="+String(strlen(post)); char *info = new
 char[inf.length() + 1]; strcpy(info, inf.c_str());

 delay(1500); sendATcommand("AT+CIPMUX=0", "OK", 3000);

 //sendATcommand("AT+CIPSERVER=1","OK",1000);

 sendATcommand("AT+CIPSTART=\"TCP\",\"192.168.178.36\",80", "OK",
 2000);

 sendATcommand(info, "OK", 2000); sendATcommand(post, "OK", 2000);

 sendATcommand("AT+CIPCLOSE", "OK", 3000);

 delay(10000); }

int8_t sendATcommand(char* ATcommand, char* expected_answer1,
unsigned
int timeout) {

uint8_t x = 0,  answer = 0;   char response[500];   unsigned long
previous;

memset(response, '\0', sizeof(response));    // Initialize the
string

delay(100);

while ( Serial.available() > 0) Serial.read();   // Clean the
input
buffer

delay(1000);   Serial.println(ATcommand);    // Send the AT   command

 x = 0;   previous = millis();

 // this loop waits for the answer   do   {

 if (Serial.available() != 0)
 {
  response[x] = Serial.read();
  x++;
  // check if the desired answer is in the response of the module
  if (strstr(response, expected_answer1) != NULL)
  {
    answer = 1;
    //MySignals.println(response);

  }
}
// Waits for the asnwer with time out   }   while ((answer == 0) && ((millis() - previous) < timeout));

 return answer; }

```

the output is:

```
AT
WiFi succesfully working!
AT+CWMODE=1
CWMODE OK
AT+CWJAP="*******","******"
Connected!
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=127
POST /ardu.php HTTP/1.1
Host: 192.168.178.36
Content-Type: application/x-www-form-urlencoded
Content-Length: 8

value1=2

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=127
POST /ardu.php HTTP/1.1
Host: 192.168.178.36
Content-Type: application/x-www-form-urlencoded
Content-Length: 8

value1=3

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=127
POST /ardu.php HTTP/1.1
Host: 192.168.1
⸮⸮6⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
2

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
2

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
⸮
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE

....

```

# Answer
Hello Navid and welcome to the community. Buddy your code is extremely hard to read.

Now let me see if I can help you archiving your goals. First of all try not to use AT commands at all, you have an ESP8266, that's not just a Wi-Fi module but also a really good micro controller you can actually use, code for it (even using Arduino IDE). I would HIGHLY suggest you to use it if you wanna do POST and GET methods. AT commands do work, but they are not as reliable as they should be, and with your code written in that format, its going to be difficult to help you buddy.

Now if you are calling it a Wi-Fi "Module" I can presume it's a ESP01 you are talking about (those ESP8266 with no usb connection), you can find on the internet a few tutorials on how to upload code to them using your arduino uno's FTDI chip (basicly grounding the reset pin of your Arduino).

With that been said, hopefully you can split your code into those 2 micro controllers if you really need to use the Arduino uno, and do a few functions to trigger based on Serial communication on both sides. I know it sounds a lot of work, but trust me, that's by far the easiest and more reliable solution you will find.

And let me give you an bonus tip, next time you wanna work with Wi-Fi applications, get yourself a Wemos D1, they are small easy to use, reliable, have GPIO's as well as ADC and PWM pins, you can pretty much put your Arduino on a shelf for 4 dollars.

And please remember Navid, code syntax is really important.
> 1 votes

---
Tags: esp8266
---


# Question
Title: Is it possible to connect many (20+) SPI sensors to an Arduino Mega?
I am making a system for measuring whether or not there is vacuum present in big steel containers. They are located up to 100 meters from the control cabinet.

The question is, *how many SPI sensors can I successfully use at the same time with an Arduino Mega?*

I have two main concerns, and there are probably more things I didn't think about.

**Signal strength** The shared lines for CLK, MOSI and MISO will need to be split up at several junction boxes and led to the different sensors. Since the voltage out from the Arduino is fixed, I'm fearing instability because the signal is weaker for some sensors, has someone done something similar? What is the greatest acceptable voltage loss for these lines to an ordinary sensor?

**Processing** Will the SPI library be fine coping with this many sensors?

The refresh rate can be set to extremely low, thinking 0.3Hz.

The alternative to all this is to go for 4-20mA sensors and have a 0-5V converter circuit for each sensor, near the controller.

Any inputs would be greatly appreciated!

# Answer
> 1 votes
You can control as many SPI devices as you can set the CS line for. You can even control all the CS lines from a SPI device. A SIPO register will help a lot there.

However you are probably better off using a proxy board to actually connect to the sensors and then connecting the mega to the proxy to communicate the measurements using a connection that is more robust over long distances.

# Answer
> 1 votes
You need to drive SCK, MOSI, and 20 chip select lines long distance, and then receive MISO back long distance.

The number 20 for slaves is not a problem. Long distance and maintaining signal integrity will be a problem.

I would suggest a bussed newtwork and send serial data to/from 20 slaves (like ProMini) and let the slaves do the SPI data gathering and then pass that data back to the Master Mega in a polled fashion: #1 send your data, #1 here it is. #2 send your data, #2 here it is. Etc. Then you just need to connect up a 3 wire bus (RS485+, RS485-, Gnd) from device to device to device with termination resistors at the end of the run. Power each device seperately vs running power to all of them. Maxim has some nice tutorials on connecting up RS485.

# Answer
> 0 votes
I would recommend using multiplexer(s) for the task.

Originally from this tutorial.

Or this tutorial by Sparkfun

---
Tags: arduino-mega, esp8266, spi
---