# Question
Title: How to re-construct audio from series of analog integer input?
I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it. At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

I'm new to working with these types of break out boards, so I found an online project that I'm using as a starting point:

Streaming audio from ESP8266 to pyaudio working in Arduino IDE

I figure I start troubleshooting my popping sound issue by inspecting the UDP packets my ESP8266 code. Below is the source code I'm working from:

```
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "change this";
const char* password = "change this";
int contconexion = 0;

WiFiUDP Udp;

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

  pinMode(5, OUTPUT);  //D1 Led de estado
  digitalWrite(15, LOW);

  WiFi.mode(WIFI_STA); //para que no inicie el SoftAP en el modo normal
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED and contconexion <50) { //Cuenta hasta 50 si no se puede conectar lo cancela
    ++contconexion;
    delay(250);
    Serial.print(".");
    digitalWrite(5, HIGH);
    delay(250);
    digitalWrite(5, LOW);
  }
  if (contconexion <50) {
      //para usar con ip fija
      IPAddress Ip(192,168,1,180);
      IPAddress Gateway(192,168,0,1);
      IPAddress Subnet(255,255,255,0);
      WiFi.config(Ip, Gateway, Subnet);

      Serial.println("");
      Serial.println("WiFi conectado");
      Serial.println(WiFi.localIP());
      //digitalWrite(5, HIGH);
  }
  else {
      Serial.println("");
      Serial.println("Error de conexion");
      //digitalWrite(15, LOW);
  }
}

void loop()
{
  Udp.beginPacket("192.168.0.26", 1234);

  for(int i=0; i<1024;i++){
    int old=micros();

    float analog = analogRead(A0);
    if (analog > 255) {
      analog = 255;
    }
    else if (analog < 0){
      analog = 0;
    }
    Udp.write(int(analog));
    Serial.print(int(analog));
    Serial.print(",");
    while(micros()-old<87); // 90uSec = 1Sec/11111Hz - 3uSec para los otros procesos
  }
  Serial.print(";;;;;");
  Udp.endPacket();
  delay(5);
}

```

Notice near the bottom of the file, I print out each analog value separated by a comma, and each data packet separated by five semicolons.

Can someone suggest a way for me to re-construct these series of integers into a sound file that I can inspect via listening with my own ears? Then I can tell if the sound data being sent is complete? Or let me know if there's a better way to test if all the data packets are being sent correctly.

**UPDATE**

I tried to create a wav file by doing this:

* Take the list of all integers from `Serial.print(int(analog))` and paste it into a file. I make sure all integers are space delimited (ie. no more commas or semicolons)
* I copied the file over to a linux machine that had ffmpeg installed
* I ran the command `ffmpeg -f u8 -ar 11111 -ac 1 -i myfileofintegers -y test.wav`

When I listen to the test.wav file, I just hear a series of rapid popping noises. Not sure if I created the wav file properly?

# Answer
> I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.

You have described several problems; one needs to break big problems into small problems:

1. Sample the audio
2. Send it to another computer
3. Decode and playback the sound

> At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

This sounds like you have got your timebases messed up; it is likely that you aren't recording enough data or playing it back incorrectly. N.b. it looks like you are recording ~92ms of audio data each 'packet' and if you get a series of pops at 2hz you are likely playing less than 1/10 of a second of audio for ever 5/10 of time, so your speaker moves for 1/10th of a second then stays still for 4/10ths and repeats; this produces your 2hz popping noises.

Your code has some other problems as well:

* Serial.print() is **Slow!** Don't use it where performance matters!
* Intertwining sampling and sending
* Incorrectly scaling the analog reading
* 11.1khz can only record signals up to 5.5khz

Lets start with the audio sampling. We have some sort of audio circuitry presenting a signal to an analog input, we need to sample it regularly and uniformly! The code presented is trying to sample at 11.1 kHz, but only does so for 1024 samples before hitting a discontinuity. We do not have circuitry dedicated to this so we will have to use the ADC circuitry on the Arduino.

First thing you will want to get you sampling regular and continuous. You will want to use an interrupt on the Arduino for this. The interrupt should take a single sample from the ADC and add it to a buffer or signal the main loop to read/buffer it.

This interrupt will need to fire regularly at the sample rate or the data will be ruined.

Second the audio circuitry should prepare the signal so that it is between 0-5v with a ~2.5v bias, this will use the ADC hardware to its fullest.

so in Pseudo code:

```
// include any libs etc.
// set up variables ect.
void interupt_sample();
// register and attach interrupt
void setup() {
//do your setup etc.
}
void loop() {
// if(new_sample) add_to_buffer(new_sample);
// if(buffer_full) send_and_flush_buffer();
}

```
> 1 votes

---
Tags: esp8266, analogread, audio
---


# Question
Title: How to write a more compact ANDed conditions with if statement?
I'm working on the rfid module and found an example that do it well. But it has a long testing the 5 bytes of the rfid received bytes, and I've tried to write it in a more compact way.

I did it with a for loop, but how to AND the conditions of the if statement?

How to change this:

```
if(bt0[cnt-1] == rfid.serNum[0] &&
   bt1[cnt-1] == rfid.serNum[1] &&
   bt2[cnt-1] == rfid.serNum[2] &&
   bt3[cnt-1] == rfid.serNum[3] &&
   bt4[cnt-1] == rfid.serNum[4]){
   lcd.clear();
   lcd.print("card accepted");
   digitalWrite(green_led,HIGH);
   digitalWrite(red_led,LOW);
 }
 else{
    lcd.clear();
    lcd.print("card denied");
    digitalWrite(green_led,LOW);
    digitalWrite(red_led,HIGH);
}

```

To something like this:

```
    for(byte i=0;i<MXCD;i++){
      if(bt[i] == rfid.serNum[i%5]){
        cnt++;
      }
    }
    if(cnt==5){
      lcd.clear();
      lcd.print("card accepted");
      digitalWrite(green_led,HIGH);
      digitalWrite(red_led,LOW);
      cnt = 0;
    }
    else{
      lcd.clear();
      lcd.print("card denied");
      digitalWrite(green_led,LOW);
      digitalWrite(red_led,HIGH);
      cnt = 0;
    }

```

In this way, I did it with 'cnt' variable to count the number of successful matched bytes then test of the number is equal to 5.

Is there a better way than this one ?

Thanks for any comments or suggestions :)

# Answer
There is a standard C function for this, `memcmp()`. It performs a memory block compare and can be used like this:

```
if (!memcmp(bt, rfid.serNum, sizeof(bt))) {
  lcd.clear();
  lcd.print("card accepted");
  digitalWrite(green_led,HIGH);
  digitalWrite(red_led,LOW);
}
else {
  ...
}

```

Ref. http://www.cplusplus.com/reference/cstring/memcmp/
> 2 votes

---
Tags: rfid, loop
---


# Question
Title: Question on pin management using PCA9534PW IO Extender
There is an IO expander PCA9534PW, Arduino UNO. I don’t really understand how I can manage this expander using UNO over I2C.

I found an example, but here is the reading mode.

What I need: Set the IO0 pin to exit mode, set the HIGH / LOW level to IO0.

In the datasheet, I just realized that to enter the settings mode - you need to write Wire.write(0x03). How can I do it?

# Answer
> 2 votes
You set the pin mode by setting the configuration register.

```
Wire.beginTransmission(0x20);
Wire.write(0x03);                   // Configuration Register
Wire.write(0xfe);                   // IO7-IO1 Input, IO0 Output
Wire.endTransmission();

```

Then write the output port register with HIGH and LOW.

```
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x01);                   // IO0 HIGH
Wire.endTransmission();
delay(500);
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x00);                   // IO0 LOW
Wire.endTransmission();

```

But using a library is much easier. See, for instance, https://github.com/alotaiba/PCA9534.

---
Tags: arduino-uno, i2c, pins, c
---


# Question
Title: nRF24L01 - leaves out end characters during transmission
This is my Master's code.

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

RF24 radio(7, 8);

const byte address[6] = "00001";
char text[20] = "";
int flag;
char *p;
int i;

void print();
void read();
void rfwrite();
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setDataRate(RF24_1MBPS);
  radio.setChannel(1);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();

  flag = 0;
  p = text;
}

void loop() {

  if (Serial.available()) {
    read();

  }
  if (flag) {
    print();
    rfwrite();

  }

}

void print() {
  Serial.println(text);
  flag = 0;
}

void read() {
  p = &text[0];
  for (i = 0; Serial.available(); p++, i++) {
    *p = Serial.read();
  }
  text[i + 1] = '\0';
  flag = 1;
}

void rfwrite() {

  radio.startWrite(text, strlen(text)+1);

}

```

Slave code:

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

RF24 radio(7, 8); //ce,csn

const byte address[6] = "00001";
char text[20] = "";
int  i;

void write_to_array();
void print();
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setDataRate(RF24_1MBPS);
  radio.setChannel(1);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  while (radio.available()) {

    write_to_array();
    print();

  }

}

void write_to_array() {
  radio.read(text, strlen(text)+1);

}

void print() {
  Serial.println(text);

}

```

I edited the code and made it with an array like @Kwasmich said. But now some end characters are not getting printed. When I type `1234567890-=` into the transmitter, only `1234567890-` gets printed. When I type a new set of characters following that, the missing `=` gets printed. Also, this happens only on the second transmission after I upload the code to the Arduino. The first set of characters are received and printed correctly. How do I fix this? Will flushing the buffer help(I doubt this because the first transmission is received correctly)?

# Answer
> 1 votes
**This is not a proper solution explaining why the issue occurred in the first place but merely a workaround to anyone encountering the same problem.**

There is another function in the RF24 library called startWriting(). The description in the library was not clear about the differences between this and write(). But I noticed that the last character was missing with the use of startWriting(). So I simply changed

```
radio.read(&text, sizeof(text));

```

in the master to

```
 radio.read(&text, sizeof(text+1));

```

and voila! The code now does its intended purpose!!

# Answer
> 0 votes
You are riding on a wave of undefined behavior. sizeof returns the size of the underlying type. In your case char. Which is 1. What you really need is the propper allocated array `char text[32] = ""` and the required length of the string using `strlen(text) + 1`. +1 to also transmit the nul terminator of the string.

The maximum string Length that can be transmitted using nRF24L01 is 32 bytes. Because of the mandatory nul termination of a string you can send at most 31 characters as a valid string.

Fun fact: The same limitation of 31 characters applies to file name langths on the classic Mac OS at least up to 7.x and also on the Amiga DOS/Workbench.

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


# Question
Title: How to / is it possible to change Vendor Name in ESP8266-12E?
I am aware of that it is possible to change hostname for ESP8266 but I want to change vendor name also so that it lists my company/product name in routers/firewalls.

Is it possible?

# Answer
No. The Vendor Name is associated with the OUI. The OUI is the first three parts of the MAC address.

The OUI's are all registered with IEEE here and Espressif's entries are:

