# Question
Title: Send AT commands to ESP8266 from Arduino Uno via a SoftwareSerial port
**GOAL**

From Arduino UNO, send AT commands to ESP8266 via a SoftwareSerial port and receive results.

**CURRENT STATUS**

I either send AT commands and get nothing back (*wiring scheme 1*) or I send AT commands and get garbage back (*wiring scheme 2*).

Using the Arduino as a pass through (as explained in the tutorial listed in the resources section), I can send AT commands. I have found that I can communicate with the ESP8266 at 115200 baud.

This is the results of running `AT+GMR`:

```
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

```

**WIRING SCHEME 1**

*!! I have the green wire attached to pin 3 on the Arduino Uno and the yellow wire attached to pin 2; not 1 and 0 as the picture suggests !!*

**WIRING SCHEME 2**

Same wiring as above, but I have RX and TX reversed. The green wire is attached to pin 2 and the yellow wire is attached to pin 3.

**CODE**

*This is running on Arduino Uno*

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

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

  Serial.println("Started");

  // set the data rate for the SoftwareSerial port
  esp8266.begin(115200);
  esp8266.write("AT\r\n");
}

void loop() {
  if (esp8266.available()) {
    Serial.write(esp8266.read());
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

```

**RESULTS FROM RUNNING SKETCH**

*Wiring Scheme 1*

```
Started

```

*Wiring Scheme 2*

```
Started
�����

```

I have tested the ESP8266 via the instructions listed in the tutorial in the *Resources I've Used* section below. The ESP8266 works just fine when sending it instructions via the Serial Prompt.

**RESOURCES I'VE USED** http://rancidbacon.com/files/kiwicon8/ESP8266\_WiFi\_Module\_Quick\_Start\_Guide\_v\_1.0.4.pdf

**QUESTION**

Does anyone know if what I am trying to do is possible? And if it is, what am I doing wrong?

# Answer
> Does anyone know if what I am trying to do is possible?

Absolutely possible :)

> And if it is, what am I doing wrong?

SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting). Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability. How to change the baud rate on the ESP8266 will depend on the firmware version. I've had success with `AT+IPR=9600`. You only need to run this command once (it's a persistent setting). I'd suggest, based on your description, that this is the most likely culprit that's causing the "garbage" output you describe.

A couple of other notes:

* The ESP8266 runs on 3v3, not 5v, so you shouldn't have it directly connected to the digital pins—you need to run through a logic level converter. Running 5v can fry your ESP8266.
* The Arduino's 3v3 output has insufficient current to support the ESP8266 reliably (50mA Arduino vs up to 300mA for the ESP8266 by some accounts)—try running the ESP8266 off a separate supply. It probably won't affect simple commands like `AT` but when you try to connect to a network etc. it may cause unexpected device resets.
* As noted by others, you need to send \r\n — so make sure your Serial window is set to send both (this is a drop-down in the serial window)
> 9 votes

# Answer
Well you may try this:

Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.

Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.

PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.

Use this code to connect to ESP8266:

```
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

```

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.
> 8 votes

# Answer
**Does anyone know if what I am trying to do is possible?** It is possible, i've done it with 2 arduinos where one was simulating ESP8266 (waiting for ebay order).

**And if it is, what am I doing wrong?**

What you are doing is wrong on most levels, but i think you got most sorted out.

An idea is to implement this little fella: Logic level shifter it will save you many troubles later.

On your "WIRING SCHEME 1" you are using the arduino's Hardware serial port to talk directly to the device as if it was connected through a TTL cable or FTDI cable.

This means that the arduino device would in theory read from the hardware when talking too the ESP8266, if you have another arduino or a TTL cable, try and connect it to gate 2 and 3 on the "main" arduino and you should get a similar result as for your example result 2. Since you would that way proxy through the arduino. If not that would be a place to start debugging.

Beside that i could only recommend you in investing in either a TTL 3,3v or a logic level converter. When i got my cable everything worked out of the box.
> 1 votes

# Answer
I had lot of problems as well. In my case problems are almost solved by switching from SoftwareSerial to AltSoftSerial. It seemed that on the Uno the standard software serial library was not working for me. After switching I started to get results back for the first time. (I also used level shifting and external power supply for 3.3V)

---

And by almost solved I mean - I still get, from time to time, gibberish on the terminal. So even AltSoftSerial isn't a perfect solution. I was using the ESP-07 with a 115200 bps data rate.
> 1 votes

# Answer
We found that many of the problems with the ESP - Arduino Uno serial software integration had to do with incompatible baudrate. We created this short tutorial (including a Github library) which you are welcome to test and see if it solves these issues. http://www.instructables.com/id/Simple-ESP8266-Arduino-Uno-Software-Serial-Integra/
> 0 votes

# Answer
Here are a few tips when using ESP8266 Module.

1. Don't use software serial as it's unreliable especially at higher baud rates.
2. Always connect ESP module to computer and test all AT commands before interacing with Arduino to ensure that you are working in right direction
3. Make a power adaptor board to make ESP module compatible with Arduino 5v supply

Also check out this link for more details
> 0 votes

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


# Question
Title: Connecting Load combinator to HX711 then to Arduino
i'm currently a student and my project is to create a weighing scale using 50kg load sensors (x4) with HX711 amplifiers, load combinator and Arduino UNO. I've connected the load combinator and HX711 based on the picture below:

I'm wondering after this connection, how do i connect it to the pins of Arduino UNO and does anyone know the codes to make the load sensors work? Because currently i keep getting 0kg as the final value as well as the offset value.

# Answer
> 1 votes
To be able to wire load sensors up you first need to understand how they work and what the wires on them actually mean. There are no standards as regards colour coding of the wires.

So step one is to find out the colour coding of your load cells. Assuming they are "normal" cheap 3-wire ones, internally they look like:

simulate this circuit – Schematic created using CircuitLab

You need to identify those wires on your cells. We'll call them +, C and - (in that order) from now on.

The idea is that you provide power between + and - and a varying voltage comes out of C depending on the load applied. More load means a lower voltage, since R1 and R2 form a simple potential divider.

However that's not enough to get good results - the voltage differences are too small. So they are usually used as part of a Wheatstone Bridge. This allows a much smaller voltage variance to be detected.

The Wheatstone Bridge is created by the combinator board. It does it by combining the individual parts of separate cells together to form just two load cells along with the static resistances. This is the form the Wheatstone Bridge create takes:

simulate this circuit

I have boxed in each load cell so you can see how two "variable" legs combine into a single variable resistance, and two "static" legs combine into a single static resistance.

Now you can see how you could test the combinator to make sure it's giving proper results. Apply a voltage between E+ and E- (say 5V) and measure the voltage between A+ and A-. Apply pressure to the load cells (all of them at once) and observe a change in the voltage between A+ and A-.

Assuming that is showing good results (the voltage change will be quite small, so set your DMM to its most sensitive setting), your next point of call is the connection to the Arduino itself.

The HX711 uses a digital serial protocol. Sparkfun has software that bit-bangs that protocol over any pair of IO pins you choose. There is nothing special about which pins are chosen - any two can be used. So as long as you have +5V, GND and the two data pins connected up to the Arduino there's not much that can go wrong.

So that then leaves the software. The biggest mistake people often make is to not tell the software which pins are being used for the serial communication. Or telling it the wrong pins - getting the clock and data pins mixed up, for instance. This would be the first port of call for checking the software. Make sure you have the right pins specified. Quite how you do that without seeing your software I can't say, but Sparkfun have some example software (scroll down to the bottom of the page) which just uses a pair of `#define` macros to specify the pins.

# Answer
> 0 votes
thank you for your help to my question and sorry i was not being specific enough.

Initially the connection of the weighing scale was based on this:

However, after much research, i've decided to give the load combinator a try and use it to connect all the 4 load sensors to form a Wheatstone Bridge that will then connect to the Arduino. So basically, the load combinator is just another add on component.

As for my codes, this is how it looks like:

```
#include <hx711.h>
#define DOUT 3
#define CLK 2

Hx711 scale(3,2);

int count=0;

float sum=0;
float value;
float avg=0;
float offset;
float toffset;

int count2;

float V;
float VT;
float total;
int t;
float foffset;

void setup()
{
  Serial.begin(9600);
  Serial.println("HX711 Test");
}

void loop()
{
  for(count=0;count<10;count++)
  {
    value = (scale.getGram()*0.07);
    sum = sum + value;
  }
        toffset = +(sum / 10);
         Serial.print("Offset: ");
        Serial.print(toffset, 1);
        Serial.println(" kg");

        Serial.println("Please stand on the plate and do not remove both of your legs.");
        delay(4000);

  for(count2=0;count2<10;count2++)
  {
    V= (scale.getGram()*0.07);
    total=total+ V;
  }

  VT=(total/10);
  Serial.print("Average Weight: ");
  Serial.print(VT, 1);
  Serial.println(" kg");

   if(foffset= -toffset)
   {
    Serial.print("Final Weight: ");
    Serial.print(((VT+foffset)*-1), 1);
    Serial.println(" kg");
   }
 else
  {
    if(foffset=toffset)
   {
    Serial.print("Final Weight: ");
    Serial.print((VT-foffset), 1);
    Serial.println(" kg");
   }
 }
 Serial.end();
}

```

---
Tags: arduino-uno
---


# Question
Title: POWER_MODE_IDLE wake on any input change?
I want to be able to put an Arduino to "sleep" but I want it to immediately resume if any panel tactile buttons are pressed.

The purpose is to try to minimize any digital noise in an nearby high gain analog circuit.

My guess at this point is that I want to put the Arduino into POWER\_MODE\_IDLE but it is less clear to me the best way to wake up.

How can I instantly wake up from POWER\_MODE\_ILDE if any input changes? I don't want to have to hold down a button or even use a specific input. Is there a "catch-all" interrupt that will react immedately to a change on any or on a large set of inputs?

# Answer
> 1 votes
As I mention on my page about interrupts you can use pin-change interrupts on the Atmega328P to wake from the deepest sleep mode (SLEEP\_MODE\_PWR\_DOWN).

Example code:

```
#include <avr/sleep.h>

const byte LEDLOOP = 8;
const byte LEDWAKE = 9;

ISR (PCINT1_vect)
 {
 // handle pin change interrupt for A0 to A5 here

 // toggle LED
 digitalWrite (LEDWAKE, !digitalRead (LEDWAKE));
 }  // end of PCINT1_vect

void setup ()
  {
  pinMode (LEDWAKE, OUTPUT);
  pinMode (LEDLOOP, OUTPUT);
  digitalWrite (A0, HIGH);  // enable pull-up

  // pin change interrupt
  PCMSK1 |= bit (PCINT8);  // want pin A0
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE1);   // enable pin change interrupts for A0 to A5

  }  // end of setup

void loop ()
{

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_mode ();

  // flash to indicate we got out of sleep
  digitalWrite (LEDLOOP, HIGH);
  delay (100);
  digitalWrite (LEDLOOP, LOW);
  delay (100);

  } // end of loop

```

This has the advantage of consuming very little power while asleep, and also waking on any pin (of an Atmega328P).

Running on 5V at 25°C you should only consume around 150 nA of current while asleep (on a "bare bones" board without USB chip, voltage regulator or power LEDs).

Other sleep modes may use more power but wake more quickly.

# Answer
> 0 votes
The Arduino can only be woken from sleep by a change on pins 2 and/or 3.

> On the hardware front, the Arduino is equipped with two interrupt ports: digital pin 2 and 3. So the Arduino can sense those pins for an event to wake up and resume execution of code.

http://playground.arduino.cc/Learning/ArduinoSleepCode

However, the datasheet indicates that any pin can be used:

http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P\_Datasheet.pdf Section 17. EXINT - External Interrupts

> The External Interrupts are triggered by the INT pins or any of the PCINT pins. \[...\] The Pin Change Interrupt Request 2 (PCI2) will trigger if any enabled PCINT\[23:16\] pin toggles. The Pin Change Interrupt Request 1 (PCI1) will trigger if any enabled PCINT\[14:8\] pin toggles. The Pin Change Interrupt Request 0 (PCI0) will trigger if any enabled PCINT\[7:0\] pin toggles. The PCMSK2, PCMSK1 and PCMSK0 Registers control which pins contribute to the pin change interrupts.

---
Tags: interrupt, sleep
---


# Question
Title: Can I remove soldered atmega328P from arduino board, using hot air gun, without damaging it?
I need to remove atmega328P from arduino board and the best tool what comes up to my mind is a hot air gun. What is the maximum temperature that atmega328P can withstand?

# Answer
web search reveals the peak reflow temperature is 260°C

the chip will withstand that for 15 seconds or so

here is an example graph of a reflow oven temperature during the reflow process
> 2 votes

# Answer
The idea of using a simple "heat gun" (such as this) will fail on two fronts:

1. You can't control the temperature. It will get too hot and you will damage the chip.
2. You can't control the hot air. It will melt all the plastic items on the board (the connectors, etc) and you'll just end up with a big blob of bubbling plastic.

You need a proper reflow station. These are to a heat gun what a soldering iron is to a blow torch. They are temperature controlled, so you can select a specific temperature (with reference to the datasheet of the component you want to (de)solder), and have interchangeable nozzles to allow you to accurately direct the heat where it is needed.

I use the (cheap) Atten 858D+.
> 3 votes

# Answer
The ATMega328P comes in 2 packages. DIP(Dual Inline Package) and SMD(Surface Mount Device)

The Hot Air Gun method is only best applicable to the SMD version. I would recommend you to not focus on what temperature the board can withstand, but try to practice on the hot air soldering techniques.

First try to practice removing SMD components on a separate PCB so you can be familiar with the hand movements and the techniques in safely removing SMD components. When you are familiar enough with the hand movements and techniques, then that is the best time to work on your Arduino Board.

After doing this you should be able to remove and SMD components from any type of circuit boards.

PS. Be sure to use a lot of soldering paste when using hotair reflow ;)
> 0 votes

---
Tags: atmega328
---


# Question
Title: When I turn on the servo it spins on its own before going to the right position and start the sketch
I can't get my head around this: when I turn the servo on it just spins on its own as if it's setting up, it goes to an angle superior to the one I want it to go. (Don't mind if it has to set up but it can't spin more than 20 degrees which is currently doing).

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  myservo.write(0);
}