```
18-FE-34   (hex)        Espressif Inc.
24-0A-C4   (hex)        Espressif Inc.
24-B2-DE   (hex)        Espressif Inc.
2C-3A-E8   (hex)        Espressif Inc.
30-AE-A4   (hex)        Espressif Inc.
3C-71-BF   (hex)        Espressif Inc.
54-5A-A6   (hex)        Espressif Inc.
5C-CF-7F   (hex)        Espressif Inc.
60-01-94   (hex)        Espressif Inc.
68-C6-3A   (hex)        Espressif Inc.
80-7D-3A   (hex)        Espressif Inc.
84-0D-8E   (hex)        Espressif Inc.
84-F3-EB   (hex)        Espressif Inc.
90-97-D5   (hex)        Espressif Inc.
A0-20-A6   (hex)        Espressif Inc.
A4-7B-9D   (hex)        Espressif Inc.
AC-D0-74   (hex)        Espressif Inc.
B4-E6-2D   (hex)        Espressif Inc.
BC-DD-C2   (hex)        Espressif Inc.
C4-4F-33   (hex)        Espressif Inc.
CC-50-E3   (hex)        Espressif Inc.
D8-A0-1D   (hex)        Espressif Inc.
DC-4F-22   (hex)        Espressif Inc.
EC-FA-BC   (hex)        Espressif Inc.

```

The ESP8266 does not advertise the vendor. The router / other device maintains a list of OUI to Name mappings (on Linux it's stored in `/usr/share/ieee-data`) and uses them to create a pretty display.

You would need to

* Change the ESP8266's MAC address somehow
* Subscribe to IEEE and pay the relevant fees
* Be allocated an OUI
* Hope that every device in the world that would ever talk to your hardware updates its OUI mappings (which they seldom do).
> 5 votes

# Answer
You can change the MAC address in software, using `wifi_set_macaddr()`. Then you have the problem of storing that address in EEPROM and making sure every piece of code that you write for your product knows how to access it. You also need to add a step in your product release process that figures out what to store, and stores it, or you need to burn a different image in each unit that you sell. Plus you need to keep track of all the mac addresses you've ever issued so you don't issue duplicate ones. Plus, as @Majenko said, you would need to register your own OUI, which costs a few thousand dollars. So unless you plan to sell tens of thousand of your units, it's not worth doing.
> 0 votes

---
Tags: esp8266, nodemcu, espressif
---


# Question
Title: Matrix keyboard and 7segment display countdown combination
I'm working on an escape room for my university with an Arduino Mega. The last part consists of a 7segment display representing a time countdown, and the participants have to introduce the correct number in a matrix keyboard before it reaches zero.

My problem comes when for representing the seconds in the countdown, I have to use a delay, and this stops the matrix keyboard from getting the numbers.

The code I have so far:

```
char keys[4][4] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

byte rowPins[4] = { 5, 4, 3, 2 };
byte colPins[4] = { 9, 8, 7, 6 };

int pinA = 26; //2
int pinB = 34; //3
int pinC = 31; //4
int pinD = 27; //5
int pinE = 25; //6
int pinF = 28; //7
int pinG = 33; //8
int D1 = 24; //9
int D2 = 30; //10
int D3 = 32; //11
int D4 = 35; //12

Keypad mykeypad = Keypad( makeKeymap(keys), colPins, rowPins, 4, 4);

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

pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinD, OUTPUT);
pinMode(pinE, OUTPUT);
pinMode(pinF, OUTPUT);
pinMode(pinG, OUTPUT);
pinMode(D1, OUTPUT);  //Turns the first digit on.
pinMode(D2, OUTPUT);  //Turns the second digit on.
pinMode(D3, OUTPUT);  //Turns the third digit on.
pinMode(D4, OUTPUT);  //Turns the forth digit on.
}

//
void showTime(){

  digitalWrite(D1, LOW);
  digitalWrite(D2, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(D4, LOW);

 //3
  digitalWrite(pinA, HIGH);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, HIGH);
  digitalWrite(pinD, HIGH);
  digitalWrite(pinE, LOW);
  digitalWrite(pinF, LOW);
  digitalWrite(pinG, HIGH);
  delay(1000);

//2
  digitalWrite(pinA, HIGH);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, LOW);
  digitalWrite(pinD, HIGH);
  digitalWrite(pinE, HIGH);
  digitalWrite(pinF, LOW);
  digitalWrite(pinG, HIGH);
  delay(1000);

  //1
  digitalWrite(pinA, LOW);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, HIGH);
  digitalWrite(pinD, LOW);
  digitalWrite(pinE, LOW);
  digitalWrite(pinF, LOW);
  digitalWrite(pinG, LOW);
  delay(1000);

  //0
  digitalWrite(pinA, HIGH);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, HIGH);
  digitalWrite(pinD, HIGH);
  digitalWrite(pinE, HIGH);
  digitalWrite(pinF, HIGH);
  digitalWrite(pinG, LOW);
  delay(1000);

}

//Receives the chars from the matrix keyboard.
void getCode(){
   char key = mykeypad.getKey();
  if(key){
     Serial.print(key);
  }
}

void loop()
{

  showTime();

}

```

Any idea on how can I archieve this combination? Have been trying to find something similiar to a Thread, but Arduino doesn't support it.

Thanks in advance.

# Answer
> 1 votes
Try using `millis()`, it returns the number of milliseconds passed since the Arduino board began running the current program.

When you start the countdown you set a variable for a beginning time

`int millisBegin = millis(); //put this at the end of your setup() {}`.

You will also need a "border" to know when one second is over, so

`int millisBorder = 1000; //one second border`

Every time your the `loop() {}` starts over you can check if one second has passed so far

```
int millisNow = millis();
if(millisNow - millisBegin >= millisBorder){} //if one second over, do {}

```

Now I would work on the segment showing thingy. In the `{}` I would put a new variable, let's call it `counter = 4; //4 because I found 3 numbers in your sketch`. Every time the `if() {}` is being executed, you go through more `if () {}` statements, checking what number to display next.

```
if (counter == 3)
{
  //show number 3
}

if (counter == 2)
{
  //show number 2
}

if (counter == 1)
{
  //show number 1
}

if (counter == 0)
{
  //show number 0
}
counter = counter - 1;

```

At the end we take one off the counter, so the next time we enter the `if(one second over)` the number displayed will get lower

And well now there are multiple ways of doing the keyboard thingy. You can keep checking if there is a key available, and if so you can safe it as a String (most people hate strings, but I never had a problem with them to be honest).

After you've saved the key as a String you can use the `strcmp();` method to compare the string with the solution/answer `strcmp(key,answer);`. If the key and the answer are the same, it will return 1.

```
if(strcmp(key,answer) == 1)
{
  Serial.println("you made it");
}

```

# Answer
> 0 votes
Use the "blink without delay" examples in the IDE, whereby you perform an action and then basically watch the clock until and let the rest of the code run until the time elapes. For example, this blinks the onboard LED on and off, you can add to it for your keypad reading and time outputs.

```
unsigned long currentTime;
unsigned long previousTime;
unsigned long elapsedTime;
const byte ledPin = 13;
byte ledState = 0;

void setup(){
pinMode (ledPin, OUTPUT);
previousTime = millis();
}
void loop(){
currentTime = millis();  // capture the 'time' now
elapsedTme = currentTime - previousTime; // how much 'time' has passed
if (elapsedTime >= 1000){  // at least one second?
ledState = 1 - ledState; // results in 1,0,1,0,1,0 ...
digitalWrite (ledPin, ledState); // toddle the L led
previousTime = currentTime;   // set up for the next pass thru loop
// update the to display, and output it
}
// now add keypad reading stuff
}

```

---
Tags: keyboard, atmega2560, 7-segment
---


# Question
Title: Transistor amplifier to drive speaker using Arduino PWM
I have been working on a project lately which uses Arduino to play a wav file from SD card. I am using TMRPCM library which made the job very easy. But the problem is that the output sound in the speaker is very low. I am using the below single transistor circuit with my Arduino to drive 1.2W / 8ohm speaker  But the Audio output is barely audible. And i have tried many speakers with different wattage but same result.

I am wondering that is there is something wrong with the Wav file i have used for my project. It is 16000Hz/ 8 bit unsigned PCM coded. So in a nutshell my questions are

1) **How can i improve the sound obtained from my speaker by making modifications in the transistor amplifier circuit?**

2) **Was the less audible sound is due to the Wav file i have used?**

Kindly help me out, thanks in advance.

# Answer
Your amplifier arrangement is fundamentally flawed. At the moment you are "tickling" the top end of the electromagnet in the speaker - that is, you are energising it when the Arduino outputs a HIGH, and leaving it energised to de-energise by itself when the Arduino outputs a LOW. Coupled with that the fact that a PCM file outputs PWM with a carrier frequency much higher than a tone() function (and ideally above human hearing frequencies) you end up with almost nothing happening on the speaker.

The classic Class A amplifier has a different arrangement:

simulate this circuit – Schematic created using CircuitLab

With that arrangement the transistor and R1 form a simple RTL inverter. Size R1 to give the output current you need for your speaker (lower resistor = more power = more heat = bigger transistor as well). R3 and C2 remove the high frequency switching from the PWM (you could also replace R3 with a suitable inductor if you want less losses from the resistor). C1 removes the DC offset from the signal to give the full swing to the speaker and prevent excess clipping and heating.

It's not an efficient design by any means. A better "first stage" (replacing R1 and Q1) would be a high drive output logic gate (one of the CD4000 series, since it can run from 12V). I have seen AND gates used before - this also gives the benefit that you can use the second input to the AND gate as a MUTE signal. The rest (R3, C1, C2) remains the same.

The advantage of using a logic chip instead of the RTL arrangement is that it gives a more efficient "Push-Pull" output which can deliver much more current with far less heat losses.

Instead of the speaker you could connect an audio power amplifier to the output of C1 to then drive a more powerful speaker. In this case you can most likely remove the first stage (Q1/R1/R2) and drive the RC filter directly from the Arduino.
> 5 votes

# Answer
You might try an audio transformer in the circuit, following a low-pass filter to smooth the PCM signal. Here's a picture of suitable inexpensive transformers (from alexnld.com; but similar transformers are available on Ebay etc.):

The effect of the transformer in the circuit is transforming the high voltage, high impedance output of the transistor driving circuit to the low voltage, low impedance needed at the speaker. The impedance ratio of the transformers in the picture is 1300 Ω to 8 Ω.
> 1 votes

# Answer
"It is 16000Hz"

That's pretty high frequency. Is your hearing good enough for that? Many folks couldn't hear it.
> 0 votes

# Answer
First, do not get fooled by some that answer that 16kHz is a pretty high, nearly unhearable frequency. You're talking about sampling rate here. Then 16khz is pretty low end (although maybe on the edge of what's possible with the microcontroller, I don't know that off the top).

I would recommend introducing a negative supply rail to majenko's design as you can not expect a circuit to output negative voltages (i.e the negative halfwaves of an audio signal) without a negative supply...

As others already pointed out the transistor you use is a pretty poor choice. There is a transistor selection guide available here. It has an audio section, take a look at that!
> 0 votes

---
Tags: pwm, audio, transistor, tmrpcm, speaker
---


# Question
Title: Measure voltage changes with unknown baseline
I would like to monitor an audio stream and detect when it is "active" and music is playing or when it is "inactive" and is silent. What is a good way to measure when an audio stream changes state and continues to be "active?"

Each audio stream is amplified with this circuit.

Each audio stream has a different baseline voltage when it is not playing and "silent", but that voltage tends to drift slightly and change. This may be an artifact of my amp. I don't have an OScope and my multimeter is rubbish for low voltage so I can't quite pin down where the drift is coming from.

Currently, I'm using the method shown below, but that isn't as effectivewhen the audio stream is loud (e.g. has a compressed dynamic range).

Also, low volume tracks (e.g. classical music) tends have too low of a dynamic range to measure accurately and I get a lot of false "off" states.

```
#include <elapsedMillis.h>    //measure elapsed time

const int analogInPin = A0;   //Analog input pin - reads from amplifyer circuit
const int statusLight = 10;   //Digital output pin for indicator light
int sensorValueA = 0;         //Sensor reading now
int sensorValueB = 0;         //Previous sensor reading
int sensorDeltaA = 0;          //Change in sensor reading
int sensorDeltaB = 0;          //Record the last delta - useful for prefenting accidental triggering on start
int sensorThreshold = 50;      //Threshold in delta to trigger action
elapsedMillis turnOverTime;   //Timer for measuring the turnover between changes in sensor reading

void loop() {
  //measure the analog input
  sensorValueA = analogRead(analogInPin);
  sensorDeltaA = abs(sensorValueA - sensorValueB);

 //check if the data is over the threshold and switch on
  if ((sensorDeltaA >= sensorThreshold) and (sensorDeltaB != 0)) {
    turnOverTime = 0;
    powerStateA = true;
  }

  sensorValueB = sensorValueA;

  //check if no sensor data beyond the threshold has been returned within the delay window, switch off
  if (turnOverTime >= delayTime) {
    turnOverTime = 0;
    powerStateA = false;
  }

  //if the powerstate changes act acordingly
  if (powerStateA != powerStateB) {
    digitalWrite(statusLight, powerStateA);
  }
}

```

# Answer
An audio signal consists of two main components:

* An AC signal
* A DC offset

What you are interested in is the AC signal, but not the DC offset. That DC offset is what is drifting in your current model.

So you need to *AC couple* the signal. That is, couple the signal to your Arduino in such a way that only the AC portion gets through.

The simplest way is with a capacitor.

But the Arduino can't handle negative voltages, and an AC signal has negative voltages. So you need to get rid of them.

The simplest way is to add a DC offset.

But didn't we just get rid of a DC offset that we didn't want? Yep. But that was an *unknown* DC offset. If we then add in a DC offset that we do know, and is stable, then we can work with it.

Here's a very simple circuit:

simulate this circuit – Schematic created using CircuitLab

The capacitor C1 removes the existing DC offset. R1 and R2 then form a voltage divider giving 2.5V (half of 5V), which is then added to the pure AC signal.

That means that the signal now varies around 2.5V. Silence is 2.5V, and noise is other values above and below that.

Since 2.5V is half of the 5V the Arduino runs on, silence should read at somewhere near half the ADC value. That's about 512. Sound will be both above and below that value.

So if you subtract 512 from your analog reading you will effectively be subtracting the DC offset you just added, giving you a value that can be either positive or negative.

For simplicity, since you don't care whether it's positive or negative, you can then remove the sign from the number to just give you a magnitude.

```
int audio = analogRead(A0); // Get a sample
audio = audio - 512; // Remove DC offset
audio = abs(audio); // Remove sign

```

You can now compare that to a threshold value:

```
if (audio > 100) {
    // do something
}

```
> 1 votes

---
Tags: audio, analog-sampling
---


# Question
Title: Arduino Mega not receiving data from Neo-6M
I am using the trying to get data from the Neo-6M GPS module with an Arduino mega, but, the condition 'While (gpsSerial.available() \> 0' is being met. I believe this means the no bytes are being transferred from the module to the serial port but I'm not sure why. The light on the Neo-6M was blinking which means it getting a lock but not giving out the data.

```
#include <SoftwareSerial.h>

// Choose two Arduino pins to use for software serial
int RXPin = 19;
int TXPin = 18;

//Default baud of NEO-6M is 9600
int GPSBaud = 9600;

// Create a software serial port called "gpsSerial"
SoftwareSerial gpsSerial(RXPin, TXPin);

void setup()
{
  // Start the Arduino hardware serial port at 9600 baud
  Serial.begin(9600);

  // Start the software serial port at the GPS's default baud
  gpsSerial.begin(GPSBaud);
  Serial.write("123");
}

void loop()
{
  // Displays information when new sentence is available.
  while (gpsSerial.available() > 0)
    Serial.write(gpsSerial.read());
}

```

I had it working on an Uno by connecting to pins 2,3 rather then 18 and 19. I have also tried swapping the 18 and 19 pins over but still noting.

Thanks for the help

EDIT: I have the RX and TX plugged into the mega at pins 1 and 2, however, it will only print GPS information when the reset button is pressed or held down

# Answer
Not all pins on the Mega support software serial, have a read below:

https://www.arduino.cc/en/Reference/SoftwareSerial

Pins 18 / 19 are actually hardware serial pins so should not need the use of software serial.

Edit, should have noted to use hardware pins 18 / 19 you would use the constructor Serial1.begin(9600)
> 0 votes

---
Tags: arduino-mega, gps
---


title: NodeMCU ESP32s can't get Vin to work?

text:
# Question
Title: NodeMCU ESP32s can't get Vin to work?
Trying to power the board with a 9V battery through VIN. As the documentation says, it can take input voltage of 6-12 Volts, but when I connect the 9V battery, all it does is power the board on and nothing else happens.

Anyone know what I am doing wrong?

EDIT: I am stupid had the ground connected to the wrong pin thanks for the help everyone.

# Answer
> 3 votes
Assuming you are using a 9V block battery: They don't deliver the current you need for the esp32 to run/create an access point/act as a client. What you can do is connect 6 AA batteries in a row (6\*1.5V = 9V) and they will deliver a higher current than the 9V block.

---
Tags: power, battery, esp32
---


# Question
Title: Arduino New Optiboot Bootloader on custom ATMega328p board, ATMEL Studio and AVRdude
I am about to ask a kind of complex question due to the number of system parts involved and the system architecture I am planning to use.

First of all I have a tiny bit of experience with the Arduino Nano and a professional experience with C microcontroller programming.

What I would like is to create a custom ATMega328p board that *does something* and be able to update whatever firmware is running on it using the UART port.

## 1) Firmware updating

Since I am not so familiar with bootloaders, I would skip for now writing my own, so I would like to use the newest Arduino Bootloader for ATMega328p to support the firmware updates.

## 2) Custom program compilation

What I definitely do NOT want is use Arduino Sketch IDE to compile whatever application code. I am using Atmel Studio up to now for whatever bootloaderless applications I was doing and I would like to keep using that with my own project and code structure. The question here is, do I need to make any linker modifications or modifications in the code in Atmel Studio projects in order to be able to "transform" my code into application code so that can coexist with the bootloader?

## 3) Updated firmware programming

After the board is on the field running with the Optiboot bootloader and an outdated firmware, I would like to use a thirdparty software to communicate with the bootloader and update the application code. Since the optiboot bootloader used by Arduino uses the STK500 communication protocol and functionality, could I use AVRdude to communicate with the bootloader and flash the applications code only through UART?

Do you think this concept could work?

Thank you in advance. polylogic

# Answer
> 0 votes
> Since I am not so familiar with bootloaders, I would skip for now writing my own, so I would like to use the newest Arduino Bootloader for ATMega328p to support the firmware updates.

Even people who do know about bootloaders rarely bother writing their own when there is a perfectly good one with good support and good cross-platform tools available. Why would you?

> The question here is, do I need to make any linker modifications or modifications in the code in Atmel Studio projects in order to be able to "transform" my code into application code so that can coexist with the bootloader?

No. The bootloader resides at a high memory address, and your code at address 0x0000 just like normal. A fuse is set to say "Boot at the bootloader address", and another lets you set the size of the bootloader area (and thus the bootloader address).

> Since the optiboot bootloader used by Arduino uses the STK500 communication protocol and functionality, could I use AVRdude to communicate with the bootloader and flash the applications code only through UART?

Yes. This is what the Arduino IDE does. It just runs `avrdude` to communicate with the bootloader. If you turn on verbose mode in the preferences you should be able to see what the exact command is that it runs so you can replicate it in your own program or script.

---
Tags: atmega328, bootloader, sketch
---


# Question
Title: How do I fill an empty array with the values from a sensor and compare it to another given array I filled before
I'm designing a safe lock of 4 digits, but the password is in terms of colors, I have 3 colors. we are obliged to use a grayscale sensor (SKU: SEN0147).

The assignment is as follows:

Write a program on Arduino that will be used as a safe lock. Consider having 3 colors black white and grey. Black = 0, Red = 1 and White = 2.

• When the microcontroller is turned on, the safe is locked. The Serial Monitor should display: “System is online.”

• The combination lock should be saved in an array of integers called arr\_code.

• The user has 3 trials to open the safe

• The system will wait for the user to enter 4 colors. To enter a color, the grayscale sensor should be place on top of the desired color. Once ready the push button is pressed. Once released, the color is saved in another array called arr\_user\_code.

• Once 4 colors are entered, the system should test automatically if the code entered by
the user is equal to the code saved in arr\_code.

• If the wrong code is entered, the serial monitor displays: “Wrong Code. Try Again.”

• If the user enters the wrong code 3 times in a row the system is locked and a message is
displayed: “System Locked.”

• If the correct code is inserted, the Led on pin 13 is turned on.

• The combinations entered by the user should be displayed on the Serial Monitor. The Arduino program should be clear, separated into functions and documented.

The program I wrote is the following:

```
char led_pin = 13;
char pb_pin = 2;
int gs_pin = A0;
//the brightness of the flash light im using is giving 894 value so im using it for testing purpose
int arr_code[4] = { 894, 894, 894, 894 };
int arr_user_code[4];

int counter;
int Lock_Interval = 2500;

char trigger = false;
bool equal = true;
char led_state = false;

int Array_Compare(int *a, int *b) {
  for (int i = 0; i < 4; i++) {
    if (a[i] != b[i]) return 0;
    else return 1;
  }
}

void Button_Wait(int buttonPin) {//function to sense if button is pressed
  int curr_state;
  int prev_state;

  while (1) {
    prev_state = curr_state;
    curr_state = digitalRead(buttonPin);
    if (curr_state != prev_state) {
      if (curr_state == false) {
        delay(10);
        return;
      }
    }
  }
}

int GS_Value(int gsPin) {
  int gs_value = analogRead(gs_pin);
  return gs_value;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(led_pin, OUTPUT);
  pinMode(pb_pin, INPUT);
  Serial.begin(9600);
  digitalWrite(led_pin, false);
}

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

  Serial.println("System Online");
  Serial.println("Please Enter Passcode:");

  for (counter = 0; counter < 3; counter++) {
    for (int i = 0; i < 4; i++) {//uploading user array with gs values
      Button_Wait(pb_pin);
      arr_user_code[i] = analogRead(gs_pin);
      Serial.print(analogRead(gs_pin));//printing values on monitor
      Serial.print(" ");
    }

    Serial.println(" ");

    for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
      if (arr_user_code[i] != arr_code[i]) {
        equal = false;
      }
      else equal = true;
    }
    if (equal == true) {
      Serial.println("System Unlocked");
      digitalWrite(led_pin, true);
    }

    else if (equal == false) {
      Serial.println("Wrong Passcode. Try Again");
    }
  }

  /*Array_Compare( arr_user_code, arr_code);
  if (Array_Compare) Serial.println("System UNLOCKED");
  else Serial.println("Wrong Passcode. Try Again");
  */
  if (trigger == false) {//for locking the system
    Serial.println("System LOCKED!");
    while (1) {
      Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
      delay(Lock_Interval);
      return;
    }
  }
  delay(100);
}

```