void loop() {
  for (pos = 0; pos <= degrees_of_motion; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos); // tell servo to go to position in variable 'pos'
    delay(servo_speed); // waits 15ms for the servo to reach the position
  }
  for (pos = degrees_of_motion; pos >= 0; pos -= 1) {
    // goes from 180 degrees to 0 degrees
    myservo.write(pos); // tell servo to go to position in variable 'pos'
    delay(servo_speed);// waits 15ms for the servo to reach the position
  }
}

```

# Answer
> 1 votes
What happens if you have a sketch such as the following? This uses the `loop()` function of the Arduino sketch to do one movement each time the `loop()` function is triggered.

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;   // variable to store the servo position
int direc = 1; // direction and amount of position iteration, + to increment, - to decrement

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  pos = 0;            // start off with zero degrees.
  direc = 1;          // start off incrementing the angle by 1
}

void loop() {
  if (direc > 0 && pos > degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = degrees_of_motion;
  }
  if (direc < 0 && pos < - degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = - degrees_of_motion;
  }

  myservo.write(pos);    // tell servo to go to position in variable 'pos'
  pos += direc;          // increment/decrement the position
  delay(servo_speed);    // waits 15ms for the servo to reach the position
}

```

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


# Question
Title: Notifications in constant loop (Blynk) trying to trigger along with serial function
This is an extension from a previous thread that was getting lengthy and off the original topic. I have the following code which monitors the state of a float switch (high or low). I upload the sketch, turn on the serial monitor and manually move the float switch up and down. The serial monitor output represents what I'm doing with the switch. The issue is that I get a constant loop of blynk notifications, every 15 seconds or so. Furthermore, if i move the switch to it's low position, the first blynk notification i get is correct reading "low", the following notifications are "high" thereafter. When the switch is moved to the high position, blynk just loops stating it's "high". I know it's weird and took quite a while to even establish what is going on here. but the biggest issue is the loop of notifications every 15 seconds.

```
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "ssid";
char pass[] = "pwd";
int flag=0;
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow && floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       Serial.println("Resevoir Water is Low!");
       Blynk.notify("Alert : Water Level low.");
       floatSavedState = floatLevelLow;
  } else if (floatLevelLow != floatSavedState)
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}

```

# Answer
Your code:

```
timer.setInterval(16000L,notifyOnButtonPress);

```

Is calling this function every 16s.

This code:

```
if (floatLevelLow && floatLevelLow != floatSavedState) {

```

needs some parentheses to force your desired order-of-operations. As it stands now, you are asking the result of `floatLevelLow && floatLevelLow` and comparing if that is not equal to `floatSavedState`. That's likely not what you want.

Did you mean:

```
if (floatLevelLow && (floatLevelLow != floatSavedState)) {

```

**EDIT:**

Also, your if/else is missing brackets around the 2nd clause and should be:

```
} else if (floatLevelLow != floatSavedState) {
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;
}

```
> 0 votes

---
Tags: arduino-uno, nodemcu, blynk
---


# Question
Title: Write a condition to execute 2 switch-case functions?
I'm new to programming and using Arduino products, and was wondering if someone wouldn't mind assisting me with a project I'm trying to tackle?

If you review my code below, I have 3 conditions within my "idle" case, and the program is constantly looking for any of those 3 conditions. If the first condition is met, then case 1 is called; if the second condition is met, then case 2 is called; if the third condition is met, then case 3 is called. All 3 cases return to the "idle" case once done running.

What I would like to do is find some way to insert the "warning" case if any of the conditions are met, BEFORE going to case 1, case 2 or case 3, without writing the functions of the "warning" case over each time for each of the other 3 cases. Essentially, the flow would be like this:

condition 1 --\> warning --\> case 1 --\> case idle;

condition 2 --\> warning --\> case 2 --\> case idle;

condition 3 --\> warning --\> case 3 --\> case idle:

```
void loop() {
  static byte theState = idle;
  switch (theState)
  {
    case idle:
      if (voltageA0 > 1.0) {
        theState = case1;
      }

      if (voltageA1 < 2.0) {
        theState = case2;
      }

      if (voltageA2 > 3.5) {
        theState = case3;
      }
      break;
    case warning:
      digitalWrite(7, HIGH);
      delay(5000);
      digitalWrite(7, LOW);
      delay(0);
      break;
    case 1:
      digitalWrite(8, HIGH);
      delay(2000);
      digitalWrite(8, LOW);
      delay(0);
      theState = idle;
      break;
    case 2:
      digitalWrite(9, HIGH);
      delay(2000);
      digitalWrite(9, LOW);
      delay(0);
      theState = idle;
      break;
    case 3:
      digitalWrite(10, HIGH);
      delay(2000);
      digitalWrite(10, LOW);
      delay(0);
      theState = idle;
      break;
  }
}

```

Also, if there is a more efficient way to do this, code-wise, I'm all ears!

# Answer
There is something incoherent in your code. It is structured as a finite state machine, and yet you are using `delay()` within it. In this kind of scenario, the whole purpose of a state machine is to avoid using `delay()`, so that your program never blocks. If your program happens to not have anything better to do than delaying, then you can forgo the state machine and write much simpler code. For example:

```
void warn_and_flash(byte pin)
{
    // Flash the "warning" LED.
    digitalWrite(7, HIGH);
    delay(5000);
    digitalWrite(7, LOW);

    // Flash the requested LED.
    digitalWrite(pin, HIGH);
    delay(2000);
    digitalWrite(pin, LOW);
}

void loop()
{
    if (voltageA0 > 1.0) warn_and_flash(8);
    if (voltageA1 < 2.0) warn_and_flash(9);
    if (voltageA2 > 3.5) warn_and_flash(10);
}

```
> 1 votes

# Answer
```
case idle:
  if (voltageA0 > 1.0 || voltageA1 < 2.0 || voltageA2 > 3.5) {
     digitalWrite(7, HIGH);
     delay(5000);
     digitalWrite(7, LOW);
     delay(0);

     if (voltageA0 > 1.0) {
        theState = case1;
        }

    if (voltageA1 < 2.0) {
       theState = case2;
       }

    if (voltageA2 > 3.5) {
       theState = case3;
       }
   }

```

EDIT: To clarify original answer, I inlined the "warning" code and deleted the "case warning", as obviously this state is not longer needed.
> 0 votes

---
Tags: atmega328, switch
---


# Question
Title: I keep getting an error message and I don't know how to fix it
I am using an Arduino Genuino, this is what comes up

```
Multiple libraries were found for "LiquidCrystal.h"
 Used: /home/user/Arduino/libraries/LiquidCrystal
 Not used: /opt/ArduinoIDE/libraries/LiquidCrystal
In file included from /home/user/Arduino/libraries/dht/DHT_U.cpp:22:0:
/home/user/Arduino/libraries/dht/DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory
 #include <Adafruit_Sensor.h>

                             ^
compilation terminated.
exit status 1

```

# Answer
The first notice about multiple libraries is not stopping you. The DHU library relies on the Adafruit Unified Sensor Library

You should have the following libraries (installed and) included:

```
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

```
> 1 votes

---
Tags: lcd, temperature
---


title: 2 Motor Robot Control with RC Radio

text:
# Question
Title: 2 Motor Robot Control with RC Radio
I am making a robot for a local robotics competition. One main function I need to do is move it forward, backward, right, left. Just like an RC car. I have programmed it to do that but it seems like the motors are not going the same speed as each other. When I move the stick just a little bit only one motor starts moving then when I go a bit further the only starts as well. I use an L293D and an Arduino UNO to control the 2 12v motors. I use a 6 channel receiver and transmitter for radio control. I think it might be something with the motor, but I might be missing something. Hopefully, someone can help me out. Thanks!

```
int motor1_in1 = 3; //H bridge direction pins
int motor1_in2 = 2; //H bridge direction pins
int motor2_in3 = 7; //H bridge direction pins
int motor2_in4 = 6; //H bridge direction pins

//the following are all ~PWM capable ports
int motor1_enable1 = 4; //H bridge motor 1 PWM PIN
int motor2_enable1 = 5; //H bridge motor 2 PWM PIN
int rc_channel2 = 10;
int rc_channel4 = 8;

void setup() {
  pinMode(rc_channel2, INPUT);
  pinMode(rc_channel4, INPUT);
  pinMode(motor1_in1, OUTPUT);
  pinMode(motor1_in2, OUTPUT);
  pinMode(motor1_enable1, OUTPUT);

  pinMode(motor2_in3, OUTPUT);
  pinMode(motor2_in4, OUTPUT);
  pinMode(motor2_enable1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  motorMoveForward();
  motorMoveSide();
  // delay(100);
}

void motorMoveForward()  {
  int pwm = 0;
  int rc2 = pulseIn(rc_channel2, HIGH, 25000);

  if (rc2 == 0) {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);
  }
  else if (rc2 > 1520) { //Backwards
    pwm = map(rc2, 1520, 1910, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, HIGH);
    digitalWrite(motor2_in3, HIGH);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, pwm);
    analogWrite(motor2_enable1, pwm);

    Serial.print(" DOWN    : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);

  }
  else if (rc2 < 1480) { //Forwards
    pwm = map(rc2, 1480, 1090, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, HIGH);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, HIGH);

    analogWrite(motor1_enable1, pwm);
    analogWrite(motor2_enable1, pwm);

    Serial.print(" UP     : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);
  }
  else {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);

    Serial.print(" CENTER  : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);
  }

}

void motorMoveSide()  {
  int pwm1 = 0;
  int rc4 = pulseIn(rc_channel4, HIGH, 25000);

  if (rc4 > 1520) { //RIGHT
    pwm1 = map(rc4, 1520, 1905, 0, 255); //map our speed to 0-255 range
    //digitalWrite(motor1_in1, LOW);
    // digitalWrite(motor1_in2, HIGH);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, HIGH);

    analogWrite(motor1_enable1, pwm1);
    analogWrite(motor2_enable1, pwm1);

    Serial.print(" RIGHT   : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);

  }
  else if (rc4 < 1480) { //LEFT
    pwm1 = map(rc4, 1480, 1090, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, HIGH);
    digitalWrite(motor1_in2, LOW);
    //digitalWrite(motor2_in3, HIGH);
    //digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, pwm1);
    analogWrite(motor2_enable1, pwm1);

    Serial.print(" LEFT    : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);
  }
  else {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);

    Serial.print(" CENTER  : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);
  }

}

```

# Answer
> 1 votes
From your code I would say, the problem lies within your loop function. The functions `motorMoveForward()` and `motorMoveSide()` are both over very quickly. But to actually move your motors need some time, before you change directions. Currently the motors rapidly change between driving forward and sidewards. Since in your `motorMoveSide()` function you only change direction for one of the motors, this one will rapidly being told to move forward and backwards. That results in the motor to move slowly or to not move at all. You simply cannot move forward and sidewards at the same time.

If you just want to controll the movement of your robot via RC, it may be better to use one channel just for speed value (for example 0 --\> stop, 255 --\> full power) and one for the direction (for example 0 --\> full power left, 127 --\> just forward, 255 --\> full power right). A normal RC car works the same way. Or you can take one channel for one motor (and mapping speed and direction of the specific motor like you did with both motors). Which way to go depends also on your remote (e.g. what is best for controlling it with the remote).

---
Tags: arduino-uno, motor, remote-control, l293d
---


title: Commucinate two arduino with each other

text:
# Question
Title: Commucinate two arduino with each other
I have 2 arduino Unos where each one works properly on its own.

I try to make them communicate with each other using serial communication (TX-RX ports).

When I try to upload my code to them I get this error :

```
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

```

what should i do to fix it ? (MY os is windows 10) thanks

# Answer
> 1 votes
Pins 0 and 1 on the Arduino Uno are used for serial communication with the computer over USB, including uploading sketches. If you connect anything to those pins you can interfere with the upload process.

To communicate between the two boards using serial communication without using pins 0 and 1 you can do software serial on other pins: https://www.arduino.cc/en/Reference/SoftwareSerial

---
Tags: serial, communication
---


# Question
Title: Arduino: Reading DS18B20 interferes with servo
I have an Arduino with a servo, INA219 (current and voltage sensor) and 2 DS18B20 connected to it.

DS18B20 are connected in full-power mode with 5k resistor connected between DATA line and +5V.

I use DallasTemperature library: https://github.com/milesburton/Arduino-Temperature-Control-Library

I get the temperature readings, but the problem is that my servo is jittering slightly almost every time temperature reading is done. If I disconnect DATA line from pin 2 (where it's normally connected) then servo is not moving anymore and everything is fine.

Any ideas what might be causing it? I would expect servo interfering with OneWire readings, not the other way around :)

Here is the full code: https://pastebin.com/xcES4PVT

Here is the minimal example with which I can reproduce the problem:

```
    #include <DallasTemperature.h>
#include <Servo.h>

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

Servo myservo;

long previousMillis = 0;

long tempRequestedMillis = 0;

bool tempRequested = false;

void setup(void)
{
  // start serial port
  Serial.begin(115200);
  Serial.println("Dallas Temperature IC Control Library Demo");

  myservo.attach(9);

  // Start up the library
  sensors.begin();
  sensors.setWaitForConversion(false);
}

void loop(void)
{

  unsigned long currentMillis = millis();
  if (!tempRequested && currentMillis - previousMillis > 2000) {
    previousMillis = currentMillis;

    sensors.requestTemperatures(); // Send the command to get temperatures

    tempRequestedMillis = currentMillis;
    tempRequested = true;
  } else if (tempRequested && currentMillis - tempRequestedMillis > 2000) {
    Serial.println(sensors.getTempCByIndex(0));
    tempRequested = false;
  }
}

```

# Answer
Arduino's Servo library on AVR uses interrupts; if interrupts are disabled for any amount of time, the servos will twitch.

1-Wire protocol (used by DS18B20) needs to disable interrupts for the protocol to work. Therefore, servos glitch.

There is a great explanation of the problem here: https://learn.adafruit.com/neopixels-and-servos/overview , just mentally replace "Neopixel library" with "OneWire library". Their TiCo\_Servo library sounds just like what you want.
> 6 votes

# Answer
Reading a DS18B20 the naive way takes up to 1500ms because you have to trigger a temperature conversion, then wait for it to complete.

If you have them full-powered, you better trigger the conversion, continue with your program and read the result 2 seconds later, when it's done. You can also trigger the conversion on all connected DS18B20 simultaneously by using the Skip ROM command before sending the Convert T command.

Please see the documentation of Maxim/Dallas' library how to do that.
> 1 votes

---
Tags: servo, ds18b20
---


# Question
Title: SSD1306 / U8glib display fonts and commands
I cannot seem to find any reference for the SSD 1306 or U8glib display font library or any command reference, like all the options for display() etc. For my fonts I been going into the utility folder and scrolling through notepad for the U8glib library but its very croweded with numbers and code. is there any reference for both libraries online that is user friendly?

# Answer
First, u8glib is superceded by u8g2

Second, the u8glib wiki has a command reference and font reference.

As does the u8g2 wiki.

Neither reference lists a `display()` command.
> 2 votes

---
Tags: library, display, u8glib, command-line
---


# Question
Title: using special symbols from the U8glib library
I enter font symbols into the u8g.setFont() and I get a string of sympols. How do I grab just one of those symbols, for example an arrow?

# Answer
> 1 votes
`setFont` just tell how display the next `drawStr` (or similar text output function).

To draw an arbitrary UTF8 char, just use

**drawUTF8**

C++/Arduino Prototype:

```
u8g2_uint_t U8g2::drawUTF8(u8g2_uint_t x, u8g2_uint_t y, const char *s)

```

**C Prototype:**