I'm sorry for having a lot of functions not used and a lot of canceled algorithms by remarks but its my scratch. the issue is that my program is always giving me a wrong passcode even if its correct. Can you help me find the problem please? Thank you in advance.

# Answer
Since you are trying to distinguish tree different colours, I assume you are using SEN0147 in analog mode. That means the sensor output is between 0-5V. I do not believe that this will always be exactly a value of 894.

I suggest to change your comparison check in a way not to check if values are identical but to check if values are in a certain range. (additionally to all the answers @RamblinRose already suggested)

Here is a modification of the comparison loop of @RamblinRose with the change I propose. Check with different values of `threshold`, starting from high to lower values.

```
// returns 1 if equal, 0 otherwise.
int Array_Compare(int *a, int *b) {

   int threshold = 500;
   int temp;
   for (int i = 0; i < 4; i++) {
       temp = a[i] - b[i];
       if (abs(temp) > threshold)
       return 0;
   }
   return 1;
}

```
> 1 votes

# Answer
Your program has a lot of issues, but the main problem revolves around

```
if (trigger == false)

```

The code initializes this to false and the logic never alters the value, thus the program will always indicate "System LOCKED!"

It looks like you've mixed the variables **trigger** and **equal**. Get rid of the trigger variable and use equal.

```
if (equal == false) {//for locking the system
    Serial.println("System LOCKED!");
    while (1) {
      Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
      delay(Lock_Interval);
      return;
    }
  }

```

I recommend a different variable name to equal, such as "unlock", as it makes clear the use of the variable. Also, initialize variables such as "equal" at the beginning of loop(). Good luck.

EDIT

Your comparison check in loop() is valid. However if you have to use Array\_Compare, here is the fix.

```
// returns 1 if equal, 0 otherwise.
int Array_Compare(int *a, int *b) {
   for (int i = 0; i < 4; i++) {
       if (a[i] != b[i])
          return 0;
   }
   return 1;
}

```

Then in loop, remove your local comparison loop with

```
//for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
//  if (arr_user_code[i] != arr_code[i]) {
//      equal = false;
//  }
//  else equal = true;
//}

equal = Array_Compare(arr_user_code, arr_code);

```

I'm not comfortable writing your program for you, this is not a coding service.
> 0 votes

---
Tags: arduino-uno, programming
---


# Question
Title: Will a 12 VDC 1A Power Supply Adapter supply too much power and damage an Arduino Mega 2560?
The specs shown here:

show that it has 54 digital pins with each outputting a DC current of 20mA which makes it 54 * 20 = 1080 mA

Plus the DC current of the 3.3V Pin of 30mA we get a total of 1110mA.

Is this how one should go about doing the computations?

If the adapter is insufficient will a 12 VDC 2A Power Supply Adapter be appropriate or excessive?

Any links to read up on will be greatly appreciated as well.

Links for this question:

https://store.arduino.cc/mega-2560-r3

https://store.nerokas.co.ke/index.php?route=product/product&product\_id=567

PS: All I'm planning to connect to the board is: 'a PIR sensor (the first version not Rev B)', a '5V relay' and possibly a 'ESP8266 ESP-01S Relay Module'

# Answer
No. You have everything wrong there.

First off, a power supply does *not* provide power. It provides voltage. The device attached to it then *draws* current. As much current as it needs at any particular moment in time. The current rating of a power supply is the *maximum* that the power supply can give.

The same goes for Arduino IO and power pins: The current ratings are the *maximum* current you can draw from the pin.

Exactly what current it will draw from the power supply depends completely on what is connected to what pins, and even what calculations the Arduino is doing at the time. To get a ball-park figure of current requirements you need to know the current requirements of whatever is attached. If a device has its own power input that is the current you need to worry about. If a device is powered directly from an IO pin (such as an LED) then that forms part of the Arduino's current (which starts at about 40mA or so for the board itself).

There are many other factors to take into consideration:

* The 5V regulator on the Arduino can't give more than 1A maximum, and considerably less than that when powered from a high voltage like 12V.
* The DC jack on the Arduino is limited to 1A due to a polarity protection diode.

It is usually recommended to use a separate 3.3V regulator for an ESP8266 module (or 5V if your module has a built-in 3.3V regulator) due to the lack of power capacity in the Arduino's on-board regulators.

As a rough guestimate:

* Arduino: 40-60mA
* ESP8266: 200mA (when transmitting)
* PIR: Negligible
* Relay: 50mA when active

So you'd be looking at 300mA as a minimum. More is better. 1A should be more than sufficient. 2A would be overkill but give a big margin of error.

For everything you have there, it would be better to use a 5V power supply, not a 12V power supply.
> 2 votes

# Answer
In addition to what Majenko told you, some additional information:

The Arudino uses a linear power supply. That type of power supply works by converting all the excess voltage above the output voltage to heat. So if you feed it 12V, at 1A, it has to convert 1 amp of 12V-5V, or 7 watts of power to heat. The heat sink on the Arduino is not up to dissipating 7 watts of heat.

A linear power supply needs a little more than the output voltage. Feeding it 7.5V would be just about right. You should be able to get a full amp of 5V out of the Arduino’s power supply if you feed it 7.5V at the input, although the output voltage will probably droop some as you approach the max output, and it will get hot. Don’t put it in an airtight container.

As Majenko says, you shouldn’t add up the max current output of every pin on the Arduino to get its power requirements. A digital output line will use almost no current unless it is feeding an output that draws current. Think of the power supply as a spring-fed well, and the output as scoops that scoop water out of the well. As long as you don’t scoop water out of the well faster than it can be replace by the spring, you’re ok. If you only use a couple of small scoops, you’ll hardly take any water out of the well. (If you only have a couple of low power outputs connected, you’ll only draw a small amount of current.)

The Arduino draws a moderate amount of current all by itself. See the specs for details.
> 2 votes

---
Tags: arduino-mega, power, atmega2560
---


title: LCD displays an "A" instead of 0

text:
# Question
Title: LCD displays an "A" instead of 0
I am trying to make a timer that has a accuracy up to 1 tenth of a second. However when it is suppose to print "0", it will print an "A". For example, when printing "10", it will print "1A". This program only lasts up to seconds. Any suggestion is highly appreciated, thank you!

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
unsigned long time2 = 0;
int x = 0;
int a = 0;
int b = 0;
void setup() {
  lcd.begin(16,2);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("00:00:00:0      ");
  Serial.begin(9600);
}

void loop() {
  unsigned long time1;
  time1 = millis();
  if (time1 - time2 > 100){
    time2 = time1;
    lcd.setCursor (9,0);
    x=x+1;
    lcd.print(x," ");
  }
  if (x>=10){
    x=0;
    a=a+1;
    lcd.setCursor(7,0);
    lcd.print(a,":");
  }
  if (a>=10){
    a=0;
    b=b+1;
    lcd.setCursor(6,0);
    lcd.print(b+a);
  }
}

```

# Answer
Here is my Suggestion: In cases a clear answer could not be seen, you have to remove any weaknesses step by step to further encircle the problem. Since there is now answer for more than a month, I assume this as an appropriate proceeding.

One weakness I see in your coding is, that you are counting your values x, a, b, up to ten and you are printing them bevor reseting them to Zero, so your are printing 'x' even if it is ten. If for any reason in the further handling your display shows `HEX` values, you will end up displaying an 'A'. Change your Code so that values \> 9 are not printed out, than this weakness will be removed.
> -1 votes

---
Tags: programming, lcd
---


title: Arduino board with built-in Bluetooth

text:
# Question
Title: Arduino board with built-in Bluetooth
I would like to find an Arduino with built-in Bluetooth. I know about the HC-06, the shields and the other Bluetooth modules, but i would like to have built in Bluetooth for eliminating the risk for miscommunication on the serial port.

The official Arduino foundation did produce an board but it's retired now.

# Answer
Arduino has just released a **MKR WIFI 1010** board that includes an *ESP32* module that allows Bluetooth connectivity. It's mainly an internet of things board but it supports:

* Bluetooth low energy, BLE
* Wifi
> 1 votes

# Answer
There is this board called Bluno Its an Arduino UNO Based board with built in Bluetooth 4.0

Bluno - An Arduino Bluetooth 4.0 (BLE) Board
> 1 votes

# Answer
This is my currently favourite Arduino compatible board: https://wiki.wemos.cc/products:d32:d32

ESP32 is great: offers both wi-fi, Bluetooth and BLE connection as well as lots of GPIO. 9 GPIO's can be used as capacitive touch sensors (it has 10, but only 9 are available).
> 1 votes

---
Tags: bluetooth
---


# Question
Title: WS2812B only works while I measure the voltage
I'm going crazy, there is clearly something I'm missing here. I have a NodeMCU V3.0 and a 5V LED strip WS2812B with 10 diodes. I tested this first with a 5V 0.3A power supply, only powering 3 diodes, this worked fine.

Than I changed the power supply to a 5V 2A (Measured to 5.2V) and now the colours are way off, they even change everytime its updating, even though nothing is changed. I put my voltmeter across "D3" and "GND" and suddently the LEDs were perfect and stable.

If I remove it again, the LEDs change to random colours again, I tried pulling "D3" to ground with a 10 kOhm resistor, but this doesn't change anything.

What is going on here, why isn't it working, and why does it work with the voltmeter?

Code:

```
#include <ESP8266WiFi.h>
#include <FastLED.h>

#define LED_PIN     3
#define NUM_LEDS    10

CRGB leds[NUM_LEDS];
int R = 255;
int G = 90;
int B = 10;

//Set up MQTT and WiFi clients
WiFiClient client;

void setup()
{
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  Serial.begin(9600);

  //Connect to WiFi
  Serial.print("\n\nConnecting Wifi... ");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
  }
  Serial.println("OK!");
  pinMode(D4, OUTPUT);
  digitalWrite(D4, HIGH);
}

void loop()
{
    leds[0] = CRGB(255, 0, 0);
    leds[1] = CRGB(0, 255, 0);
    leds[2] = CRGB(0, 0, 255);
    FastLED.show();
    delay(5000);
}