```
u8g2_uint_t u8g2_DrawUTF8(u8g2_t *u8g2, u8g2_uint_t x, u8g2_uint_t y, const char *s);

```

**Description:**

Draw a string which is encoded as UTF-8. There are two preconditions for the use of this function:

* The C/C++/Arduino compiler must support UTF-8 encoding (this is default for the gnu compiler, which is also used for most Arduino boards), and
* The code editor/IDE must support and store the C/C++/Arduino code as UTF-8 (true for the Arduino IDE).

If these conditions are met, you can use the character with code value greater than 127 directly in the string (of course the character must exist in the font file, see also **setFont**).

Advantage: No escape codes are required and the source code is more readable. The glyph can be copied and paste into the editor from a "char set" tool.

Disadvantage: The code is less portable and the strlen function will not return the number of visible characters. Use getUTF8Len instead of strlen.

Arguments: u8g2: A pointer to the u8g2 structure. x, y: Position of the first character on the display. s: UTF-8 encoded text.

Returns: Width of the string.

Note 1: This drawing function depends on the current font mode and drawing color. Note 2: Use the print function to print the value of a numeric variable.

See also: **setFont** drawStr print

Example:

```
u8g2.setFont(u8g2_font_unifont_t_symbols);
u8g2.drawUTF8(5, 20, "Snowman: ☃");

```

---
Tags: u8glib
---


# Question
Title: Communication between Arduino Uno and Mega
I am working on a project which uses a set of sensors (HC-SR04). These sensors use pins 2 to 13 of the Arduino Uno. Here you can find the board:

.

I also want to add an MP3 shield (VS1053B) to it and it fills all the pins on Arduino. So I decided to add an Arduino Mega and add the sensors to it and use the Arduino Uno and MP3 shield. The problem is with connecting these two Arduinos. As I said the MP3 shield fills A4 and A5 pins too, so I can not use them to communicate with the Mega. What other options do I have?

# Answer
> 3 votes
You can multiplex the trigger line. With 3 pins you can address up to 8 sensors. If you multiplex the reply line as well (so you can abstract out the latency) you only need 2 additional pins for the actual trigger and reply.

# Answer
> 1 votes
Salam, you could somewhat multiplex the HC-SR04 Ultrasonic Sensor by using I2C(IIC) instruction on how to convert those into I2C and by using OctoSonar library can be found here so that only the SDA(pin16) and SCL(pin17) pins on your Arduino UNO will be used. https://hackaday.io/project/19950-hc-sr04-i2c-octopus-octosonar

---
Tags: arduino-uno, arduino-mega, hc-sr04
---


# Question
Title: Arduino program does not start when plugged in
I am having trouble with my Arduino Mega with getting the program to start when the Arduino is plugged into a computer via USB. All that happens is the LED turns on and stays on. The device does not initialize, and only when I press the reset button does it begin the setup. How can I make the Arduino start the program when it is first plugged into the computer?

**EDIT:** my code

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

void loop() {
  Serial.println("test");
}

```

very simple, which is why i don't understand why this is happening

# Answer
> 1 votes
I would recommend you to follow the following instructions step by step to verify your Arduino Mega.

1. Reboot your computer
2. Connect the Arduino using the USB cable to PC and check the Arduino itself if there is any jumper wires connected/grounded. If there are then remove them all.
3. Upload a blank sketch first. Go to ***File -\> New***
4. Verify the Arduino has accepted the blank sketch and resetted.
5. Upload the Blink sketch from the ***File -\> Examples -\> 0.1Basics -\> Blink***
6. Verify if the Pin 13/onboard LED is blinking. If yes then go to uploading your sketch, if no then there is a hardware/bootloader problem with your Arduino. Watch this video on how to burn bootloader here. https://www.youtube.com/watch?v=X5achE10rCI

---
Tags: arduino-mega, usb
---


title: functions not running

text:
# Question
Title: functions not running
I have the following code as part of my efforts to clean this all up into more neatly organised functions.

I'm trying to run GetTemperatures and RunSerial as part of the main loop, however neither are being called.

If I uncomment the two code blocks I've tried to migrate into the functions in the main loop and comment out the calling of those two new functions, everything works ok.

I've looked through the arduino documentation and other places online but I'm unable to see where I've gone wrong.

```
#include <OneWire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//#include <DallasTemperature.h>

const char* ssid = "ssid";
const char* password = "password";

//This sketch is for Wemos R1 not Arduino
//Pin Assignment
OneWire  ds(D6);

//Digital Pin 4 Fan PWM pins)
int FanPin = D7; //Pin 4
int FanPWM = 0; //Start fans at max speed
int FanPercent = 100; // PWM power %

//Temperature thresholds

int Set0PCTemp = 26;   // Temp for 0% fan speed
//int MidTemp = 30;   // Max Temp for Min & Min Temp for Max
int Set100PCTemp = 36;   // Temp for 100% fan speed

// Temperature measurements

float MeasTemp;       //Measured temperature value
float DStemp;         //Value extracted from DS18B20 Sensor

// Serial port input values
int In0PCTemp;
int In100PCTemp;

ESP8266WebServer server(80);

void setup(void)
  {
  //analogWriteFreq(25000);
  pinMode(FanPin, OUTPUT);
  analogWrite(FanPin, 128);
  delay(1000);
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (MDNS.begin("esp8266"))
    {
    Serial.println("MDNS responder started");
    }
    server.on("/", handleRoot);
    server.on("/inline", []()
      {
      server.send(200, "text/plain", "this works as well");
      }
              );
    server.onNotFound(handleNotFound);
    server.begin();
    Serial.println("HTTP server started");
    //wifi end
    }

void handleRoot()
  {
  //declare CSV variables
  String CSVHeaders = "Set0PCTemp,Set100PCTemp,MeasTemp,FanPercent,FanPWM";
  String CSVMessage = "";
  String CSVPayload = "";
  //  Compile CSV variables
  //CSVMessage = Set0PCTemp + "," + Set100PCTemp + "," + MeasTemp + "," + FanPercent + "," + FanPWM;
  CSVMessage += Set0PCTemp;
  CSVMessage += ",";
  CSVMessage += Set100PCTemp;
  CSVMessage += ",";
  CSVMessage += MeasTemp;
  CSVMessage += ",";
  CSVMessage += FanPercent;
  CSVMessage += ",";
  CSVMessage += FanPWM;
  CSVPayload = CSVHeaders;
  CSVPayload += "\n";
  CSVPayload += CSVMessage;
  //  char CSV_Payload[] = CSVPayload;
  //notify serial port of HTTP request
  Serial.println( "Sending Readings");
  Serial.println(CSVPayload);
  server.send(200, "text/plain", CSVPayload);
  }

void handleNotFound()
  {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++)
    {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }
  server.send(404, "text/plain", message);
  }

void GetTemperature ()
  {
    Serial.println("step1");
  //original
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float DStemp;
  //////
  if ( !ds.search(addr))
    {
    Serial.println("step2");
    ds.reset_search();
    delay(250);
    return;
    }
  if (OneWire::crc8(addr, 7) != addr[7])
    {
    Serial.println("CRC is not valid!");
    return;
    }
    // the first ROM byte indicates which chip
    switch (addr[0])
      {
      case 0x10:
      type_s = 1;
      break;
      case 0x28:
      type_s = 0;
      break;
      case 0x22:
      type_s = 0;
      break;
      default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
      }
    Serial.println("step3");
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    delay(1000);
    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad
    for ( i = 0; i < 9; i++)
      {
      data[i] = ds.read();
      }
    // Convert the data to actual temperature
    int16_t raw = (data[1] << 8) | data[0];
    if (type_s)
      {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10)
        {
        raw = (raw & 0xFFF0) + 12 - data[6];
        }
      }
    else
      {
      byte cfg = (data[4] & 0x60);
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      }
  DStemp = (float)raw / 16.0;
  }

void RunSerial()
  {
        Serial.print(Set0PCTemp);
    Serial.print(",");
    Serial.print(Set100PCTemp);
    Serial.print(",");
    Serial.print(DStemp);
    Serial.print(",");
    MeasTemp = DStemp;
    //control fan speed
    //if(MeasTemp < Set0PCTemp)
     //{
     // if temp is lower than minimum temp
       //FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 255, 0); // the actual speed of fan
       FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 1023, 0); // the actual speed of fan
       //FanPWM = constrain(FanPWM, 0, 255);
       FanPWM = constrain(FanPWM, 0, 1023);
       analogWrite(FanPin, FanPWM);  // spin the fan at the fanSpeed speed
       //FanPercent = map(FanPWM,0,255,100,0);
       FanPercent = map(FanPWM,0,1023,100,0);
       Serial.print(FanPercent);
       Serial.print(",");
       Serial.println(FanPWM);
       //Serial.println(CSVMessage);
       //}
       //take temperature threshold input
      while (Serial.available() > 0)
        {
        int In0PCTemp = Serial.parseInt();
        int In100PCTemp = Serial.parseInt();
        if (Serial.read() == '\n')
          {
          In0PCTemp = constrain(In0PCTemp, 20, 35);
          In100PCTemp = constrain(In100PCTemp, 35, 50);
          Serial.print("Min=");
          Serial.print(In0PCTemp);
          Serial.print(",");
          Serial.print("Max=");
          Serial.print(In100PCTemp);
          Serial.println();
          Set0PCTemp = In0PCTemp;
          Set100PCTemp = In100PCTemp;
          }
      }
  }

void loop(void)
  {
    GetTemperature;
  //start of GetTemperature content
  /*
  Serial.println("step1");
  //original
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float DStemp;
  //////
  if ( !ds.search(addr))
    {
    Serial.println("step2");
    ds.reset_search();
    delay(250);
    return;
    }
  if (OneWire::crc8(addr, 7) != addr[7])
    {
    Serial.println("CRC is not valid!");
    return;
    }
    // the first ROM byte indicates which chip
    switch (addr[0])
      {
      case 0x10:
      type_s = 1;
      break;
      case 0x28:
      type_s = 0;
      break;
      case 0x22:
      type_s = 0;
      break;
      default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
      }
    Serial.println("step3");
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    delay(1000);
    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad
    for ( i = 0; i < 9; i++)
      {
      data[i] = ds.read();
      }
    // Convert the data to actual temperature
    int16_t raw = (data[1] << 8) | data[0];
    if (type_s)
      {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10)
        {
        raw = (raw & 0xFFF0) + 12 - data[6];
        }
      }
    else
      {
      byte cfg = (data[4] & 0x60);
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      }

    //Display current values
    DStemp = (float)raw / 16.0;
    */
    //end of GetTemperature content
    RunSerial;
    //start of RunSerial content
    /*
    Serial.print(Set0PCTemp);
    Serial.print(",");
    Serial.print(Set100PCTemp);
    Serial.print(",");
    Serial.print(DStemp);
    Serial.print(",");
    MeasTemp = DStemp;
    //control fan speed
    //if(MeasTemp < Set0PCTemp)
     //{
     // if temp is lower than minimum temp
       //FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 255, 0); // the actual speed of fan
       FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 1023, 0); // the actual speed of fan
       //FanPWM = constrain(FanPWM, 0, 255);
       FanPWM = constrain(FanPWM, 0, 1023);
       analogWrite(FanPin, FanPWM);  // spin the fan at the fanSpeed speed
       //FanPercent = map(FanPWM,0,255,100,0);
       FanPercent = map(FanPWM,0,1023,100,0);
       Serial.print(FanPercent);
       Serial.print(",");
       Serial.println(FanPWM);
       //Serial.println(CSVMessage);
       //}
       //take temperature threshold input
      while (Serial.available() > 0)
        {
        int In0PCTemp = Serial.parseInt();
        int In100PCTemp = Serial.parseInt();
        if (Serial.read() == '\n')
          {
          In0PCTemp = constrain(In0PCTemp, 20, 35);
          In100PCTemp = constrain(In100PCTemp, 35, 50);
          Serial.print("Min=");
          Serial.print(In0PCTemp);
          Serial.print(",");
          Serial.print("Max=");
          Serial.print(In100PCTemp);
          Serial.println();
          Set0PCTemp = In0PCTemp;
          Set100PCTemp = In100PCTemp;
          }
      }
      */
      //end of RunSerial content
      //wifi
      server.handleClient();
  }

```

# Answer
```
RunSerial;

```

that does not call the function. Instead you should do

```
RunSerial();

```

same with `GetTemperature`
> 2 votes

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


title: 3D printer firmware version

text:
# Question
Title: 3D printer firmware version
Is there a way to determine which version of a Marlin firmware I would have installed onto my printer? I am trying to modify the existing arduino sketch rather than starting all over with a wrong, earlier version. Thanks.

# Answer
First, check to see if the printer itself yields this information, either on LCD display if present, or by reporting it to a host computer upon connection (ie, try enabling verbose output in your printing software).

While it's not guaranteed to be supported, in practice many Arduino Mega based 3d printers have bootloaders capable of readback of the flashed contents, and the chips themselves are unlocked. Even if the bootloader does not support this, an ISP connection might.

If you are able to read out the contents, you can have `avrdude` write them to a flat binary file, and examine it with the `strings` program or a hex editor. If you end up with a hex file instead, there are tools for converting this to a flat binary.

Your goal would be to look through the file for version strings, and other messages which might indicate specifics, especially on which side of various points of change or configuration options it falls.

Making such a backup is a good idea before loading a new firmware anyway. Ideally after verifying that you obtained meaningful contents, you would also readback a few distinct copies of the file and use something like `diff` to verify that they are all the same. You can grab the EEPROM contents too, if your firmware may be storing things there.
> 1 votes

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


title: Parse Bluetooth string

text:
# Question
Title: Parse Bluetooth string
I'm developing on android with bluetooth LTE, I can send hex codes, but I send one code at time, so I need to send many informations in this way, how can I recognize a string and save the datas inside an array to parse it later?

Here is my sketch:

```
 char c=' ';
 String inString,one,check;
 char inData[11];
 char inChar;
 int counter=0;
 bool started = false;
 bool ended = false;
 byte index;

boolean NL = true;
const int LED1 = 6;
const int LED2 = 7;
const int LED3 = 2;
const int LED4 = 3;
const int LED5 = 4;
const int LED6 = 5;

void setup() {
   Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");

    BTserial.begin(9600);
    Serial.println("BTserial started at 9600");

    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    pinMode(LED5, OUTPUT);
    pinMode(LED6, OUTPUT);

}

void loop() {

  if (BTserial.available()>0)
    {
      Serial.print("bts: ");
      Serial.println(BTserial.available());
      c = BTserial.read();
      check =  String(c, HEX);

      if(check=="ffbc"){
        Serial.println("check");
        index=0;
        while (BTserial.available()>0){

            inChar = BTserial.read();
            check=String(inChar,HEX);
            if(check != "0xfff3")
            {
                inData[index] = inChar;
                index++;
            }
        }
        for (int i=0;i<=11;i++){
          one =  String(inData[i], HEX);
          Serial.print(i);Serial.print(": ");Serial.println(one);
        };

      }

             if(check=="ffca"){
             // Serial.write(c);
              digitalWrite(LED1, !digitalRead(LED1));
             }
             if(check=="ffcb"){
              //Serial.write(c);
              digitalWrite(LED2, !digitalRead(LED2));
              }
              if(check=="ffcc"){
              //Serial.write(c);
              digitalWrite(LED3, !digitalRead(LED3));
             }
             if(check=="ffcd"){
              //Serial.write(c);
              digitalWrite(LED4, !digitalRead(LED4));
              }
              if(check=="ffce"){
             // Serial.write(c);
              digitalWrite(LED5, !digitalRead(LED5));
             }
             if(check=="ffcf"){
             // Serial.write(c);
              digitalWrite(LED6, !digitalRead(LED6));
              }
    }
}