```

# Answer
> 2 votes
WS2812B LEDs are 5V devices. The NodeMCU is 3V. Your first 5V supply will probably have been somewhat under 5V once the NodeMCU had taken a big chunk of the current (see Voltage Droop). This would mean that the Logic High Threshold would be within the bounds of the 3.3V output by the NodeMCU.

However, with your new high powered power supply that voltage droop will be less prevalent (added to the fact that it's measuring 5.2V), and so the logic high threshold will be higher. At, or very close to, the 3.3V that is output by the NodeMCU. That makes it rather unstable at communicating, since the logic HIGH may not always be above that required HIGH threshold.

Adding your voltmeter obviously changes that logic signal so that it stabilizes above the required threshold (the volt meter input has capacitance. That will help hold the line higher for longer).

To drive 5V devices from a 3.3V MCU you really need to add a logic level shifter, or ensure that the power supply isn't too high.

The WS2812B has a logic HIGH of 0.7 × Vdd. At 5V that's (0.7\*5=) 3.5V. That's close, but not quite there. Your original power supply was probably putting out more like 4.75V under load. That would be 3.325V for a logic high - just about manageable by a NodeMCU.

However at 5.2V the logic HIGH will be 3.675V, which is way above the 3.3V that the NodeMCU outputs.

So you either need to:

* Add a 3.3V to 5V logic level shifter, or
* Reduce your LED power input voltage to below 4.75V.

The latter can be done by adding a single series diode with a suitable current handling capacity to the VDD connection. That will (depending on the diode) drop around 0.7V taking you to about 4.5V (the actual drop usually depends on the current to a certain extent). The WS2812B will happily run from 3.5V to 5.3V.

---
Tags: arduino-ide, nodemcu, rgb-led, ws2812
---


title: Servo or motor with manual control

text:
# Question
Title: Servo or motor with manual control
I am searching for a servo or motor with the ability to easy manually controlling (turning) when power off. What is the mechanism recommend to use?

Thank you for your answer.

# Answer
> 1 votes
Motor that has no gearbox will be easier to manually turn when it is not powered. Now, I don't know what you categorize as "easy" but this info will give you a starting point.

And I don't get why the use of the "arduino-nano" and "arduino-uno" tag

---
Tags: mechanical
---


# Question
Title: .elf and .hex equivalency? (code, eeprom, fuses, and lock bits all in one)
I have all configurations (eeprom data, fuses, lockbits) of my ATMega168A together with the code in my C files. The compilation creates an elf file that I use as an all-in-one programming file for production.

Just as a tryout, I converted the elf file to hex with avr-objcopy and saw that the code and configurations are still there (why wouldn't they).

My question is, if the two files are equivalent in case of using them for all-in-one programming. Is there any critical data stripping taking place between elf-to-hex conversion that could affect the actual programming?

Also, I tried again to convert the hex file to bin and saw again the same thing but of course with zero-padding. Except for the obvious different of file size, is there any practical difference when using the bin file and the hex file? Does this padding create any problems? (For example trying to write 0 to addresses that do not exist).

Thank you in advance.

# Answer
> My question is, if the two files are equivalent in case of using them for all-in-one programming. Is there any critical data stripping taking place between elf-to-hex conversion that could affect the actual programming?

Nothing critical, but data stripping does take place. Everything that is in the HEX file is in the ELF file. That is - all the compiled machine code and data.

Basically everything that gets written to the chip is in the HEX file, and the HEX file can be created from what is in the ELF file - ergo the ELF file contains everything that is in the HEX file.

However, not everything that is in the ELF file goes into the HEX file.

The ELF file contains a huge amount more information. Mostly that information is geared towards debugging. There are things like the names and locations of all the *symbols* in the code - that is, the functions and variables, etc. There are breakdowns of all the assembly instructions grouped by source code file and line number.

None of that is relevant for the Arduino environment, but when you're using professional tools to do your development you can use them for realtime debugging and tracing of your program while it's running on the real hardware.

None of that is relevant to putting your program on the chip. It's all used by the PC.
> 1 votes

---
Tags: programming, avr
---


title: RGB not working properly

text:
# Question
Title: RGB not working properly
My RGB led is not working properly. It should light up red when the ultrasonic sensor detects more than 10 cm and green when it detects less than or equal 10 cm. It is just blinking red and green at the same time. How do I fix this?

```
#include<Servo.h>
Servo servo1;
int Motor = 3;
int tpin = 7;
int epin = 6;
int red1 = 12;
int green1 = 13;
int pos = 0;
long duration, inches, cm;

void setup() {
    Serial.begin(9600);
    pinMode(tpin, OUTPUT);
    pinMode(epin, INPUT);
    pinMode(red1, OUTPUT);
    pinMode(green1, OUTPUT);
    servo1.attach(Motor);

}

void loop() {
    digitalWrite(tpin, LOW);
    delayMicroseconds(5);
    digitalWrite(tpin, HIGH);
    delayMicroseconds(10);
    digitalWrite(tpin, LOW);
    duration = pulseIn(epin, HIGH);
    cm = (duration / 2) / 29.1;
    inches = (duration / 2) / 74;
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if ((cm > 10))
    {
        servo1.write(pos = 0);
        digitalWrite(red1, HIGH);
        delay(100);
        digitalWrite(red1, LOW);
        delay(100);
        Serial.println("\t RED");
    }
    else if ((cm <= 10))
    {
        servo1.write(pos = 90);
        digitalWrite(green1, HIGH);
        delay(100);
        digitalWrite(green1, LOW);
        delay(100);
        Serial.println("\t GREEN");
    }
}

```

# Answer
The ultrasonic sensor scans every 0,1 seconds according to your code. Problem is, sometimes you have "faulty" results. Taking into consideration the frequency of your scans + the "faulty" scans, it could be that your arduino just keeps switching between those two LEDs.

What helped me back then was to make a counter. A variable, that counts how many times in a row the distance to the object is "distance \<10cm". If the streak was interrupted, it would reset the variable. This is how a serial output would display it:

```
distance: 20cm
distance: 16cm
distance: 8cm
count: 1
distance: 9cm
count: 2
distance: 6cm
count: 3
distance: 8cm
count: 4
distance: 11cm
count: 0
distance: 12cm
distance: 20cm