```

Without the loop I can read all the single datas, but for my job it's not enough, to recognize the data applications I send a "sample string" to recognize the type of informations I want to send.

# Answer
> 1 votes
i think i solved in some way, i send always the same codes at the start and at the end of the datas, so i can racognize the end and then i parse the first element of the destination array. tell me what you think abou, if it could help someone else:

```
 if (BTserial.available()>0)
{
  c = BTserial.read();
  check =  String(c, HEX);
  if(check!="fff3"){              // i always start wit an fff3
  inData[index] = c;
  index++;
 }
  else if(check=="fff3"){         //end of data
  index=0;                        //reset the index for the next set of data
  if(String(inData[1], HEX)=="ffbc"){
    Serial.println("read the next 10 data of the array");
    }else if(String(inData[1], HEX)=="11"){
    Serial.println("turn on led 1");
    }

    // for more operations use a switch/case over the if

  }

```

---
Tags: bluetooth
---


# Question
Title: Power Arduino Due and 6 servo motor with Battery
I would like to create a project contains 6 servo motors and Arduino Due board, but I have no idea how to operate should I use only a 9V battery only or in addition to 4 AAA battery?

# Answer
> 0 votes
There is no best way in general. With your setup you may use a 9V battery as input for the Due (over the power jack, which wants voltage between 7V and 12V) and using a voltage regulator to get maybe 6V from your 9V battery voltage for your servos. Make sure, you get a regulator that can give you enough current for the 6 servos (You can find this info in the datasheet of the servo motors).

Of course you can also drive your project with 2 different battery packages, like you have described it in your question. Note, that you have to connect both grounds to make this work.

---
Tags: power, motor, arduino-due, servo, battery
---


# Question
Title: ACS712 to build doorbell sensor - Arduino Hangs up
I have a ACS712 module that I am connecting to my Arduino Uno to read the current spike when my door bells rings (and then trigger some events in my "sketch").

In my country doorbells use the ~115 VAC at ~60Hz. So, I just opened the doorbell and connected the ACS712 module in series.

I do not know how much amperage my doorbell draws, but it is hardly the 30A supposedly supported by the module.

At this point I am *not* connecting the OUT pin to the Arduino, only VCC and GND to the +5V and GND of the Arduino Uno. (I am also tried connecting the OUT pin to A2 in the Arduino).

What happens is that as soon as I ring the doorbell the Arduino hangs up. Sometimes I even have to physically unplug the Arduino to get it back to life.

It doesn't necessarily happens in the first bell, but it does not survive 3 rings in a row.

The ACS712 chip is supposed to provide 2.1 kVRMS of isolation... it doesn't seem likely that the "kickback" from the bell would be 2100 VAC... so I cannot imagine how/why my Arduino is hanging up, when it is supposed to be completely isolated from the AC (that's the whole point of the Hall Effect current sensor).

I added some capacitors to the VCC/GND pins with no luck.

So... any ideas on 1) how to protect the Arduino from hanging up?, 2) what is making the Arduino hang up?.

# Answer
> 1 votes
There are two probable solutions to your problem:

1. The ACS712 is a hall effect based sensor and also door bells have a solenoid attracting a hammer to hit the bell. Try and place the sensor away from the bell, this could avoid any possible magnetic interference. (This is less likely to happen but there is a fair amount of chance)
2. May be, there is a problem with the code OR the laptops USB. Connect the Arduino to the sensor and the OUT pin to an analog input. Run the following code:

```
  void setup()
  {
     Serial.begin(9600);
  }
  void loop()
  {
     Serial.println(analogRead(A2));
  }

```

If this doesn't work, probably there's a problem with the sensor or the connections.

Give me more details about your connections, code and post a picture of your project for more help.

---
Tags: arduino-uno, current
---


# Question
Title: Connect NodeMCU (ESP8266) with normal Switch (Regular 1 way Home button)
i am new to these circuit things, i am using Node MCU (ESP8266) board with relay board. To connect to a bulb, but i want to keep my old (one way) switch as it is. Also i want to add internet switching to this button.

How my circuit should look like? Two way switch will be compulsory to use here? What my circuit should look like? with two way switch and one way switch.

Thank you! (in advance)

# Answer
First of all, a light bulb works on regular 110 or 230V AC depending on where you live, so directly connecting a wire to, for example, see if the hardware switch is turned on, would fry the NodeMCU. You'll need a relay break-out board that can handle these outputs on the COM/NO/NC (which most of them do) but they usually operate on 5V DC.

A NodeMCU can thus only supply the trigger signal to the relay, you'll need for example a AC to 5V DC power supply (like an iPhone adapter) to power your circuit. The circuit will contain of the relay board (connected with its DC in and out to the adapter and the com port to one of the GPIO's from the NodeMCU) and the NodeMCU itself as the 'brain' of the operation.

I don't exactly know what you mean by 'two-way switch' but the way I'd handle the situation is to wire the switch to the NodeMCU. This means the switch is connected to the 5V power adapter and when the switch is on, the nodeMCU will know because there will be a positive value at one of the GPIO's (whichever you choose). You can then also handle both commands from a server and the switch itself.

I'm doing kind off the same thing here with a NodeMCU working as a garageport opener with MQTT communication to a Homebridge server and MQTT broker running on a Raspberry Pi. If you want the code (still work in progress though) let me know ;)

**EDIT** Here is the schematic you asked for. not the prettiest thing but it should make things clear. Let me know if you have any more questions!

simulate this circuit – Schematic created using CircuitLab

-BM
> 2 votes

---
Tags: esp8266, nodemcu
---


# Question
Title: Arduino MEGA 2560 - PWM in case statements not working
So I am using Arduino to control RGB Strip light, the `analogueWrite(Pin,Value);` Works with the prebuilt AnalogueWriteMega example - on pins 8, 9, and 10.

When I move this into my program, Pin 8 still works but pins 9 and 10 don't work.

Anywhere I write `analogueWrite()` it only works if the value is 255

* Green is pin 8
* Red is pin 9
* Blue is pin 10

```
#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#include <LiquidCrystal.h>
// encoder
int val;
int encoder0PinS = 29;
int encoder0PinA = 31;
int encoder0PinB = 33;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;
int MenuPos;
int SubPos;
bool Selected = false;
int Reader = LOW;

// lcd
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//pot
int ASensePin = A0;
double ASenseValue = 0;
double AFixedValue = 0;
int AFixOut = 0;

//randoms
int ranPin;
int ranVal;

//IR

int receiver = 45; // Signal Pin of IR receiver to Arduino Digital Pin 45

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

void translateIR() { // takes action based on IR code received

  // describing Remote IR codes
  switch (results.value)
  {

```

---

```
    case 16195807:
      Serial.println("Red, 0, 255, 0");
      analogWrite(8, 0);
      analogWrite(9, 255);    < ------ works
      analogWrite(10, 0);
      break;

    case 16197847:
      Serial.println("Yellow, 255, 255, 0");
      analogWrite(8, 100);      < ----don't work
      delay(50);
      analogWrite(9, 100);       <----don't work
      delay(50);
      analogWrite(10, 0);
      break;

```

---

```
    case 16228447:
      Serial.println("green, 255 , 0, 0");
      analogWrite(8, 255);
      analogWrite(9, 0);
      analogWrite(10, 0);
      break;

    case 16230487:
      Serial.println("turquois, 0, 255, 255");
      analogWrite(8, 0);
      delay(50);
      analogWrite(9, 100);
      delay(50);
      analogWrite(10, 100);
      delay(50);
      break;

    case 16212127:
      Serial.println("blue, 0, 0, 255");
      analogWrite(8, 0);
      analogWrite(9, 0);
      analogWrite(10, 255);
      break;

    case 16214167:
      Serial.println("Purple, 255, 0, 255");
      analogWrite(8, 100);
      delay(50);
      analogWrite(9, 0);
      delay(50);
      analogWrite(10, 100);
      delay(50);
      break;

    case 16244767:
      Serial.println("White, 255, 255, 255");
      analogWrite(8, 255);
      analogWrite(9, 255);
      analogWrite(10, 255);
      break;

    default:
      Serial.println(results.value);
  }// End Case

  delay(500); // Do not get immediate repeat
} //END translateIR

void setup() {
  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  pinMode (encoder0PinS, INPUT);
  pinMode (8, OUTPUT);
  pinMode (9, OUTPUT);
  pinMode (10, OUTPUT);

  lcd.begin(16, 2);
  lcd.print("      Start     ");

  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Pos--;
    } else {
      encoder0Pos++;
    }
  }
  encoder0PinALast = n;
  if (encoder0Pos == 4) {
    encoder0Pos = 0;
  }
  if (encoder0Pos == -1) {
    encoder0Pos = 3;
  }

  MenuPos = encoder0Pos;

  Reader = digitalRead(encoder0PinS);
  // Serial.println(Reader);

  if (digitalRead(encoder0PinS) == LOW) {
    while (digitalRead(encoder0PinS) == LOW) {}
    Selected = true;
  }

  Serial.println("MenuLoop");
  switch (MenuPos) {
    case 0:
      lcd.setCursor(0, 0);
      lcd.print("     Random    ");
      while (Selected == true) {
        ranPin = random(8, 10);
        ranVal = random(0, 255);
        analogWrite(ranPin, ranVal);

        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }
      break;

    case 1:
      lcd.setCursor(0, 0);
      lcd.print("       IR      ");
      Serial.println("IR Receiver Button Decode");
      irrecv.enableIRIn(); // Start the receiver

      while (Selected == true) {
        if (irrecv.decode(&results)) // have we received an IR signal?
        {
          translateIR();
          irrecv.resume(); // receive the next value
          lcd.setCursor(0, 1);
          lcd.print("               ");
          lcd.setCursor(0, 1);
          lcd.print(results.value);
        }
        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }

      break;

    case 2:
      lcd.setCursor(0, 0);
      lcd.print("      Temp     ");
      break;

    case 3:
      lcd.setCursor(0, 0);
      lcd.print("      Pot      ");

      while (Selected == true) {

```

---

Not working

```
        for (int thisPin = 8; thisPin <= 10; thisPin++) {
          // fade the LED on thisPin from off to brightest:
          for (int brightness = 0; brightness < 255; brightness++) {
            analogWrite(thisPin, brightness);
            delay(2);
          }
          // fade the LED on thisPin from brightest to off:
          for (int brightness = 255; brightness >= 0; brightness--) {
            analogWrite(thisPin, brightness);
            delay(2);
          }
          // pause between LEDs:
          delay(100);
        }

```

---

```
        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }
      break;
  }
}

```

# Answer
The problem has nothing to do with your switch code. It's all to do with what you are *trying* to do, and peripherals conflicting.

Simply put: both PWM on pins 9 & 10, and the infrared library, require exclusive use of Timer 2.

Only one can use it. Either the infrared library, or PWM on those two pins, but not both.

You can modify the IR library to use a different timer instead of Timer 2 - for instance, you can set it to use Timer 1 which will remove your ability to use pins 11 and 12 as PWM.

This is the bit of code that you would need to find and modify on your system to change timers. This page shows you which timers are used for PWM on which pins.
> 4 votes

---
Tags: arduino-mega, pwm
---


# Question
Title: Is it possible to extract a hex file via UART from an Arduino?
Right now I am tinkering on my 3D printer that has an Arduino mega as a brain. I need to update the Marlin firmware but in case of an error I want to create an backup of the firmware. And because it is assembled using a shield on top have no access to the ICSP interface. And I was curious if you can extract all the flash and EEPROM via USB (UART). If yes than what software should I use to do that.

# Answer
AVRDUDE which is used by the IDE to send the content of HEX file from your computer, as a feature letting it to get back the data of the flash, in order to compare and see if data are correct.

For a UNO try:

```
avrdude -patmega328p -carduino -P/dev/cu.usbmodemFD121 -b115200 -U flash:r:"flash.bin":r

```

I think it would not be very hard to change that for a Mega.

It works fine. I have use that a lot to debut my "Android Updater" which allow the user of my board to update the code themselves.

PS: Just for info, you'll not get back the HEX file as in the flash, you have only some "pieces" of the HEX file.
> 5 votes

# Answer
*It looks like my other answer was completely wrong, so I've deleted it.*

---

**Yes**, you can read back the flash using the USB interface, as Chris Stratton pointed out, and Peter mentioned in his answer.

The bootloader includes a "verify" action, which means it can be used to read the flash. If you connect up the USB cable to your Atmega2560 you can read the flash back by using a command similar to this:

```
/usr/local/bin/arduino-1.6.9/hardware/tools/avr/bin/avrdude  `# where avrdude is`  \
-patmega2560     `# chip type: atmega2560` \
-cstk500v2       `# protocol: stk500 v2` \
-P/dev/ttyACM2   `# what serial (hardware) port the board appears on` \
-b115200         `# baud rate` \
-U flash:r:"flash.hex":i   `# save flash as "flash.hex", in Intel format` \
-C /usr/local/bin/arduino-1.6.9/hardware/tools/avr/etc/avrdude.conf  # config file for avrdude

```

This was done under Linux, with the command in "bash" format, which means the comments look a little strange, as I had to do that to put a comment on each line.

I've put comments on each line to show what each parameter means.

If you happen to have avrdude in your path, or are in the directory where it is installed, the brief form of the command would be:

```
avrdude -patmega2560 -cstk500v2 -P/dev/ttyACM2 -b115200 -U flash:r:"flash.hex":i -C avrdude.conf

```

You will probably (almost certainly) have to change the path to where avrdude is, and where the configuration file for avrdude is. You will also need to find out the serial port that the board is on, which you can find out from the Arduino IDE (the Port menu will show you the possibilities).

---

As Chris Stratton suggests, do this a few times (change the file name of course) and compare the files (eg. using "diff"). If they are all the same then you can be reasonably confident that you have got good copies.
> 2 votes

---
Tags: uart, firmware
---


title: ESP8266 as wifi Card?

text:
# Question
Title: ESP8266 as wifi Card?
I am very new to arduino and electronics in general. Can i use the NodeMcu Esp8266 as one of those usb wifi dongles? I want to use it as a monitor mode capable wifi card, for my linux laptop.

# Answer
No, you can't. All you have is a UART interface through a USB to UART adaptor. It can only ever be a UART.

The best you could get would be to write a program to run on the NodeMCU that did the monitoring for you (assuming you can get it into a suitable promiscuous mode) and report information back to you through the UART.
> 3 votes

---
Tags: esp8266, wifi, electronics, linux
---


# Question
Title: Why I'm getting this error: invalid conversion from 'const char*' to 'char' [-fpermissive]?
Why I'm getting this error?

`invalid conversion from 'const char*' to 'char' [-fpermissive]`

Here is my simple sketch:

```
const char data = "should";

//I have also tried:
//const char* data = "should";

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

void loop() {
  Serial.print("this " + data + " work");
}

```

# Answer
> 4 votes
```
const char data = "should";

```

In this case `data` is a single character, not a string. So it can store `'s'` but not `"should"`.

```
Serial.print("this " + data + " work");

```

No, that will never work, even if you get your data types correct. You do not concatenate strings like that. All you are doing is attempting to add the addresses of two string literals to the address of a string constant. If that were possible (the compiler doesn't let you) you'll get gibberish (or a crash) as it tries to print out whatever is at that address.

Instead break it down:

```
Serial.print("this ");
Serial.print(should);
Serial.print(" work");

```

# Answer
> 1 votes
A char can only store one character.

and const char\* data can store a pointer to a string.

You can copy it with strcpy:

```
const char* data = malloc(7);
if (data != 0)
{
    strcpy(data, "should");
}

```

This will create 7 bytes, which can store "should" (adding 1 byte extra for the \0 byte to denote the end of a string.

However, in your case you can create a const string like:

```
const char data[7]="should";

```

or

```
const char data[]="should";

```

---
Tags: arduino-ide, constants
---


# Question
Title: Preventing relay switch-off crashing Ethernet controller
I have an Arduino Uno with Ethernet Shield controlling some relays. Initially everything works fine but then when switching the relay off, the Ethernet controller frequently 'crashes'. Ethernet stops responding to pings, although the Arduino Uno keeps running. Pressing the reset button brings the Ethernet controller back to life.

I am using three relays to control:

* The 'Call for Heat' contact on the boiler (normally connected to a thermostat)
* A Honeywell V4043 zone valve (6W / 0.42A)
* A Grundfos UPS2 underfloor heating pump (0.06A - 0.42A)

This is my setup:

* I am using 2N7002 MOSFETs to drive the relays
* I have 1N4004 diodes across the coils

There is a circuit diagram for the 'Relay Driver Shield' part of the circuit here:
https://github.com/njh/relay-driver-shield

This is what I have done to attempt to solve the problem:

* I have moved the Arduino + Ethernet further away from the relays
* I switched to higher quality Omron Relays (G2R-1-S-DC12)
* I have tried both Wiznet W5100 and ENC28J60 Ethernet controllers

But so far nothing has solved the problem.

Of the three relays, it appears to be the Honeywell V4043 zone valve that is causing the problem. While testing with no loads connected to the relays, it was working fine. My assumption is that the problem is related to discharges across the contacts, partly due to the inductive loads. But I am not sure what to do to fix it.

Thanks,

nick.

# Answer
I would suggest two things:

1. Use opto-isolators instead of (or as well as) the MOSFETs to control the relays, and
2. Add RC snubber circuits across the contacts.

The latter is the most important, since the spark across the contacts when they open will cause massive amounts of EMI.

The simplest circuit is a simple series resistor and capacitor placed across the contacts:

simulate this circuit – Schematic created using CircuitLab

Of course, ensure that the resistor and capacitor are rated for *at least* the voltage you are switching, preferably double.

Selecting the right values for the components depends very much on the load being switched and how much energy needs to be absorbed. I have shown ball-park figures that are usually "ok" for many situations.
> 1 votes

---
Tags: arduino-uno, ethernet, relay
---


# Question
Title: Using SD library in a ESP-IDF project on ESP32
I just started to move from the **Arduino** firmware to the **esp-idf** firmware. I read that link. I learn that I have to include libraries creating a component files, with a `component.mk` file, `*.c`, `*.cpp` files and an `include/` folder for `*.h` files. That was ok for most of libraries I had to include, except for the SD card library, more precisely the `Sd2PinMap.h` header.

It seems that **ESP32** is not recognized:

```
$(IDF-PATH)/Project/components/SD/include/Sd2PinMap.h:510:2: error:
#error Architecture or board not supported.

```

but with the **Arduino** firmware, there were no problems.

I checked `make menuconfig` options, but I didn't find a way to make it work for an ESP32 board... Any ideas ?

# Answer
> 0 votes
Okay, the solution was simple, I just had to pull the update for the SD Card library, mine was outdated. Thank you all.

---
Tags: sd-card, esp32, makefile
---


# Question
Title: Will adding Ethernet shield reduce the IO count of Arduino?
I have searched this question but could not find an answer on this site.

There was a related question - `Latest Ethernet shield - used pins, how to bypass restrictions` on arduino forums, but, I was unable to understand what the answer meant.

**The background of my project:**

My project requires

```
| S.No. | IO Type | IO Qty |
|-------+---------+--------|
| 1     | AI      |     11 |
| 2     | DI      |      9 |
| 3     | DO      |     11 |

```

I intend to connect this arduino board via ethernet shield to a network. I want to receive data over the network for display and storage purposes on a PC.

**Questions:**

1. What Arduino board should I select?
2. Will **ESP8266** be compatiable with the suggested model?
3. Are there any pitfalls that should be considered when making the selection for this design.

*P.S: I have raised the same question on the arduino forum. If I get an answer- I will share my answer here as well*

# Answer
You should use a Mega if you really need so many gpio pins.

Arduino Ethernet and WiFi shields and their clones use 3 GPIO pins with SPI function with connection on ICSP header. Next they use the Slave Select signaling pin 10 and the SD card Slave Select signaling pin 4. The shields are compatible with Mega. So you should still have enough pins.

esp8266 can be connected to SPI. then it uses the same pins like the Ethernet shield except of the SD card slave select pin.

if you connect esp8266 to Serial port, then all the pins are free. Mega has 4 Serials.

esp8266 is cheaper but you need to connect it with level shifters and have a good power supply. there is no good esp8266 shield for now. The Mega + WiFi board from Robotdyn has the esp8266 on board with Serial connection.
> 2 votes

---
Tags: ethernet-shield
---


title: powering Nodemcu using Vin

text:
# Question
Title: powering Nodemcu using Vin
Forgive me for this really dumb question. I am an amateur in electronics, and im trying to wrap up my head around this question and im not able to do so. Need your help.

Im trying to power up a nodemcu using a 5v 1A power supply- I connected +ve to Vin and ground to ground. But i see that 5v is not enough to power up the nodemcu. So i removed the 5V and connected to a 9V battery, and again I find the same issue- the power is not enough. Knowing that i did something wrong - i measured the voltage across Vin and ground and find it to be around 2.5V when using the 5v source and around 2.5V when using the 9 V battery too.

Confused and thinking that my nodemcu is corrupted, i ordered a new one, and did the same. But i find that when i try to supply power using Vin, the voltage across the device- Vin and ground is around 2.5V for the newer device also. Obviously Im missing something.

Can anyone tell me what is it that Im doing wrong. Please tell me how to power a nodemcu without using a usb and only using a 5v source.

# Answer
I have a NodeMCU Esp8266 v3 (Lolin) and it works fine conecting Vin and G to my cell phone power supply rated 5.1V, 1000mA. This develop board has a aprotective diode (the closest to Vin), if you have a Multimeter o multitester you can check it measurement continuity. If your diode is damaged the power applied to Vin never be enough to power up the nodemcu.
> 2 votes

---
Tags: esp8266, power, nodemcu
---


title: Connecting TCD1304 with Arduino

text:
# Question
Title: Connecting TCD1304 with Arduino
I'm working on a project, where I will have 2 red light beams, where one will be constantly turned on while the other will be turned on and off continuously with frequency about 100 hz. I need to detect, on which side is the blinking beam and show it on the output (something such as if the blinking beam is on the left, turn green LED on; if it's on the right side, turn on the red LED). Each beam is big as 3mm circle.

I bought 3pcs (in case if I burn 2 of them :D) of Toshiba TCD1304 sensors(datasheet), which have 3684 elements in a row. I want to connect the sensor with Arduino, but I really don't know how I would even start this project. I've found some schematics, but it's either for some other model or is for different kind of a project(reading different colors over the field). Either way, none of them is useful for me.

It will look something like that at the end (the blue circle will be also red, but it's striped to show, it's the blinking one).

# Answer
The TCD1304's minimum OS-datarate is 200 kHz. Quite a lot more than what the arduino is capable of. You should look to faster processors or to a different sensor. The TSL1401 seems to be popular with the arduino-community.

If you /need/ the TCD1304, then an arduino due will probably be able to do it, but I'm guessing you'll have to drop the arduino-IDE to achieve the full speed of the ADC.

Here's how I've done it with a STM32F4 processor: https://tcd1304.wordpress.com/
> 2 votes

---
Tags: sensors
---


# Question
Title: Xbee shield to shield connection sends but not receives correctly
Setup: 2XArduino Uno 2x XBees S1 2x Sparkfun xbee shields.

My first arduino reads in values from a photoresistor and sends the values to the second arduino. I know for sure the arduino is sending values because when i plugged the second xbee directly into the computer and opened the serial monitor correct values showed up in the serial monitor. But the problem is when i attach the second Xbee onto its sparkfun shield and arduino i get repetitive wrong values .

Can someone please tell me what i am doing wrong? I am doing this to make sure i get the right values before i beef up the project.

Sender sketch

```
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <XBee.h>
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int photocellReading;     // the analog reading from the analog resistor divider
 SoftwareSerial XBee(2,3);