```

And the moment your counter reaches a certain spot, for example the object is closer than 10cm five times in a row, then you will let an led light up

```
if(count>=5)
{
  //turn on green led (color may be wrong)
}
else
{
  //turn on red led (color may be wrong)
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Cannot set MOSI pin low even after ending SPI
I'm building a battery operated device and must shutoff MOSI pin during sleep because it leaks current through the SD card if I don't (about 400 µA).

Problem is, it won't stay off. I've looked at SPI documentation and as far as I know I just need to call `spi.end()` then set pinmode to output and finally digitalWrite LOW. I observe with an oscilloscope that it does go low upon my asking it to but only for about 1 µs (actually it goes low twice within a 5 µs time period).

I've also tried manually setting the pin low using the PORT registers and the behavior is the same... see relevant code:

```
spi.end();

//pinMode(pin_MOSI, OUTPUT);
//digitalWrite(pin_MOSI, LOW);

//Both above (commented out) and below result in the same behavior -- pin does not stay LOW

DDRB |= B00100000;            //set pin 5 as output
PORTB &= B11011111;           //set output low for pin 5

delay(5000);

```

...As you can see there is a delay to ensure that it isn't being set high by some other code.

Is there some sort of SPI interrupt that automatically sets the pin high again?

## Hardware details:

**MCU:** ATMEGA1284P; **Programmer:** Atmel-ICE

---

## **UPDATE (13-Mar-2019):**

I didn't realize that SPI is implemented by Atmel in hardware directly (see datasheet page 105):

> MOSI/PCINT13 – Port B, Bit 5 – MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI0 is enabled as a slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is enabled as a master, the data direction of this pin is controlled by DDB5. When the pin is forced to be an input, the pull-up can still be controlled by the PORTB5 bit.

I am currently chasing down this latest information and will hopefully come to a resolution soon. I will post any progress.

# Answer
> 2 votes
Indeed, SPI is hardware implemented. I was able to get the MOSI pin to operate as intended by clearing the SPI enable bit from the SPCR register as follows:

```
SPCR &= 0B10111111;  //disable SPI

```

To re-enable after sleep, I'm assuming I'll just do `SPCR |= 0B01000000;` ...pretty sure that will work but I'll update here if I have to modify my solution.

.

**Perhaps also pertinant information:**

I was using an object of *SPIClass* in *SPI.h* which is from the Arduino core libraries -- for some reason it wasn't disabling SPI in hardware when calling the `spi.end()` method, maybe because there was some other SPI object initialized by some other library. Here is the source from SPI.cpp for the *end* method:

```
void SPIClass::end() {
  uint8_t sreg = SREG;
  noInterrupts(); // Protect from a scheduler and prevent transactionBegin
  // Decrease the reference counter
  if (initialized)
    initialized--;
  // If there are no more references disable SPI
  if (!initialized) {
    SPCR &= ~_BV(SPE);
    interruptMode = 0;
    #ifdef SPI_TRANSACTION_MISMATCH_LED
    inTransactionFlag = 0;
    #endif
  }
  SREG = sreg;
}

```

The line `SPCR &= ~_BV(SPE);` should have done the job for me but I'm guessing it never got there because `initialized` was probably still non-zero.

---
Tags: interrupt, pins, spi, atmega
---


# Question
Title: How to connect Wi-Fi shield ESP-12E-ESP8266-UART-WIFI-Wireless-Shield with Arduino
I have bought this shield from ebay and now I don't know how to use it, ESP 12E ESP8266 UART WIFI Wireless Shield for Arduino UNO R3 Bouclier Sans filfr:

There are no instructions in the box or anywhere on internet for this board. The only description I found everywhere is this:

> **Description:**
>
> 1. Standard pin interface to achieve full compatibility with the pitch Arduino Uno, Mega and so on. (Unless the standard size Arduino, such as Nano, Mini)
> 2. 3.3V power supply using advanced chip (with the official expansion board power chip CC3000 same), so 3.3V Arduino board provided more accurate, so ESP8266 as official CC3000 chip work as normal, there is no gap.
> 3. It leads to a WiFi module power supply / service interface to facilitate developers to extend the power supply and maintenance.
> 4. Onboard ESP8266-12 stable industrial grade serial WiFi module, using an enhanced PCB antenna, signal better.
> 5. You can quickly switch DIP switch ESP8266-12 industrial grade WiFi stable operation mode (such as operating mode and upgrade mode) module, integrated serial chip, quickly flashing the firmware.
> 6. Built-in 5V to 3.3V TTL level converter to prevent high-pressure Arduino TTL level of the WiFi module damage.
> 7. Onboard ESP8266-12 stable industrial grade WiFi module with a metal shield, immunity to interference.
> 8. Onboard ESP8266-12 standard pitch leads to a stable industrial grade WiFi module all interfaces, enabling developers to easily develop deep.
> 9. Use stackable design, it can continue to accumulate above the other modules, easy to use.
> 10. Onboard four LED displays the status of ESP8266, namely PWR, DFU, AP, STA

What should be the board settings for this?

I am new to electronics please help me how can I connect this with Arduino.

# Answer
There are some fake Modules on eBay! Only after changing the wiring can you use them. The fake modules have the wrong text printed on it.

> Moer info $ tech

instead of

> More info & tech

But when you change the wiring you can use the shield!

The two transistors which are connected to Arduino board pin 0 and 1 have to disconnected. Also the connection to the switches 1 and 2 have to change. Then you can stack ESP-12 shield on the Arduino. You can now flash the Arduino Uno when you switch off (switch 1 and 2) With the old wiring you can't use it because the transistors are wrong connected.

The voltage divider is need for 3,3 V ESP-12 RX pin
> 3 votes

# Answer
Just to add to Andreas' answer, this is what the shield's circuit looks like at the board level:

For connecting to a 3.3v Arduino I found the neatest solution was:

* Remove all the components from the area above
* add 2 small bits of wire to short the areas shown in green above
* Switch the DIP switch so 1&2 are towards 'ON' (to connect serial to D0/D1) and 3&4 are 'OFF' (to disable the bootloader)
* Use with your Arduino on D0/D1 at 115200 baud

(You *may* have to flash you own ESP8266 command firmware using the debug port and a USB-TTL converter, in which case setting 3&4 to 'ON' and resetting the ESP8266 will stick it into bootloader mode. If you're doing this you can also send `AT+UART_DEF=9600,8,1,0,0` to put the ESP8266 into 9600 baud mode permanently if you're using an Arduino that can't handle the higher baud rates)
> 2 votes

# Answer
Same Shield here, the most useful guide I've found is https://www.espruino.com/arduino-esp8266

The DIP switches are:

```
Switch  Function
SW1 Connect ESP8266 TX to pin D0
SW2 Connect ESP8266 RX to pin D1
SW3 Enable bootloader mode
SW4 Use DFU LED to show serial activity (?)

```

For connection to the Arduino, just stack the shield over the Arduino board.
<sub>(source: robotshop.com)</sub>
> 1 votes

# Answer
A search on the designer's name turned up a few posts by people working with this board. This post was the most useful one I found. I don't have this shield and haven't tested this poster's instructions, but it seems worth trying:

> Hi! Finally back here, more enlightened! :D I have finally done some stuff with the 8266 shield. I just wanted to share it with you all. Since I know I wanted all this before I started. I write all this a little bit as a "for dummies" just to make sure every step is included. So to be more precise, I use a Arduino uno with a (se below).
>
> 1: (identifying) The shield is a "ESP8266 ESP-12E UART WIFI Wireless Shield for Arduino UNO R3" (from Ebay). Since there seems to be none documentation about this board, hopfully this will help you. I think there was some pictures before on this thread. On my board it states:
>
> "Arduino ESP8266 Wifi shield. Version 0.9 by WangTongze." (and 1.0.. I've got two)
>
> Here is a good link to identify which ESP8266 module you got if you want to know exacly what you got (if it is a different wifi board) : wiki/doku.php?id=esp8266-module-family
>
> There a 4 DIP switches on this board are numbered from 1-4. To be honest I really don't know what 1 and 2 is. But my guess is that you can use TTL levels on TX & RX opposed to 3.3 which the 8266 module uses directly. These two are always set to DOWN for me. Second though, if so, I might set them to UP when using Arduino. I usually play around with the board with a USB to 232 converter when testing. The other two, 3-4, are connected to GPIO 0 and something else xD. I really doesn't matter really. All I know, that I set these to UP to start a firmware update. Here is a good link that might be somewhat equal to what the shield has implemented.
>
> http://blog.falafel.com/how-to-wire-the ... ogramming/
>
> 2: (using Arduino with the shield) So everywhere, including this thread states that Arduino UNO doesn't handle the software emulated serial very good at high speeds. That is true :D So I got it to work perfectly with a baud rate 9600. What I did was to find a firmware that has default baud rate 9600 from AI thinker. I never really got the baud change to work. AT+CIOBAUD=9600 never got stuck after a reset (rst button och a AT+RST). And the other AT+IPR=9600 broke the firmware. If someone got this to work, please write here in this thread!!
>
> Here is a link: http://wiki.aprbrother.com/wiki/Firmware\_For\_ESP8266
>
> The only wiring I did to make it work, is to connect the tx and rx to Arduino's pins. (rx-\>tx and tx-\>rx). According to this example: http://allaboutee.com/2014/12/27/esp826 ... d-circuit/ connect to pins 2 and 3. The tx and rx from the 8266 shield are located on the left down side. There are other pins you can use also.
>
> 3: (flashing a firwmware) To set the board on flash mode, put the DIP switches to 3-4 to UP, press the 'ESP-RST' button. When flashing is done, set these to DOWN and press the 'ESP-RST'. Maybe there is a way to flash a firmware with the Arduino, but I finally bought a "FT232RL 3.3V 5.5V FTDI USB to TTL Serial Adapter Module for Arduino Mini Port T". There is a picture here: http://blog.falafel.com/how-to-wire-the ... ogramming/. I use this flash software:
>
> https://github.com/Stadslab/ESP8266\_exa ... te%20Ready
>
> Because you can't really do any setting with it and it has worked 100% of all time for me and my use.
>
> So to connect the FT232RL to the 8266 board:
>
> (pins down) from left to right you have: dtr, rx, tx, vcc,cts and gnd and on the wifi shield from left to right: txd, rxd, 5v, gnd, 3v3. rx-\>txd, tx-\>rxd, gnd-\>gnd, vcc-\> 3v3. Remeber that the FT232RL board has a jumper to change the voltage. You should use 3.3v. But for me I had some problems flashing, so I actually the the voltage to 5v and then connect the vcc to 5v connector on the wifi board. Never had any problems after that.
> 0 votes

# Answer
I just managed to get mine working and wrote a blog article about it. Long story short:

* Set all DIP switches "off"
* configure the ESP8266 to use 9600 baud using the AT command "AT+UART\_DEF=9600,8,1,0,0"
* connect debug ports RX/TX to Arduino pins of your choice (not being pin 0 and 1)
* Use the WiFiEsp Lib and tell it to use "your" pins and 9600 baud
> 0 votes

# Answer
In addition to Andreas' answer, I believe he is correct about the general wiring of the 2 pins #0, #1 for some cheap clones.

I got mine to talk to the serial monitor (Arduino) by jumpering over the shield pins directly to the header pins next to the ESP-12E module.

This is at 115200 baud and Both NL and CR on the serial monitor.
> 0 votes

---
Tags: arduino-uno, esp8266, wifi, library
---


# Question
Title: Using a water sensor with a NodeMCU make it less sensitive?
I'm trying to `digitalRead` from a water sensor (the one in the picture) using NodeMCU v3,when I try the sensor with an Arduino board it works fine, but when I try it with an ESP8266 NodeMCU v3 it becomes less sensitive to water with some pins or doesn't work at all with the others. My question is: Is that normal or I'm doing something wrong ?

```
 int pin = 14;
 char printBuffer[128];
 int ledPin = 12;
 const int buzzerPin = 13;

  void setup()
  {
    pinMode(pin, INPUT);
    pinMode(buzzerPin, OUTPUT);
    pinMode(ledPin,OUTPUT);
    Serial.begin(115200);
  }

  void loop()
  {
    sprintf(printBuffer,"PIN %d level is %d\n",pin, digitalRead(pin));
    Serial.print(printBuffer);
    if (digitalRead(pin)==HIGH)
    {
      tone(buzzerPin, 100,1000);
      digitalWrite(ledPin, HIGH);
      delay(100);
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
      delay(100);
      Serial.println("----------- ALARM ACTIVATED -----------");
    }
    else{
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
    }
    delay(500);
   }

```

# Answer
> 1 votes
You are using it wrong.

That sensor (crude as it is) is an *analog* sensor. It's not designed to be used connected to a digital pin.

It outputs an analog voltage proportional to the resistance between the tracks in the sensing portion.

By feeding that voltage into a digital pin you are relying on the logic threshold values, plus any other components (pullup resistors, etc), to give you a "wet" or "try" signal.

Since pins differ (some have pullups, some pulldowns, some nothing, etc) and the logic thresholds are only an approximation in any case, it's doomed to failure.

You need to connect the sensor to an analog input and compare the value read to a threshold value of your choosing. However the ESP8266 is very very poor when it comes to analog - it only has one analog input, and that is only capable of sensing between 0 and 1 volt.

---
Tags: esp8266, sensors, nodemcu, digital
---


# Question
Title: Unexpected negative values from abs() function inline with analogRead
When sampling from A0 with a 0-5V signal on an arduino micro with the code below I get some negative values.

```
int sensor = 0;
sensor = abs(analogRead(A0) - 512);

```

Values:

```
77
25
-74
-58
46
113
-74
102
-91
-51
-126
47
31

```

When running the (apparently) mathematically equivalent code below I get exclusively positive values.

```
int sensor = 0;
sensor = analogRead(A0);
sensor = sensor - 512;
sensor = abs(sensor);

```

I don't think this is an integer overflow as in this post because when I switch to `long sensor = 0` I get the same negative results.

What's going on here?

# Answer
`abs()` is defined in Arduino.h as a macro:

```
 #define abs(x) ((x)>0?(x):-(x))

```

A macro does not evaluate in the same way as a function.

```
 sensor = abs(analogRead(A0) - 512);

```

This statement will be expanded at compile-time to:

```
 sensor = ((analogRead(A0) - 512)>0?(analogRead(A0) - 512):-(analogRead(A0) - 512));

```

Now the "error" is easy to understand. The analog pin is read twice. The "error" can be avoided by adding the following line first in your sketch:

```
#undef abs

```

This will remove the macro `abs()` and the standard library function will be used instead.

Cheers!
> 6 votes

---
Tags: arduino-micro, mathematics
---


# Question
Title: How do I supply either (1) dual voltage or (2) negative voltage?
Sorry in advance if this question already exists--I tried to search but my keyword knowledge is shaky. I have created a Colpitts oscillator on breadboard using AA batteries as the power supplies. I want to implement this oscillator with an Arduino. (Once it's set up, I want to use its voltage to do some things, but that isn't part of this question.)

In the image below, I have two voltages, Vcc (positive voltage) and Vee (negative voltage). My simulations indicate I can run the oscillator either with a dual voltage (+5V and -5V), or with one negative voltage (-5V) and the other set to ground. Either provides a 100 kHz oscillation from about -5 to 2 V. So:

* Is there a way to provide a dual voltage supply from the Arduino Uno?
* Is there a way to provide a single negative voltage supply from the Arduino Uno?

Thanks!

# Answer
You can make -5 V if you use an external power source, like in the circuit below (untested).

Connect the GND (-) from the Arduino to the +5V from the External (5V) source, than 0V will be the GND (with respect to the Arduino), but the GND of the external source will be -5V with respect to the Arduino.

I only used the resistors to get no short circuits, you can replace it by your own circuit (connecting the 5V arrow to Vcc and the -5V arrow to Vee).

simulate this circuit – Schematic created using CircuitLab
> 3 votes

---
Tags: power, voltage
---


# Question
Title: Component with controllable resistance from Arduino?
I'm new to Arduino and building circuits, and was wondering if there is a type of component, or some other way to do the following task:

I want to control the resistance of a circuit from my computer linked to my Arduino, presumably using an output analog PIN.

Basically what I have is an LED whose brightness I want to control from my computer. I want to be able to control the resistance of the circuit to limit the electricity going to the LED, and I want to be able to do this from my computer (not physically, with a potentiometer) (unless a potentiometer's resistance can also be controlled from a PIN?).

How can I do this?

# Answer
> 1 votes
The easiest way to drive an LED with variable brightness is to use one of the pulse width modulation (PWM) output pins on an Arduino.

A PWM pin takes an input value from 0 to 255 (or is it 0/1023? I don't remember.) and converts it to a ratio of on-time to off-time. At the highest value, the output pin is in the on state, 100% of the time. At the halfway point, the output pin is HIGH 50% of the time, and LOW 50% of the time.

Our eyes average out the flashes and see a variable brightness. It works very well.

If you absolutely must have a variable resistance controlled by a digital value, there are devices known as digital potentiometers. These are variable resistors controlled by digital inputs. For an Arduino, you should think about an I2C or SPI potentiometer, which is controlled by serial port commands. You tell it the resistance you want, and it sets itself to that resistance.

As CrossRoads points out in their comment below, you still need a current limiting resistor to drive an LED from a logic pin, to protect both the LED and the output driver on the Arduino. You want to limit the current to the max current for your LED, and then use PWM to lower the brightness from the absolute max set by the current limiting resistor. CrossRoads explains how to calculate the resistor value.

---
Tags: led, remote-control, potentiometer
---


# Question
Title: Using NodeMCU D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins
I am using a NodeMCU board and have already used 6 digital pins as output for interfacing with the LCD. I intend to use 2 more digital pins, one as input and other as output for interfacing an ultrasonic sensor.

D8, D4 and D3 are the only digital pins remaining. I understand that D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins of the NodeMCU have special boot-controlling uses. So how can I use those pins as generic digital pins. Any help is appreciated.

# Answer
> 1 votes
The boot setup pins have pull-up on board (0, 2) and pull-down (15) to ensure the correct boot. io 0 (D3) is additionally wired to the reset circuit controlled over USB to put the esp8266 into bootloader a.k.a. flashing mode.

io 0 must be HIGH for normal boot, io 2 must not be LOW (can float according to spec).

If you attach a device to this pins, the device must respect the boot state. Some devices will pull-down or pull-up a wired pin. Usually it is not documented. You can't use such devices on boot config pin which requires the other state.

The pull-up and pull-down can influence the attached device or readings from the device. For some elements it can be advantageous.

Best is to use this pins for elements which would need pull-up or pull-down anyway. For example buttons/switches or sensors which behave like buttons or switches.

In my project with Wemos D1 R2 I had signal to relay module on io 0, speaker module (with amplifier) for tone() function on io 2. I could not use a relay or mosfet module on io 2. On io 15 I had a reed relay module control signal, which I didn't want to go HIGH at boot as most esp8266 io pins do.

# Answer
> 0 votes
Not a direct answer to your question, but some other way that solves your problem, is to use a shift register like 74HC595 and control the 6 pins for the LCD with the 74HC595 which only uses 3 (digital GPIO) pins. That saves you 3 pins for others. Actually you can use 8 pins or even 32 when you daisy chain four 74HC595s.

---
Tags: nodemcu, digital-in, digitalwrite
---


# Question
Title: My ESP8266 web server is only displaying text, even after ensuring content type is text/HTML
So I just got my two ESP8266/ESP-12E WiFi development boards in the mail as I am trying to set up a few home automation devices in my house. I've gotten much further than I thought I would today, considering this is my first foray into working with circuits that involve microprocessors/WiFi, but I've run into a problem that I can't find a solution to myself. Forgive me if there is another question similar to this, but I could not find it and this seems like the best place to ask.

I am using a tutorial/template program that Rui Santos from Random Nerd Tutorials was kind enough to create ( https://randomnerdtutorials.com/esp8266-web-server/ ), and although we have (as far as I can tell) identical boards, operating systems and Arduino code, I keep getting an HTML page that is text only, with none of the CSS or HTML elements showing. It should look like this:

However, I am getting a page that looks like this:

His serial monitor is giving this response:

My serial monitor is giving me this response:

I've tried putting `client.println("Content-type:text/html");` in a few places to see if it would help display the page, but to no avail. Any help with getting this little program/website running would be greatly appreciated.

Thanks for your time!

# Answer
> 1 votes
Don't use the low-level tools to handle http, use the built-in http tools. They make creating http responses trivial. No more concatenating headers or worrying about client status; it provides a nice clean function ex:`server.send(404, "text/plain", message);` and nice subscription method: `server.on()`.

Checkout its usage on one of the Arduino ESP8266's built-in examples: https://github.com/esp8266/ESPWebServer/blob/master/examples/HelloServer/HelloServer.ino

# Answer
> 0 votes
The use of HTTP here is fairly straight forward so I think printing out your own HTTP headers is OK, you just need to be very specific with the order and send exactly what the browser expects. Without seeing your code, my guess is that you're sending out a blank line to the client somewhere prior to the 'Content-type: text/html' line being sent or that you're not printing an empty blank line somewhere after the Content-type line is being sent. If your browser (the client) doesn't receive the HTTP protocol commands that it expects in the order that it expects, then it will default to displaying EVERYTHING you send it as either plain text or an HTML document. To illustrate exactly what is supposed to be sent to the browser in this example:

```
HTTP/1.1 200 OK
Content-type:text/html
Connection: close

<HTML>....

```

Note that there should be a empty line printed out after the Connection: close line and before you send any HTML. There should be nothing else sent to the client prior to the HTTP/1.1 200 OK line being sent and before your HTML code starts. If you don't follow the protocol, your browser will probably default to displaying everything plain text as you're seeing.

Something else I noticed in the example code, there is no space between Content-type: and text/html. This is unusual, but I guess it doesn't break the protocol and Firefox and Chrome handle it ok in my testing. Still, it could cause issues if a browser doesn't handle that properly so you might just try adding a space between the header and it's value.

---
Tags: esp8266, wifi, web-server
---


# Question
Title: Why shouldn't you connect more than one motor directly to either the 5V or 3.3V pins/rails of an Arduino?
Why shouldn't you connect more than one motor directly to either the 5V or 3.3V pins/rails of an Arduino?

What would go wrong otherwise?

# Answer
> 0 votes
On an Uno, the barrel jack feeds a reverse polarity diode that can support 1A max, which then feeds a 5V regulator rated for 800mA max (800mA cannot be reached due to lack of cooling - but it does pretty well if barrel jack voltage is kept to 7.5V) which then feeds a 3.3V regulator rated for 150mA.

With too high a voltage or too much current, the 5V regulator either goes into thermal shutdown, or often just severely overheats and fails (sometimes spectacularly).

The 5V can also come from the USB source, which has 500mA PTC resettable fuse, so even less current is available.

So power your motor from another source, and use the Arduino output pins to control a transistor to turn the motor on and off.

---
Tags: arduino-uno, motor
---


title: Mini ethernet shield pins don't have SI

text:
# Question
Title: Mini ethernet shield pins don't have SI
Please somebody who had the same issue help me. The question is how to connect this Mini Ethernet shield to an Arduino. The main problem is the pins that my shield have or haven't; my current connections to the Arduino Mega 2560 are:

1. 5v to 5v
2. GND to GND
3. LNT to NULL
4. CLK to NULL
5. SO to pin50
6. WOL to NULL
7. SLK to PIN52
8. ST to ????
9. RST to RST
10. CS to PIN53
11. Q3 to NULL
12. GND to NULL

But in all cases when I search the connection diagram every picture has SI, but I don't have it (I tried to connect ST to PIN51 without luck).

What kind of Ethernet shield is that? Or how to connect those pins?

I hope someone can help me; thank you in advance.

```
/*
  DHCP-based IP printer

  This sketch uses the DHCP extensions to the Ethernet library
  to get an IP address via DHCP and print the address obtained.
  using an Arduino Wiznet Ethernet shield.

  Circuit:
   Ethernet shield attached to pins 10, 11, 12, 13

  created 12 April 2011
  modified 9 Apr 2012
  by Tom Igoe
  modified 02 Sept 2015
  by Arturo Guadalupi

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
   // Ethernet.init(53);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  switch (Ethernet.maintain()) {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    default:
      //nothing happened
      break;
  }
}

```

And result is :

* 16:41:14.242 -\> Initialize Ethernet with DHCP:
* 16:41:14.804 -\> Failed to configure Ethernet using DHCP
* 16:41:14.848 -\> Ethernet shield was not found. Sorry, can't run
without hardware. :(

# Answer
The "Mini Ethernet Shield" uses ENC26j60 chip. The Arduino Ethernet library is for Wiznet W5100/W5200/W5500 chips. You can't use it with ENC26j80.

With Arduino Mega I would recommend to use the UIPthernet library for ENC26j80. Other option is the EtherCard library.

The UIPEthernet library has the same API as the the Arduino Ethernet library.
> 0 votes

---
Tags: pins, ethernet
---


# Question
Title: How can write a single data into spiffs?
```
typedef struct book {
char title[20];
 char author[20];
 int pages[10];

} Book;

Book b1 = {"The Zahir","Paulo Coelho",336,0};

```

while writing this structure into SPIFFS of ESP8266, I am using function

```
filename.write( (const uint8_t*)&b1, sizeof(b1));

```

but how can write a single data like name of book into structure of spiffs?

# Answer
For this kind of situation it's best to treat your data as records in a database. To change one part of a record you read the entire record, change the value, then write that record back.

```
int record = 4; // which record you want to change

struct book b; // Temporary storage for editing the data

// Go to the record and read it in
filename.seek(record * sizeof(struct book));
filename.read( (const uint8_t*)&b, sizeof(struct book));

// Change the data
strcpy(b.title, "Winnie The Pooh");

// Go to the record again and write it out
filename.seek(record * sizeof(struct book));
filename.write( (const uint8_t*)&b, sizeof(struct book));

```
> 1 votes

---
Tags: esp8266
---


# Question
Title: Arduino app hangs on upload for all boards
I'm at a loss. I have many boards and have not had much trouble in the past uploading to feather, uno, light blue bean and others. I have a lot of boards loaded in the board manager and I'd rather not delete everything just yet.

But, after taking a month off of arduino programming I've come back to the app to discover that I can't upload *anything* to *any* board. I've tried a brand new uno, an adafruit feather and the light blue bean. In each case I can see the port, but the upload just hangs like this:

On the board the light that normally blinks during upload never blinks. It's like the upload just isn't happening. But there is no error in the app.

I tried reinstalling the app, but that didn't help. My next thought is to delete everything, and do a fresh install. Which will be annoying. Is that my only hope?

---

**UPDATE:**

Here are the settings from the tools menu as requested:

# Answer
I tried that once. A very common reason for this problem is a different cable. Some USB cables are not suited for uploading the data to the Uno board.

Have you brought a new cable? If so, switch back to the old one. It may not look like it makes a difference, but it requires attention.
> 1 votes

# Answer
I appreciate that this is an old post but I have recently been experiencing this problem.

I found that the issue was caused when I had a wireless SD shield attached to the Arduino. Taking this shield off allowed me to upload. This occurred across 5 different Arduino's.

After some more testing I found that switching the "serial select" toggle on the wireless shield from "MICRO" to "USB" allowed me to upload as well. Switching it back to "MICRO" subsequently blocked the upload.

Hope this help anyone having this problem in the future.
> 1 votes

---
Tags: uploading
---


title: Reading ADS1232 with Arduino

text:
# Question
Title: Reading ADS1232 with Arduino
I'm a newbie and I'm trying to read an ADS1232 with an Arduino for a Weight Scale Project.

I read data through the SPI interface, but i don't receive the result.

```
#include <SPI.h>

#define MISOPIN  50  //DATA
#define SCLKPIN  52  //SCLK
#define PDWN     53  // SS
#define SPEED       5
#define GAIN0       7
#define GAIN1       6
#define CLKIN       10
#define A0          9
#define TEMP        8

uint32_t byte1;
uint32_t byte2;
uint32_t byte3;
uint32_t finaladc = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(PDWN, OUTPUT);
  pinMode(MISOPIN, INPUT);
  pinMode(SCLKPIN, OUTPUT);
  pinMode(SPEED, OUTPUT);
  pinMode(GAIN0, OUTPUT);
  pinMode(GAIN1, OUTPUT);
  pinMode(A0, OUTPUT);
  pinMode(TEMP, OUTPUT);

  digitalWrite(GAIN0, HIGH);
  digitalWrite(GAIN1, HIGH);
  digitalWrite(SCLKPIN, LOW);
  digitalWrite(A0, LOW);
  digitalWrite(TEMP, LOW);
  digitalWrite(SPEED, HIGH);//0-->  10SPS ,1-->80SPS
  digitalWrite(PDWN, HIGH);  //0-->  POWERDOWN(SLEEPING -NO CONVERSION) ,1-->WORKING MODE

  reset_adc();

  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE1);

  digitalWrite(SCLKPIN,LOW);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(MISOPIN)== LOW) read_adc();

  delay(1000);

}

void reset_adc()  {
  digitalWrite(SCLKPIN,HIGH);
  delayMicroseconds(1400);

}

void read_adc()  {
  drdy_wait();
  uint8_t i;
  finaladc = SPI.transfer(0xff);
  finaladc |= (uint32_t)SPI.transfer(0xff) << 8;
  finaladc |= (uint32_t)SPI.transfer(0xff) << 16;
  Serial.print ("ADC_value:  ");
  Serial.println(finaladc,DEC);
  Serial.println();

}

void drdy_wait()
{
  delayMicroseconds(30);
}

```

Has anyone worked with this? Can you help me? Thank you

# Answer
I fished out some code I wrote a while back while evaluating the 1232. SPI is a headache because of the need toggle the clock signal to prevent the last data bit from 'sticking', which will botch repeated reads when the last data bit is high.

If you are absolutely required to use SPI stop reading this answer.

Everything you need to know is on pages 18 and 19 of the ADS1232 datasheet. Note this is strictly demo material, for example it doesn't take into account settle time when switching channels.

```
int32_t read_adc(const uint16_t wait_millis) {
   int32_t data = 0;
   // reset ADC
   digitalWrite(ADS1232_PDWN, LOW);
   delayMicroseconds(10);
   digitalWrite(ADS1232_PDWN, HIGH);
   delayMicroseconds(10);

   for (; data < wait_millis && digitalRead(ADS1232_DRDY_DOUT) != LOW;
        delay(1),
        data++);

    if (data == wait_millis) {
        // timeout
        return -1;
    }

   // read in 24 bits, see Page 19 of the datasheet

   data = 0;
   for (uint8_t i = 0; i < 24; i++) {
        digitalWrite(ADS1232_CLK, HIGH); // clock out next data bit
        data <<= 1;
        data |= digitalRead(ADS1232_DRDY_DOUT);
        digitalWrite(ADS1232_CLK, LOW);
    }
    // adjust for sign. See page 18 of datasheet
    if (data & 0x00800000)
        data |= 0xFF000000;
    // avoid having DRDY/DOUT remain in the state of the last bit
    // see page 19 of datasheet
    digitalWrite(ADS1232_CLK, HIGH);
    delayMicroseconds(10);
    digitalWrite(ADS1232_CLK, LOW);

    return data;
}

```
> 1 votes

---
Tags: spi
---


# Question
Title: Wire.h missing - Failing to upload I2C 16x2 LCD sketch
I am total newbie in Arduino and for the last 3 days I am trying to figure this out.

I would like to use an I2C display for a project. I have installed the LiquidCrystal\_I2C, but when I try to upload it I get this `wire.h` missing message.

Could anyone please help me to understand and fix this?

# Answer
> 2 votes
That library is special. It expects to be placed in the same location as the Wire library. You need to find the location of the Wire library and place this library alongside it. So you have:

```
.../Wire/Wire.cpp
.../Wire/Wire.h
.../LiquidCrystal_I2C/LiquidCrystal_I2C.cpp
.../LiquidCrystal_I2C/LiquidCrystal_I2C.h

```

etc

---
Tags: i2c, lcd, wire-library
---


title: Servo delay problems

text:
# Question
Title: Servo delay problems
So I had a test last week with the Arduino Uno starter kit. We got a task including the servo. I had to get the servo to go from 0 to 90 degrees and it was supposed to use 4 seconds to do so. Than back from 90 degrees to 0 again. My code is like this:

```
#include <Servo.h>

Servo myservo;
int pos = 0;
void setup() {
  myservo.attach(9);
}
void loop() {
  for (pos = 0; pos <= 90; pos += 1) {
    myservo.write(pos);
    delay(40);
  }
  for (pos = 90; pos >= 0; pos -= 1) {
    delay(13);
  }
}

```

As you see the delay should be just 40 and 13 milliseconds, but it used 4 seconds and 1.3 seconds. but since the code was, wrong I didn't pass on this task. So what have I done wrong.

# Answer
I would use the `millis()` function to set up a timing as accurate as possible.

Before starting your operations store the actual value of the `millis()` timer to a variable `time_passed`. After finishing your operation, in this case a 1° step of the Motor, wait until the 90's part of your desired time (4s) is reached. Then you increase your time\_passed with the 90's part of your desired time bevor going on.

```
#include <Servo.h>

unsigned long time_passed;
unsigned long timestep = 4000 / 90; // necessary period to reach 4s in 90 steps
Servo myservo;
int pos = 0;

void setup() {
  myservo.attach(9);
}
void loop() {
  time_passed = millis();
  for (pos = 0; pos <= 90; pos += 1) {
    myservo.write(pos);
    while ( millis() - time_passed < timestep) {
    }
    time_passed = time_passed + timestep; // this was time_passed = millis(); at testing, but this should be even more accurate. Hope I made no mistake, since I tested only the previous Version ;-)

  }

  for (pos = 90; pos >= 0; pos -= 1) {
    myservo.write(pos);
    while ( millis() - time_passed < timestep) {
    }
    time_passed = time_passed + timestep; // this was time_passed = millis(); at testing, but this should be even more accurate. Hope I made no mistake, since I tested only the previous Version ;-)
  }
}

```
> 1 votes

---
Tags: servo
---


title: NodeMCU with HC-SR04 ultrasonic sensor

text:
# Question
Title: NodeMCU with HC-SR04 ultrasonic sensor
How can I interface an ultrasonic sensor with a MCU with 3.3 V GPIO like the NodeMCU? I tried powering the sensor with both 5 V and 3.3 V from the MCU. Both failed to show any results as the distance appeared to be 0 V. In both cases the trig pin of the sensor was given 3.3 V input from the GPIO pin. I assume I need to level shift the echo pin output from 5 V to 3.3 V. How can I do that? Or is something else the issue? The code I used is fine as it works with Arduino.

# Answer
> 1 votes
The datasheet I found says the logic is TTL, which as far as I know is 2 V - Vcc, so 3.3 V should be fine. Is Trig just constantly given 3.3 V? According to the datasheet, it needs a 10 us pulse. Perhaps that is your issue? Code or schematics could help if that isn't it.

---
Tags: nodemcu, voltage-level, hc-sr04
---


# Question
Title: Problems with serial communication from Arduino to ESP8266
I've been trying to get an Arduino and ESP8266 to communicate with each other over serial. The ESP8266 uses the `Serial` class for communications, while the Arduino uses `SoftwareSerial`.

The problem is that when I try to send data from the Arduino to the ESP8266, only the first character of the string sent gets received by the ESP8266. For example, if I send a string "leather", the ESP8266 only receives an 'l'. Both devices are operating at 38400 baud, although I have tried 9600 baud with similar results (apparently `SoftwareSerial` is more reliable at lower baud rates).

Here is the relevant code that's running on both devices:

Arduino code:

```
#include <stdlib.h>
#include <SoftwareSerial.h>

#define COMMAND_TILT                'c'
#define SOFTWARE_SERIAL_BAUD_RATE   38400
#define ESP_RX                      8
#define ESP_TX                      9

SoftwareSerial esp(ESP_RX, ESP_TX);

void setup()
{
    ...
    esp.begin(SOFTWARE_SERIAL_BAUD_RATE);
    ...
}

void loop()
{
   if (esp.available() > 0) {
        String data;
        while (esp.available() > 0) {
            data += (char) esp.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);
        int value = data.toInt();
        char buf[STR_BUF_LEN];

        switch (command) {
             case COMMAND_TILT:
                 ...
                 sprintf(buf, "%c%d", COMMAND_TILT, value);
                 esp.write(buf);
                 break;
             ...
        }
    }

    delay(100);
}

...

```

ESP8266 code:

```
#define SERIAL_BAUD_RATE 38400

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

void loop()
{
    ...

    if (Serial.available() > 0) {
        String data;
        while (Serial.available() > 0) {
            data += (char) Serial.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);

        // problem: now, data.c_str() is blank when it should contain an integer in string format

        ...

        delay(100);
    }
}

...

```

If it helps to know, I'm running an MQTT client on the ESP8266 and controlling some steppers and relays on the Arduino.

# Answer
> 0 votes
The cause of the issue was that the ESP was reading `char`s too quickly, meaning that it would give up before the next `char` could be sent from the Arduino. To fix the issue I simply added a 10 ms delay between each `Serial.read()` call on the ESP.

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


# Question
Title: WiFi connection times out if credentials retrieved via serial terminal
I've implemented a small WiFi connection procedure into my ESP32 project. The available networks get printed with index, then I'm entering the index and retrieve the network name from it. The password is entered via serial in clear text.

Before connecting, I'm printing the credentials and thus could confirm they are read into `const char *` strings properly.

Unfortunately when using this procedure the connection to my AP times out. I've also tried to override the strings with hardcoded values and then the connection works as expected.

```
while (!Serial.available()) {
    // (timeout is implemented here)
}
String index_s = Serial.readStringUntil('\n');
long index = index_s.toInt();

// { same while as above }
String passw = Serial.readStringUntil('\n');

const char *ssid = WiFi.SSID(index).c_str();
const char *pass = passw.c_str();

// with this it works:
// ssid = "my_network";
// pass = "my_password";

Serial.printf("connecting to %s using %s", ssid, pass);
WiFi.begin(ssid, pass);

```

# Answer
> 1 votes
The answer was quite simple but of the kind you need some time get find out. The issue was a hiding carriage return.

```
passw.trim();

```

Did the trick. `String.trim()` removes the `\r` and thus the password gets accepted.

---
Tags: wifi, esp32
---