void setup(void) {

  Serial.begin(9600);
  XBee.begin(9600);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Wireless LightDimmer");

}
 void loop(void) {
  photocellReading = analogRead(photocellPin);
  lcd.setCursor(0, 1);
  lcd.print("Photocell= ");
  lcd.setCursor(11, 2);
  lcd.print(photocellReading);
  //Serial.println(photocellReading);
  lcd.setCursor(20, 0);
  lcd.print("Measured in lux");

  delay (500);
  lcd.setCursor(20, 3);
  lcd.print(" ");
 // Serial.print("Analog reading = ");
 // Serial.print(photocellReading);
   photocellReading = 1023 - photocellReading;
 unsigned int LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
   Serial.println( LEDbrightness);
    XBee.print(LEDbrightness);

  delay(1000);
}

```

recieving sketch

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

SoftwareSerial XBee(2,3);

void setup() {
 // Begin Serial communication
 Serial.begin(9600);
 }
void loop(){
 while ( Serial.available() > 0) {
 unsigned int num =  Serial.read();
 Serial.println(num);
 delay(2000);
 }
}

```

# Answer
> 1 votes
The xbee pins can only read up about 1.2V which it will show 256 bit. You should check how much the photoresistor is giving out because it might gives something that is more than the xbee pin can handle.

---
Tags: arduino-uno, serial, shields, xbee
---


title: SD begin affecting OLED display

text:
# Question
Title: SD begin affecting OLED display
Okay, I'm using `u8g2` library for my OLED display. After calling SD.begin(4) function, I cannot display anything on my OLED.

I'm using `U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);` constructor from `u8g2` library since I'm using `I²C` for the display and SPI for microSD reader. I removed the `CS Pin 4` from `SD.begin()` and I can now display something on the OLED.

How did supplying CS Pin parameter to `SD.begin()` function affected the `I²C` OLED display?

# Answer
> 1 votes
Pins 4 and 5 are the I2C pins that belong to the built in I2C peripheral on the Arduino. You have to put your CS line for the SPI SD card on a different pin.

**EDIT:** The answer above is relevant to the Arduino ATMega328-based board, not ESP8266-based NodeMCU board. This answer is not relevant to ESP8266 or NodeMCU with regard to hardware I2C, as the ESP8266 does not have a dedicated hardware I2C peripheral.

---
Tags: esp8266, i2c, spi, sd-card, display
---


# Question
Title: Arduino & NodeMCU, one server and multiple clients
I have seen another similar question and I followed the answer, but I cannot get my code to work for a single client properly.

In short, one NodeMCU provides AP and a WiFi server to multiple clients. The clients are supposed to stay connected. I am testing just a single client and it succeeds to connect and server reads just the first message, whereas all the subsequent messages are not received.

The server code:

```
#include <ESP8266WiFi.h>

#define MAX_CLIENTS 10

IPAddress    apIP(42, 42, 42, 42);
const char *ssid = "ESP8266";
const char *password = "ESP8266Test";
WiFiServer server(80);
WiFiClient *clients[MAX_CLIENTS] = { NULL };

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.begin();
}

void loop () {
  WiFiClient newClient = server.available();
  if (newClient) {
    Serial.println("new client");
    // Find the first unused space
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
      if (NULL == clients[i]) {
        clients[i] = new WiFiClient(newClient);
        break;
      }
    }
  } else {
    // Check whether each client has some data
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
      if (NULL != clients[i]) //ako ima taj client {
        if (clients[i]->available()) {
          Serial.print("client "); Serial.print(i);
          Serial.println("data received");
          digitalWrite(ledPin, LOW);
          String request = clients[i]->readStringUntil('\r');
          Serial.println(request);
        }
      }
    }
  }
}

```

As one can see, I'm checking incoming connections with `server.available()`, whereas I check if there is some data over the existing connection with `clients[i]->available`.

What happens is that I get only the first message from the client. The client code follows:

```
#include <ESP8266WiFi.h>

char ssid[] = "ESP8266";
char pass[] = "ESP8266Test";
WiFiClient client;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("W");
    delay(500);
  }
  client.connect(WiFi.gatewayIP(), 80); // Connection to the server
}

void loop () {
  client.println("0.00"");
  Serial.println("0.00"");
  delay(3000);
}

```

I suspect that I do not understand well the Server and Client classes from ESP8266WiFi Library, but it seems poorly documented.

Please advise.

# Answer
> 1 votes
I presume you are not flushing the first data that's why only the first time your communication is happening but not after the subsequent time

---
Tags: wifi, nodemcu
---


# Question
Title: NodeMCU doesn’t send the sensor read while powering with Vin
I have connected a NodeMCU ESP 12 with the Vin (6 volts) shared with 2 other NodeMCU. The sensors are getting power from the NodeMCU but the NodeMCU isn’t sending to the ThingSpeak cloud unless I plugged it to the PC and unplug the Vin.

Help please.

# Answer
You must connect together all devices by their GND pin.
> 0 votes

---
Tags: arduino-mega, esp8266, nodemcu
---


# Question
Title: What causes Serial.available() to become false after Serial.read() gets data?
As serial data bytes are being read from the serial buffer by `Serial.read()`, are they removed from the Arduino's 64-byte serial buffer altogether?

In my current situation I'm using SoftwareSerial, but this question applies to both software and hardware serial connections.

**EDIT:** *Based on a comment from **@dandavis**, I'd like to further clarify my question*

How does `Serial.read()` interact with `Serial.available()`? Let's say that I have the usual setup:

```
while( Serial.available() ) {
    Serial.read();
}

```

What causes `Serial.available()` to become `false`?

**EDIT 2:** *Changed question title for even further clarification...*

# Answer
Calculating how many bytes are available for reading:

```
int HardwareSerial::available(void)
{
  return ((unsigned int)(SERIAL_RX_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail))
}

```

It's so simple.

Have a look at the Arduino subdir (in your disk) `hardware/arduino/avr/cores/arduino`. The HardwareSerial.cpp is where you have to look at.
> 0 votes

# Answer
It is an internal buffer and only the pointer gets increased. It it visible in the source code off the project, located on github:

```
// Read data from buffer
int SoftwareSerial::read()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  return d;
}

```

This third line from the bottom is the important part, it wraps back to the beginning if the buffer space has run out. If you call `Serial.read()`, the pointer is moved to the next position. So with the next `Serial.read()`, you'll get the next byte, if available. The byte itself gets overwritten only after the wrap (circular buffer).
> 2 votes

---
Tags: serial, softwareserial, serial-data, buffer
---


title: How do I lower clock speed for MKR1000?

text:
# Question
Title: How do I lower clock speed for MKR1000?
According to data sheets, the MKR1000 runs a SAMD21 Cortex-M0+ processor at 48 MHz. For a project I need to drop that down to 16MHz to get some accurate timing in us. How can I do this? Most of the suggestions on the internet involve the ATmega\* boards.

Thanks in advance.

# Answer
> 2 votes
48 MHz is a multiple of 16MHz. Why not just adjust the timing code to account?

---
Tags: mkr1000, speed
---


title: Nodemcu connecting to Wi-Fi Problem

text:
# Question
Title: Nodemcu connecting to Wi-Fi Problem
I am trying to connect to Wi-Fi with Digital pin declaration in setup() function it's not connecting to wi-fi. But connecting to wi-fi without digital pin diclaration. \`

```
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
int m1 = 5;
int m2 = 6;
const char* ssid = "KS Infotech";
const char* password = "kalamsalam";
String readc = "";
void setup () {
pinMode(m1, OUTPUT);
digitalWrite(m1, LOW);
pinMode(m2, OUTPUT);
digitalWrite(m2, LOW);
Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.print("Connecting..");

}

}

void loop() {
while (Serial.available()){  //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read();
String T = String(readc);
    Serial.println(T);
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://ksinfotech.co/kslab/write_to_database.php?incoming="+T+"&UID=surya");  //Specify request destination
int httpCode = http.GET();

if (httpCode > 0) { //Check the returning code

  String payload = http.getString();   //Get the request response payload
  Serial.println(payload);                     //Print the response payload
  if (payload == 'N');
  {
  digitalWrite(m1, HIGH);
  digitalWrite(m2, LOW);
  delay(2000);
  digitalWrite(m1, LOW);
  digitalWrite(m1, LOW);
}
      if (payload == 'F');
  {
  digitalWrite(m1, LOW);
  digitalWrite(m2, HIGH);
  delay(2000);
  digitalWrite(m1, LOW);
  digitalWrite(m1, LOW);
}

http.end();   //Close connection

}

delay(30000);    //Send a request every 30 seconds

}

```

The above code not working but the below code working.

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

const char* ssid = "KS Infotech";
const char* password = "kalamsalam";
String readc = "";
void setup () {

Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.print("Connecting..");

}

}

void loop() {
while (Serial.available()){  //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read();
if (c == '#'){
  break;                   //Stop the loop once # is detected after a word
}//Conduct a serial read
readc += c; //build the string- "forward", "reverse", "left" and "right"
}
String T = String(readc);
    Serial.println(T);
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://ksinfotech.co/kslab/write_to_database.php?incoming="+T+"&UID=surya");  //Specify request destination
int httpCode = http.GET();
 //Send the request

if (httpCode > 0) { //Check the returning code

  String payload = http.getString();   //Get the request response payload
  Serial.println(payload);                     //Print the response payload

}

http.end();   //Close connection

}

delay(30000);    //Send a request every 30 seconds

}

```

# Answer
> 2 votes
use D5 and D6, not 5 and 6. D5 is IO 14, D6 is IO 12. IO 5 is D1 and IO 6 is SDIO\_CLK for the flash memory and that is your problem.

the reference

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


# Question
Title: Ethernet connection - how to send data from interrupt
I have question similar to old topic here Any way to pass EthernetClient to function outside of loop automatically?

I have in the main loop opening of the TCP server which is just maintaining the connection, but I need to send data from the interrupt rutine.

Can anybody tel me how to declare the connection globaly to be able to reference from event rutine and not from main loop only?

Thank you

# Answer
You don't, instead you set a volatile flag in the interrupt routine and/or append to a circular buffer and handle the actual sending the next time through in your main loop.

The time delay from deferring action from the ISR to the main loop code will be on the order of milliseconds, if that.
> 2 votes

---
Tags: interrupt, ethernet
---