# Question
Title: What USB to UART chip provides highest data rates with Arduino boards?
Checking out online stores for a USB/TTL adapter, I came across a wide range of products, and I'm having a hard time selecting the one which would achieve the highest data rate. I was comparing datasheets of the chips I have seen so far, to understand which baud rates are supported:

* FT232R (FTDI): 183 to 3M baud, including **250k**, **500k** and **1M**, 128 RX / 256 TX FIFO
* PL2303 (Prolific): 75 to 1.2M baud, not including 250k, 500k and 1M, 256 RX / 256 TX FIFO
* CP2102 (Silicon Labs): 300 to 921600 baud, including **250k** and **500k**, 576 RX / 640 TX FIFO
* CH340G (WCH): 50 to **2M** baud, not including 250k, 500k and 1M, unknown FIFO size

As explained here, 500k, 1M and 2M are particularly important, because those are the highest baud rates supported with 16MHz crystals. Moreover, data transmission becomes CPU-limited above 500k, so real data rates are practically the same with all three baud rates.

Am I right to assume that in order to get the highest data rate, I essentially have to stay away from PL2303, and prefer FT232R adapters, the other two chips being in the middle? Or are there other factors that I didn't take into account which may affect my choice?

# Answer
> 2 votes
Here's my experience with the above chips over the last two years:

**FT232R** is the fastest, works well with any baudrates. UART adapters with it are sometimes more expensive than alternatives.

**PL2303** is good if you don't plan to go faster than 115200. Additionally, it has the strongest 3.3V reference (available on some adapters as 3.3V output) which can be abused as a 3.3V 20mA power supply. Other chips will refuse to work if you draw more than 5mA from the 3.3V reference.

Prolific is currently fighting against clones by making their up-to-date drivers incompatible with non-original chips, so if your adapter won't work in Windows with code 10, take a look at this page.

**CP2102** which looks great in theory didn't work well for me (in Windows 10, with driver v10.1.3). Bulk data transfers at 115200 were in some cases 4 times as slow compared to other chips.

**CH340G** has a sketchy-looking windows driver, but otherwise works quite well and is often the cheapest option available. Unfortunately, it lack the intermediate baud rates, and getting 2Mbps UART link to work may be hard sometimes. Arduino clones which have this chip on-board do work at 2Mbps without issues (the ones I have seen do, anyway).

---
Tags: usb, hardware, uart
---


# Question
Title: Arduino Clock Speed effect on Stepper Speed
I am running a Pololu A4988 Stepper driver with two (soon to be three) steppers using the `AccelStepper` library. I have wired 1/8th microstepping on both as smooth running is important.

The motors run fine however, when running simultaneously, if Stepper 1 finishes its move before the Stepper 2, there is a marked increase in speed in the Stepper 2 (evident audibly and visually).

The code I use to run the motors is:

```
void MoveAccelXY(int Xm, int Ym) // function 6
{
  X_Axis.moveTo(Xm);
  Y_Axis.moveTo(Ym);
  while(X_Axis.distanceToGo() !=0 || Y_Axis.distanceToGo() !=0)
  {
    X_Axis.run();
    Y_Axis.run();
  }
  Xpos = X_Axis.currentPosition();
  Ypos = Y_Axis.currentPosition();
  Serial.print("X" + Xpos);
  delay(50);
  Serial.print("Y" + Ypos);
  delay(50);
  Serial.print("C");
}

```

I would like there to be no speed drop on any steppers. Increasing the input voltage does not have an effect.

Is the Arduino clock speed the culprit?

# Answer
> 2 votes
Without seeing the rest of your code, the best guess - and I think it is quite likely - is the use of `delay()` and printing within the stepper function. With 2 motors running, and even ignoring the printing time, there will be a total of 200ms taken up by the delays. That means each motor gets serviced a maximum of 5x/sec. Stop one motor, and the other one can double that to 10x/sec.

Look at the Blink Without Delay example for one way of managing timed events without calling `delay()`. The SimpleTimer library provides another.

Update:

> ...run() events are triggered within a while() loop ...

Ah, yes, I see that. So it looks like only one motor could run at a time - the while() loop runs until this motor reaches its target. But you said you run two at a time. So yes, I think understanding the rest of the code will help.

# Answer
> 0 votes
Why would the clockspeed change when driving multiple motors at the same time?

How do you power the motors and Arduino?

I suspect that your power supply is the problem. Running 2 motors likely doubles the current consumption. Try to measure the input voltage, does it drop when driving both motors?

You should check the current your motors can consume and compare with what your power supply may provide. (Also keep the 1A limit of the driver in mind)

---
Tags: arduino-uno, stepper, oscillator-clock
---


title: ESP8266 fail to connect MQTT broker

text:
# Question
Title: ESP8266 fail to connect MQTT broker
I am using NodeMCU dev board with ESP8266 WIFI.

Every time I try to connect to my local broker it returns this error:

```
failed, rc=-2 try again in 5 seconds

```

I am using Ubuntu 18.04, my local brokers are Mosquitto and EQMTT. I tried both of them through pubsubclient library and it doesn't connect. Using MQTT Box works connecting to my local brokers. Connecting to my WiFi also works. When I connect to a MQTT broker using pubsubclient e.g. mqtt://test.mosquitto.org:1883/ it works. It just doesn't seem to work with local broker. This is the code:

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

// Update these with values suitable for your network.

const char* ssid = "mywifi";
const char* password = "password";
const char* mqtt_server = "127.0.0.1";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
  pinMode(D7, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(D7, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(D7, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(1000);
    }
  }
}
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

```

Note: The brokers are running, I can even connect it through MQTT Box (attached picture).

# Answer
`127.0.0.1` is not the address of your computer. That is the address of the "loopback" interface - a virtual interface that allows a device to talk to itself.

That means that when you are using the MQTT server itself you can connect, because it's all the same computer. However the ESP8266 is trying to connect to itself, not the MQTT server.

You need to replace `127.0.0.1` with the actual IP address of your MQTT server.

The simplest way of getting your computer's IP address is to open a terminal window and type:

```
hostname -I

```
> 2 votes

---
Tags: arduino-uno, esp8266, nodemcu, mqtt
---


title: Error using Adafruit Feather M0

text:
# Question
Title: Error using Adafruit Feather M0
I am trying to upload an empty program on the Adafruit feather to see if it connects to my PC. So far, it isn't. I'm running a Windows 10 and I followed this guide:

https://learn.adafruit.com/adafruit-feather-m0-wifi-atwinc1500?view=all

But I get this error:

Couldn't find a Board on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.

And the PORT submenu is greyed out.

# Answer
I found out the issue I was having, though I have a Gemma.

What worked for me:

* Selecting the correct board under "Tools" -\> "Board:" (in your case, the Adafruit Feather 32u4 is probably the one you want)
* Selecting the "USBtinyISP" under "Tools" -\> "Programmer:"

Then it was able to upload to the Gemma, after hitting it's reset button twice to get it into a 'programming mode' (I don't know if the feather has such a feature).

If you are still having problems make sure that you have properly set up your arduino IDE for adafruit boards, and just play around with settings (try different programmers).

I don't know why it was so hard finding this info out, and why it is not more visible on the documentation to set these things up. I think I found out the 'hitting reset twice' thing somewhere buried in a forum... I digress, but Adafruit does need to consolidate their documentation to make it clearer.

Hope this helps
> 1 votes

# Answer
A common problem on Windows for people who may be encountering this type of issue is actually having the wrong USB to UART Bridge drivers or none at all. You can download the most up to date ones here
> 1 votes

---
Tags: arduino-ide, adafruit
---


# Question
Title: Problem Uploading to the Arduino Nano board
\]I am using an Arduino Nano board. It has an ATmega 328P processor. For running the codes I use Arduino 1.8.6 Software. The issue is that when I am uploading my sketch to the board it shows me the following errors:

```
 Using Port                    : COM7
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding

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

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

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x9b

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

I have turned on the show verbose output option turned on.

Also, sometimes the following errors pop up:

```
collect2.exe: error: ld returned 255 exit status

Using library SoftwareSerial at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.14.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\SoftwareSerial
exit status 1
Error compiling for board Arduino Nano.

```

I have referred the following links to solve my issue:

I am making an application wherein I have to control two DC motors via Bluetooth module HC-05

In one of the troubleshooting questions, the solutions contained the possibility of the bootloader not being installed where the problem can be verified by pressing the reset button and checking the bootloader LED to blink. Can someone help me with this?

Also, there are two processors shown for ATmega328P:

1. The ATmega328P
2. The ATmega328P (old bootloader)

I tried using then both options for uploading the sketch but still, the errors pop up.

I have also downloaded and installed the latest FTDI drivers from their site.

# Answer
A common solution is to actually switch the board type to the Arduino Uno. It is a known problem but I have yet to see any other viable fix.
> -1 votes

---
Tags: arduino-nano, bluetooth
---


# Question
Title: The right way to find and understand the libraries
I am working on a project to send sensor values from esp8266's Wemos D1 mini to MySQL. I tried using the library MySQLconnection.h but I couldn't make it to connect to wifi. So I uploaded a simple program to connect the board to WiFi using ESP8266.h but I got the error that Unable to compile for Wemos D1 board.

Please tell me the right procedure to select the right library for the problem defined.

# Answer
You should break your problem down into simple parts, which it seems you are on-track to do. Your ultimate goal appears to break down into the following sub-tasks (not in order):

1. Read sensor value
2. Connect to a WiFi network
3. Connect to a MySQL server
4. Send sensor data to MySQL database

You are unlikely to find a single library to do all of these tasks, but as progress in solving each step, any library that works is the "Right" one, in general. Choose a library that solves an individual task.

You say you tried to upload a simple program to only connect to WiFi, but that it did not compile. The clue to why it did not compile will be found in the actual compile error message. If you can update your question with the error message and the code to the simple program, you can get some guidance from the users of this site to solve that problem.
> 1 votes

---
Tags: esp8266, wifi, iot
---


title: Read analog port set as output

text:
# Question
Title: Read analog port set as output
I have a PWM analog port that is outputting a frequency, is it possible to do an analogRead on the same pin and get a correct value? If so, will reading that port disrupt the freq output on the pin? This is being done on a Teensy 3.2 device. My goal is to output the freq visually on an OLED. Tnx.

# Answer
You want the voltage that would be read by a voltmeter? If you know what value you set for PWM, you know the voltage that is generated.

But if you are curious, you can connect the PWM output to ADC pin and read for example a 100 values and calculate the average. You will see that at the same resulution of PWM and ADC, you get as average of ADC values the same value as you set for PWM.

This is for M0:

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

  analogWriteResolution(10);

  for (int i = 0; i < 1024; i += 10) {
    analogWrite(7, i);
    delay(100);
    long sum = 0;
    int n = 0;
    unsigned long start_time = millis();
    while (millis() - start_time < 100) {
      sum += analogRead(A1);
      n++;
    }
    Serial.print(i);
    Serial.print(' ');
    Serial.println(sum / n);
  }
}

void loop()
{
}

```
> 1 votes

# Answer
No, it's not possible.

PWM is not actually analog - it's digital, but switching on and off at a high speed.

If the pin were capable of reading an analog value at the same time as outputting a PWM waveform (which I highly doubt...) all you would get is alternating 0 and 1023 values (or whatever range the Teensy reads in).
> 1 votes

# Answer
You can create a parallel branch from PWM pin with a diode. And put a 0.1uF capacitor and parallel 1k resistor after the diode and connect analog pin between diode and resistor to read pwm avarage output voltage. But becareful it will give 0,6V below.
> 0 votes

---
Tags: arduino-nano, teensy
---


# Question
Title: How can I detect which baudrate a virtual COM port is set to?
I would like my software running on Leonardo to behave differently depending on the baudrate of the USB Serial set by the PC. For example, I want to make a smart USB to UART converter which performs some processing of the data it transmits. It would be much more elegant to set the UART baudrate to whatever value the PC is requesting on USB side, rather than hardcoding a value.

AFAIK 32u4 chip is used as a USB to UART converter on Mega, where it supports different baudrates, so this should be doable.

I also have a Teensy 3.2 board, so if anyone knows how to detect the baudrate on this board I'm also interested.

# Answer
From looking at the source it appears that on 32u4 based boards `Serial` includes extra methods to access the settings from the USB host:

see: https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/cores/arduino/USBAPI.h#L129

From USBAPI.h:

```
// These return the settings specified by the USB host for the
// serial port. These aren't really used, but are offered here
// in case a sketch wants to act on these settings.
uint32_t baud();
uint8_t stopbits();
uint8_t paritytype();
uint8_t numbits();
bool dtr();
bool rts();

```
> 6 votes

---
Tags: serial, usb, arduino-leonardo, teensy
---


title: Read only one line in SD card

text:
# Question
Title: Read only one line in SD card
I have some C++ code, but I cant convert it to Arduino language. I just want to ask, what is the same as `getline()` (C++ code) function in Arduino?

I just wanted to get the first line in my SD card... I can only display all text inside my SD card...

Example:

```
line1   <-   only this line should display(and this line will delete in text
             file... but that is another issue... i will just focus to get the
             line1 and get the value)

line2

line3

line4

line5

```

This code displays all lines

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

    File myFile;

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

       Serial.print("Initializing SD card...");

       if (!SD.begin(4)) {
         Serial.println("initialization failed!");
         while (1);
       }
       Serial.println("initialization done.");

       // open the file. note that only one file can be open at a time,
       // so you have to close this one before opening another.
       myFile = SD.open("test.txt", FILE_WRITE);

       // re-open the file for reading:
       myFile = SD.open("test.txt");
       if (myFile) {
         Serial.println("test.txt:");

         // read from the file until there's nothing else in it:
         while (myFile.available()) {
           Serial.write(myFile.read());
         }
         // close the file:
         myFile.close();
       } else {
         // if the file didn't open, print an error:
         Serial.println("error opening test.txt");
       }
     }

     void loop() {
       // nothing happens after setup
     }

```

# Answer
> 1 votes
There is no builtin way to do that but you got all the necessary tools at hand.

End of line should be signaled by a decimal 10, aka LF(Line Feed) character. So what you do is keep reading until you encounter LF or end of file, which then is the entire line you want to read.

```
while (file.available() && file.peek() != 10) // peek returns the next character without incrementing the read index
    file.read();

```

This code does exactly that. Now you could either store the read bytes in a buffer (**big enough!**) right away or instead find out the number of bytes beforehand to create a precisely sized buffer afterwards and use the read(buffer, length) overload to read all bytes at once.

Please keep in mind that the LF character has to be there in order to be read. So if you are the one creating the files, be sure to place it. (most desktop text editors do that for you)

Example:

```
char buffer[20];
uint8_t i = 0;

while (file.available() && file.peek() != '\n' && i < 19)    // note how this also prevents the buffer from overflowing (18 max to leave space for '\0'!)
{
    buffer[i] = file.read();
    i++;
}
buffer[i + 1] = '\0';    // it is good practice to end strings with a terminating NULL character

```

# Answer
> -1 votes
If I understand you correctly, it depends on what you want to do with that code. Do you want to execute lines of C++ code in/on the SD card or are you merely attempting to convert what you have in C++ to "Arduinoese?"

If you need to, you can actually execute microcontroler-based C/C++ code on your arduino if it has an AVR in it, and you have the proper AVR Toolchain.

Elliot William's "Make: AVR Programming" book is a great place to learn about this.

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


# Question
Title: Connecting 5V arduino logic with 12V car logic
I need to connect arduino to K-Line in my car's OBDII port.
I used an L7805 to power the atmega but how can I interface 12V car logic with 5V arduino logic?
The problem is, the connection has to be bidirectional- sometimes the arduino
will pull the line high/low and sometimes the car will - the purpose of
this connection is to get throttle, rpm etc. data.
This would be easy if the connection was one directional - I could use a
transistor to steer 12V to going IN the K-Line and voltage divider if I wanted to do the reverse. But how to do both?

# Answer
I found this that may be helpful to you. this circuit allows for bidirectional communication between automotive K-line ECUs and an arduino. K-Line Interface circuit
> 1 votes

---
Tags: voltage
---


# Question
Title: Can the Arduino be hurt by connecting too many LEDs in serial?
Today I learned about Vf for leds, after founding out that 3 leds in series driven by 5 V did not make them light up while 2 did.

However, I also read that it is quite bad for a power source to use more volts (like 3 times 2V) this way than the power source (5V for the Uno).

Can the Arduino be hurt this way?

# Answer
The forward voltage of an LED or diode is the *applied* voltage of the "knee" in the exponential characteristic at which it starts to substantially conduct, and in the case of an LED, produce light.

It is not, under ordinary circumstances of indicator-type LEDs, a voltage that would be produced internally to the LEDs, at least not with any substantial current capability.

As long as you are supplying the LEDs from a voltage within the Arduino's I/O range, it should not be hurt by a series strings of *too many* LEDs. However, in theory (if rarely in practice) a series string of *too few* LEDs that did not include a `current limiting resistor` would stress the Arduino beyond its ratings - and possibly (and more commonly) also the LED(s) beyond their current limits.
> 4 votes

# Answer
Placing 3 "typical" LEDs in series and then driving them with the Arduino will not produce any light because the Arduino can only output 5V on any pin. It would require approx 6 volts to drive current through the LEDs when connected in series. This is for typical green, yellow, red type LEDs that have a 2 volt or so forward voltage drop. Note: some other colors require more forward voltage.

When you place two of these LEDs in series the forward voltage drop required to light them is only about 4 volts, that's why they light up when 3 in series didn't. However, since the Arduino outputs 5 volts on its pin and the LEDs only require 4 volts the extra 1 volt can cause more current to flow which, if excessive, can damage the output pin. Thats why when driving LEDs in this way its usually a good practice to place a current limiting resistor in series with the LED(s). This resistor limits the current induced by any driving voltage which is over the voltage needed to drive the LEDs to conduction.
> 1 votes

---
Tags: current, voltage
---


title: The need to use logic level converter

text:
# Question
Title: The need to use logic level converter
Why do we need level logic converter to have 5V or 3.3V?

Because in Arduino Uno/Mega (don't know about other boards), they already provide 5V and 3.3V for us to use.

# Answer
Level logic converting for level shifting is different from powering a device.

Logic level is the state of a digital input/output. No voltage (or very little of it) is considered `LOW`. Over the threshold voltage is `HIGH`. On a 3.3V system, if you set pin to `HIGH`, it has 3.3 V. On a 5 V system, `HIGH` is 5 V.

A digital input pin reads `HIGH` once the threshold voltage is surpassed. If the input pin is for 3.3 V and doesn't have 5 V tolerance, feeding 5 V as `HIGH` could destroy it. That is why you need level converter from 5 V to 3.3 V.

If the input pin is for 5 V and the threshold voltage is higher then 3.3 V, 3.3 V input will not be read as `HIGH`. That is when you need level converter from 3.3 V to 5 V.

You must consult the 3.3 V device datasheet and check if the input pins are 5 V tolerant. You should also check the digital pin threshold voltage on a 5 V device in case you want to communicate with it using 3.3 V.
> 5 votes

---
Tags: power, voltage-level
---


title: D1 Mini; is there a fuse?

text:
# Question
Title: D1 Mini; is there a fuse?
While this board (listed on ebay as *D1 Mini NodeMcu Lua WIFI ESP-12F ESP8266 WeMos 4M Bytes Development Board Kit*) was powered by usb, I accidentially shorted between the gnd (G) and 5v pins on the left, and some magical smoke escaped.

I can no longer power the device from usb, but it works nicely if I supply it with the right voltage on either the 5V on the left or the 3V3 on the right.

So something has burned between the 5V on the usb and the 5V on the regulator. I have tried measuring the components with an ohmmeter, and compared it to a working board, but I can measure no difference.

Is one of these tiny components a fuse, or a diode to prevent backwards voltage from board to pc, if the board is powered on the pins?

Or could the short between 5V and GND have caused a track to burn?

# Answer
> 2 votes
Try measuring with a voltmeter to compare the good board to the bad one. If it is the diode as mentioned in the comments under the question, you should get a different reading on the bad board. It should be fairly easy to replace if you have a soldering iron and a steady hand.

# Answer
> 2 votes
I came here because of a dead Wemos D1 Mini Pro. One which I managed to kill in exactly the same way (shorting out something while trying to measure a voltage - most likely I shorted the 5V and GND as well :) ).

The symptoms were identical - could power the board via 5V or 3V3, but not via USB. And they were solved after replacing the diode - or, more accurately, bypassing it, since I was unable to find an SMD Schottky to replace it with.

I won't tell you the rest of the story (where I first blamed it on the voltage regulator and replaced that), to save myself the embarassment :)

# Answer
> 2 votes
I can confirm that the component, which on my Mini clones (which have an almost identical layout) is the tiny black component pictured at the upper left corner of the USB shielding, is a diode and can be blown pretty easily by shorting +5 to Gnd. I did as you Lenne proposed and jumpered it with a tiny wire and recovered the device.

---
Tags: hardware, nodemcu
---


# Question
Title: Passing HardwareSerial and SoftwareSerial as a Class Property
I wish to know if there is a way to use a single property `Serial0` to hold a `HardwareSerial` or a `SoftwareSerial` or other class instances supporting basic methods such as `available()`, `read()` and `write()`, in order to make a `CustomSerial` Class (*polymorphism*?).

```
class CustomSerial{
    <GenericSerial??> Serial0;
    char c;
    void read(void){
        c=Serial0.read();
    }
};

```

The calls should be:

```
CustomSerial SerialCus;
int n=SerialCus.available();
char c=SerialCus.read();
SerialCus.write(c);

```

What should I use as `GenericSerial` class, or what should be the proper use? I tried the `Stream` class (as the answer pointed), but for some reason the functionality is not preserved (it writes unknown characters). Should indeed `Stream` be the generic class I need for this?

# Answer
> 3 votes
A base type for Arduino hardware serial classes, SoftwareSerial and other software serial classes and some other Arduino classes is Stream (reference). Stream.h on GitHub

```
class CustomSerial {

private:
  Stream &stream;

public:
  CustomSerial(Stream &_stream) : stream(_stream) {}

  int read() {
    return stream.read();
  }

  int available() {
    return stream.available();
  }

  int peek() {
    return stream.peek();
  }

  void write(byte b) {
    stream.write(b);
  }

};

SoftwareSerial Serial0(10, 11);
CustomSerial SerialCus(Serial0);

void setup() {
}

void loop(){
  if (SerialCus.available()) {
    char c = SerialCus.read();
    SerialCus.write(c);
  }
}

```

---
Tags: serial, softwareserial, class
---


# Question
Title: ESP8266 Soft Access Point: Timeout of request of resource when not responded to in set undocumented time
I'm experimenting with the ESP8266 chip on a Wemos D1 R2 board. I'm trying to write some code which will allow the user to input a username and password in an HTML form then get a response as to what happened with trying to connect to the WiFi as either they connected or the password was wrong. After I've turned setup Access Point and Station mode on the device using:

```
    // The field here would be global so other functions can access it
    ESP8266WebServer server(80);
    server.on("/connect", handleConnect);
    server.begin();

```

In my handleConnect function, I check the body of the request and attempt to login:

```
    if(!server.hasArg("ssid") || !server.hasArg("password")) {
        server.send(200, "text/html", "You didn't submit a ssid and password");
        return;
    }

    auto ssid = server.arg("ssid");
    auto password = server.arg("password");

    WiFi.begin(ssid, password);

    auto status = WiFi.waitForConnectionResult();

    server.send(200, "text/html", String(status));

```

When the user inputs the correct password, the function returns the request in time and the request responds with 3 (the connection was successful). However, if the password is wrong, the request times out. I've also tried several approaches to either work-around or fix the problem such as:

* Using a while loop and calling `WiFi.status()` and checking it and responding accordingly. This approach ends with the same request timeout if the password is wrong. An example of this would be:

```
while(true) {
  delay(1000);
  auto status = WiFi.status();

  if(status == WL_CONNECTED) {
    server.send(200, "text/html", "You're connected!");
  }

  if(status == WL_CONNECT_FAILED) {
        server.send(200, "text/html", "You inputted the wrong password! Try again!");
  }
}

```
* Registering another resource to specifically only return what state the WiFi is in and in the original connect function to send back HTML with some javascript in it which calls this other resource and do the decision making of what text to display client-side but this approach always returns 0 (when the WiFi is in process of changing between statuses, quoted from the docs)

```
server.on("/checkConnection", checkConnection);

// other code

void checkConnection() {
  server.send(WiFi.status());
}

```

+ And finally, I have experimented with using a public field to save the state once it has finished in the main function where the original connection tried to be established and then use the checkConnection function to return this state and this ***SOMEWHAT*** works, however, the code is messy, hacky and there must be a better way of doing this otherwise this will have to be my solution until the libraries are updated to fix this or something like that:

// public field for the status

```
      int status = 0;

      // other code

      void handleConnect() {

        // checking ssid and password

        WiFi.begin(ssid, password);

        // use an interval with AJAX or this to get the connection state
        server.send(200, "text/html", "Go to <a href='/checkConnection'>to check the connection</a>");

        while(true) {
          delay(1000);
          auto s = WiFi.status();
          status = s;
          if(s = WL_CONNECTED) break;
        }

      }

      void checkConnection() {
        server.send(200, "text/html", status);
      }

```

Has anyone encountered this problem and if so, is there a better way of solving it apart from using a public variable which just makes it a pain in the bum to work with? Thank you.

# Answer
```
WifiMulti wifiMulti;//declare global.
wifiMulti.addAP(ssid,pass);//instead of WiFi.begin();
int i = 0;
//add below to wait for connection.
while (i < 20)
  {
    if (wifiMulti.run() == WL_CONNECTED)
    {
      return (20);
    }
    delay(500);
    Serial.println(WiFi.status());
    i++;
  }

```
> 1 votes

# Answer
Make the WiFi.begin outside the WebServer handler. In the handler store the ssid and password into variables and send a response. In loop() then make the WiFi.begin. For the result, pool from the browser with javascript.

Example
> 0 votes

---
Tags: esp8266, http
---


title: Use IR remote with arduino

text:
# Question
Title: Use IR remote with arduino
I would like to use the IR remote with Arduino to turn on a LED and turn off the same LED when I push on the remote.

That is to say :

* If I push on 1 I would like the LED turn on
* If I push on 2 I would like the LED turn off

Here is my code :

```
#include <IRremote.h>

const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;

const int L1 = 13;

void setup(){
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
  pinMode(L1, OUTPUT);
}

void loop(){
  if (irrecv.decode(&results)){
        unsigned int value = results.value;
        Serial.println(value);
        irrecv.resume();
        if(value == 12495){
        digitalWrite(L1, HIGH);
        delay(1000);
        }
        else if(value == 6375){
        digitalWrite(L1, LOW);
        delay(1000);
      }

  }
}

```

But the problem is when I push on 1 I just see the LED turn on but very quickly the LED turns off then whereas I don't push on the button 2.

Could you help me please?

# Answer
This line of your sketch `irrecv.blink13(true);` tells the `IRrecv` object to flash the LED on and off when an IR signal is received. `boarddefs.h` in the IRremote folder has pin number 13 defined as the default `BLINKLED`. The code you have written in `loop()` is trying to do something different with the same LED. I would remove this line `irrecv.blink13(true);` then try your sketch again. Once the LED is working correctly, try removing both of these lines `delay(1000);`.
> 1 votes

---
Tags: arduino-uno, led, ir, remote-control
---


# Question
Title: Is there any easy way to change Arduino Wifi shield to ESP8266?
As the title says, is there any easy way to replace WiFi shield with ESP8266, with as little as possible modification to code?

Here is my ESP:

# Answer
> 1 votes
Consider porting your sketch to esp8266 board like Wemos D1. The API of the ESP8266WiFi library is same as the API of the WiFi library.

To use esp8266 as network adapter, you have two wiring options.

If you have or buy an esp8266 module with SPI pins, you can connect the esp8266 over SPI like the WiFi shield is connected. Then you upload the WiFiSpiESP firmware to esp8266 and you include in your sketch WiFiSpi library instead of WiFi library.

Second option is to connect esp8266 over Serial or SoftwareSerial. The esp8266 should have AT firmware installed. The you can include WiFiEsp library in you sketch and initialize it with the Serial interface of your choice. You can find the WiFiEsp library in Library manager. Most new esp8266 modules have AT firmware installed at default.

There is one more option for Serial connection, if WiFiEsp wouldn't work for you. WiFiLink firmware and library

All mentioned libraries WiFiSpi, WiFiEsp and WiFiLink have the same API as the WiFi library so the rest of the code should work without changes.

---
Tags: esp8266, wifi
---


# Question
Title: Sending data over two independently powered arduinos
I have multiple arduinos that are each powered by a 12v battery through a 5v regulator. All arduinos share a common ground. Can I simply connect the digital output from one arduino into the digital input of another? I'm worried the (small) voltage differences between each regulator could cause a problem.

# Answer
> 1 votes
It's ok if the distance between the two devices are not too big. (couple meters)

Since the valid logic level (voltage) ranges are pretty wide a small difference won't affect the operation of the devices. Arduino uses TTL (5V) logic so let's see the level diagrams:

If you see the output level ranges (on the right) are more strict than on the input side (on left) so the logic value remains valid even if a small voltage drop or noise occurs on the wire.

Make sure you won't connect two outputs directly since it can damage the microcontrollers. Connecting two inputs are totally safe.

EDIT: If you want to cover longer distances you need to use a balanced line e.g. differential I/O-s, RS-485 or CAN. These are not default Arduino features so you'll need additional electronic to use them.

---
Tags: power, wires
---


# Question
Title: How do I read addresses on multiple DS2413 1-Wire GPIO Breakouts, using the Adafruit sketch?
I am using three DS2413 1-Wire GPIO Breakouts from Adafruit connected to an ESP8266. I tested the DS2413 breakouts using their example sketch and it works fine for just one DS2413. But I cannot get it to work when 2 or more DS2413s are connected.

**Adafruit DS2413 Example Sketch** https://github.com/adafruit/Adafruit\_DS2413/blob/master/DS2413.pde

**Adafruit DS2413 Overview**
https://learn.adafruit.com/adafruit-1-wire-gpio-breakout-ds2413?view=all

When I connect 2 or more DS2413s, it only blinks the LEDs connected to the 1st breakout and doesn't read the other addresses.

I made some changes to the void setup section and now I am getting the following in the serial monitor. It sees all the addresses, but it is duplicating them and the first set have "No device found on the bus!" at the end. How can I get the sketch to read all the addresses without these errors?

**Serial monitor**

```
Looking for a DS2413 on the bus
3A B2 C2 39 00 00 00 8C No device found on the bus!
3A 8E AE 39 00 00 00 2C No device found on the bus!
3A E5 B6 39 00 00 00 55 No device found on the bus!
Found a DS2413: 3A B2 C2 39 00 00 00 8C
Found a DS2413: 3A 8E AE 39 00 00 00 2C
Found a DS2413: 3A E5 B6 39 00 00 00 55

```

Here is what the code with my changes.

```
#include <OneWire.h>

#define DS2413_ONEWIRE_PIN  (4)

#define DS2413_FAMILY_ID    0x3A
#define DS2413_ACCESS_READ  0xF5
#define DS2413_ACCESS_WRITE 0x5A
#define DS2413_ACK_SUCCESS  0xAA
#define DS2413_ACK_ERROR    0xFF

OneWire oneWire(DS2413_ONEWIRE_PIN);
uint8_t address[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

void printBytes(uint8_t* addr, uint8_t count, bool newline=0)
{
  for (uint8_t i = 0; i < count; i++)
  {
    Serial.print(addr[i]>>4, HEX);
    Serial.print(addr[i]&0x0f, HEX);
    Serial.print(" ");
  }
  if (newline)
  {
    Serial.println();
  }
}

byte read(void)
{
  bool ok = false;
  uint8_t results;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_READ);

  results = oneWire.read();                 /* Get the register results   */
  ok = (!results & 0x0F) == (results >> 4); /* Compare nibbles            */
  results &= 0x0F;                          /* Clear inverted values      */

  oneWire.reset();

  // return ok ? results : -1;
  return results;
}

bool write(uint8_t state)
{
  uint8_t ack = 0;

  /* Top six bits must '1' */
  state |= 0xFC;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_WRITE);
  oneWire.write(state);
  oneWire.write(~state);                    /* Invert data and resend     */
  ack = oneWire.read();                     /* 0xAA=success, 0xFF=failure */
  if (ack == DS2413_ACK_SUCCESS)
  {
    oneWire.read();                          /* Read the status byte      */
  }
  oneWire.reset();

  return (ack == DS2413_ACK_SUCCESS ? true : false);
}

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

  Serial.println(F("Looking for a DS2413 on the bus"));

  /* Try to find a device on the bus */
  oneWire.reset_search();
  delay(250);
  while (oneWire.search(address)) {
       printBytes(address, 8);
       Serial.println(F("No device found on the bus!"));
}
  /* Check the CRC in the device address */
  if (OneWire::crc8(address, 7) != address[7])
  {
    Serial.println(F("Invalid CRC!"));
    return;
  }

  /* Make sure we have a DS2413 */
  if (address[0] != DS2413_FAMILY_ID)
  {
    printBytes(address, 8);
    Serial.println(F(" is not a DS2413!"));
    return;
  }

  while (oneWire.search(address)) {
  Serial.print(F("Found a DS2413: "));
  printBytes(address, 8);
  Serial.println(F(""));
}
}

void loop(void)
{
  /* Read */
  /*
  uint8_t state = read();
  if (state == -1)
    Serial.println(F("Failed reading the DS2413"));
  else
    Serial.println(state, BIN);
  */

  /* Write */
  bool ok = false;
  ok = write(0x3);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
}

```

# Answer
I was able to get the ESP8266 to read all DS2413 devices without errors as well as blink each LED connected to the DS2413, individually, down the chain.

**Here are animations of it working.**

I owe all the credit to mortonkopf on Github. His sketch DS2413\_button\_array\_test, was exactly what I needed to be able to read the addresses on all DS2413 devices connected and blink each LED. Here is a link to his OneWire\_DS2413\_array repo.

https://github.com/mortonkopf/OneWire\_DS2413\_array

**Here is the code I am using to make this work.**

```
// This sketch is based on mortonkopf's DS2413_button_array_test sketch and allows
// you to read multiple DS2413 devices and blink an LED connected to each DS2413,
// individually, down the chain.
// https://github.com/mortonkopf/OneWire_DS2413_array
//
// This sketch is an improvement on the write feature of the Adafruit DS2413
// sketch which only reads 1 DS2413 device.
// https://github.com/adafruit/Adafruit_DS2413
// https://learn.adafruit.com/adafruit-1-wire-gpio-breakout-ds2413/reading-writing-and-arithmatic

#include <OneWire.h>

/* reading pins
0x0 (B00000000) - Both pins LOW
0x1 (B00000001) - IOA = HIGH, IOB = LOW
0x2 (B00000010) - IOA = LOW, IOB = HIGH
0x3 (B00000011) - Both pins HIGH
0xFF (B11111111) - Read Failed!
*/
#define DS2413_ONEWIRE_PIN  (4) // GPIO 4 on Adafruit Feather HUZZAH ESP8266

#define DS2413_FAMILY_ID    0x3A
#define DS2413_ACCESS_READ  0xF5
#define DS2413_ACCESS_WRITE 0x5A
#define DS2413_ACK_SUCCESS  0xAA
#define DS2413_ACK_ERROR    0xFF

#define BUTTON_NO 3 //use this for size of array to store state values//

OneWire oneWire(DS2413_ONEWIRE_PIN);
uint8_t address[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

byte Button_states[BUTTON_NO];//this is the array of button states//

void printBytes(uint8_t* addr, uint8_t count, bool newline=0)
{
  for (uint8_t i = 0; i < count; i++)
  {
    Serial.print(addr[i]>>4, HEX);
    Serial.print(addr[i]&0x0f, HEX);
    Serial.print(" ");
  }
  if (newline)
  {
    Serial.println();
  }
}

byte read(void)
{
  bool ok = false;
  uint8_t results;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_READ);

  results = oneWire.read();                 /* Get the register results   */
  ok = (!results & 0x0F) == (results >> 4); /* Compare nibbles            */
  results &= 0x0F;                          /* Clear inverted values      */

  oneWire.reset();

  // return ok ? results : -1;
  return results;
}

bool write(uint8_t state)
{
  uint8_t ack = 0;

  /* Top six bits must '1' */
  state |= 0xFC;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_WRITE);
  oneWire.write(state);
  oneWire.write(~state);                    /* Invert data and resend     */
  ack = oneWire.read();                     /* 0xAA=success, 0xFF=failure */
  if (ack == DS2413_ACK_SUCCESS)
  {
    oneWire.read();                          /* Read the status byte      */
  }
  oneWire.reset();

  return (ack == DS2413_ACK_SUCCESS ? true : false);
}

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

  Serial.println(F("Looking for a DS2413 on the bus"));
}

void loop(void) {
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !oneWire.search(address)) {
    Serial.println("");
    Serial.print("No more addresses.\n");
    oneWire.reset_search();
    delay(50); //was 250
    return;
  }
  Serial.println("");
  Serial.print("R=");
  for( i = 0; i < 8; i++) {
    Serial.print(address[i], HEX);
    Serial.print(" ");
  }

  if ( OneWire::crc8( address, 7) != address[7]) {
      Serial.print("CRC is not valid!\n");
      return;
  }

  if ( address[0] != DS2413_FAMILY_ID) {
      Serial.print("Device is not a DS2413 family device.\n");
      return;
  }

// Blink each LED connected to the DS2413 one at a time
  bool ok = false;
  ok = write(0x1);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
  ok = write(0x2);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
///////////////////

uint8_t state = read();
  const int IOA = 0x1;
  const int IOB = 0x2;

  if (state == -1)
  {
    Serial.println(F("Failed reading the DS2413"));
  }
  else
  {
    if (state & IOA)
    {
       Serial.print("   A");
    }
    if (state & IOB)
    { //can use this IO if needed to perfom tasks
        Serial.print("   B");
    }
  }

}

```

Here is a link to the Gist I created for this sketch. https://gist.github.com/orbitrod/51eb10c1a88f5747dc79298030e4480c
> 0 votes

# Answer
You have two detection loop in your setup function. This one can be safely deleted as for each detected device it will print the error message

```
while (oneWire.search(address)) {
   printBytes(address, 8);
   Serial.println(F("No device found on the bus!"));

```

}
> 0 votes

---
Tags: esp8266, adafruit, 1-wire
---


title: arduino firmware

text:
# Question
Title: arduino firmware
Hi I was wondering if there is any way to/ how I might go about solving the following.

I am designing my own arduino board based on a mega32u4 chip and I want my arduino board to light up an indicator led depending on if an analog pin is in use. For example if a user uploads code that utilizes a certain pin say reading a voltage from A0, the arduino would light up an LED next to that pin.

I was thinking perhaps I could tie the analog pin to a digital pin in the firmware and have the digital pin go HIGH every time the analog pin is in use(is this possible/ could anyone point me to good examples online)?

The user needs to know whether or not the pin they think is writing is actually outputting a signal and/or if the pin they think is reading is reading a signal. This is beacause they will be hooking up outputs and inputs to the arduino board using conductive ink and if their circuit isnt working the indicator lights will let them know that their software is working but there is probably a break in the circuitry they drew out.

# Answer
> 1 votes
When you upload code that **is** the firmware. There isn't another lot of firmware (like an operating system) that is always there (excepting the bootloader which is only used for uploading new code).

Maybe you could connect an LED, via an op-amp as an amplifier, to the analog pin, so that if a voltage appears that it would light the LED. However it could be "in use" and reading zero volts so that wouldn't prove an enormous lot.

---

> would it be ill advised to attempt a solution on the lines of what Mikael proposed in the comments?

You can make your own analogRead function and encourage your users to use it (or do it via a #define) however that will only work if people use your new function or header file.

It would also have the side-effect of making other pins not available (ie. the pins you are doing the LED on) which might be confusing for users who are trying to use all available pins.

I assume this is some sort of teaching gadget? It might be better to teach people to do an indicator LED themselves rather than trying to automate it for them.

# Answer
> 0 votes
Create a library. User will include it and the h file will create a single instance of the handler object for your pin pairs. The handler will register a timer interrupt, and the interrupt will check the source pin and set the target pin.

---
Tags: led, analogread, atmega32u4, firmware
---


# Question
Title: Can a DHT11+ESP8266 be powered by a Adafruit USB LiPo charger directly?
I have rigged up a small DHT11+ESP8266 combo which I'm currently powering from the 3.3v from an Ardruino. I've ordered a 3.7v LiPo battery and have a Adafruit usb micro LiPo charger, however, the battery will take two weeks to come.

Can I plug the usb charger directly into the DH11 while my battery arrives?

# Answer
No, you can't.

The charger circuit will only operate properly with a battery attached.

It is not designed to provide power to a system. It is designed for charging the battery and nothing else. You are supposed to remove the battery from the charger and then attach it to your circuit. Even with a battery attached you can't use it to power your circuit - the voltage will be too high, and your target circuit will confuse the charger and it will fail to charge the battery properly (or it may end up over-charging the battery).

To do what it sounds like you want to do you need:

1. A LiPo charge circuit
2. A 3.3V regulator (ideally a Buck/Boost combined regulator)
3. Bypass circuitry to power the 3.3V regulator directly from the incoming power when present or from the battery when no external power is present.
> 1 votes

---
Tags: esp8266, usb, lipo
---


# Question
Title: Build an improved GSM antenna for arduino mkr gsm 1400
I want to use an Arduino MKR GSM 1400 in my area wich has a bad connectivity on mobile internet. On my phone it's very weak and if i drive to the next village it works sometimes on the arduino with the given standard antenna but I want it to work in a wider range. Is there any antenna available specifically for mobile connections wich you can put on a arduino? And how do you call them and where can I buy such a thing or even build it myself? Do you have any suggestions for such an antenna? And is there something I can improve with just using software to strengthen the signal?

# Answer
> 1 votes
On one end of the MKR GSM 1400 is a *U.FL* antenna connector. To that you need to connect a *U.FL To Female SMA Adaptor*. That adaptor can then screw into an *SMA GSM Antenna* of your choice.

---
Tags: remote-control, system-design, mkr1000
---


# Question
Title: How many clients can connect to an ESP32?
I am using an ESP32 as my master and 10 ESP8266-07s are connected to the master that is in AP mode.

But I need at least 12 clients. Please help me to increase the number of clients the ESP32 can handle in AP mode.

I have read this article but it did not help me ESP32 AP max connections: 4 or 10?

# Answer
> 0 votes
The max number of stations for SoftAP is a runtime setting available in Arduino.

ESP32 arduino WiFi library and esp8266 ESP8266WiFi library have it as last parameter in `softAP()` function which starts the SoftAP.

```
bool softAP(const char* ssid, const char* passphrase = NULL,
    int channel = 1, int ssid_hidden = 0, int max_connection = 4);

```

esp8266 arduino doc

> max\_connection - optional parameter to set max simultaneous connected stations, from 0 to 8. Defaults to 4. Once the max number has been reached, any other station that wants to connect will be forced to wait until an already connected station disconnects.

ESP32 SDK doc

> uint8\_t max\_connection Max number of stations allowed to connect in, default 4, max 10

# Answer
> 2 votes
The SDK API documentation from Espressif directly notes:

> `uint8_t max_connection`
>
> Max number of stations allowed to connect in, default 4, max 4

**EDIT**

However, another area of the API documentation (The API Guide) notes:

> `max_connection`
>
> Currently, ESP32 Wi-Fi supports up to 10 Wi-Fi connections. If max\_connection \> 10, soft-AP defaults the value to 10.

# Answer
> -1 votes
If you use softAP, you can set the max number of connections to 16 I believe.

```
WiFi.softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection);

```

---
Tags: esp32
---


# Question
Title: Turn off power to a moisture sensor except when reading values
I have an Arduino Uno and a moisture sensor (looks like a YL-69 clone) submerged in water. I need to read the sensor's (analog) value every 3 min or so. The problem is: the sensor is always powered by the Arduino (GND and VCC), i.e. the current passes through it at all times. Because of this, one of the sensor's electrodes (presumably containing copper) grows a cyan residue. I'd like to NOT supply any power to the sensor except for the brief moment when I need to read the value. How can I do this?

EDIT: I've just noticed a related question (link below). The user decided to intermittently power the sensor via a digital pin, rather than VCC. Is this reasonable?

Does a moisture sensor need warm-up time?

# Answer
> 5 votes
If your sensor draws less than 40mA to operate, then you can safely "power" it from an GPIO pin.

The related question also asks how long the sensor must be powered in order to get a stable reading. For a sensor such as this one, it appears to be a simple resistive voltage divider, with the moisture sensor itself providing one leg of the divider circuit. The active component appears to be a comparator to provide a digital HIGH/LOW output as an alternative to the analog output.

Most schematics show a capacitor between ground and the voltage divider output, presumably to reduce noise. You need to allow for this capacitor to charge up and become stable before you take a reading. The time for this depends somewhat on the value of that capacitor and the supply voltage you are using.

Safe to assume, however, that a wait time of 1 second is more than enough.

# Answer
> 2 votes
I built a project very similar to this last winter to monitor moisture levels in the soil of plants that I was keeping over winter in my basement. I used GPIO pins to power the sensors similar to what jose can u c described above and performed testing to determine the minimum on time to get readings. I found that 150ms was enough to get stable readings in soils varying from completely saturated and with standing water to very dry (plant leaves starting to show signs of drying out).

# Answer
> 0 votes
Here are other anti-corrosion measures for moisture sensors I found:

A moisture sensor with gold-plated electrodes: https://www.dfrobot.com/product-599.html#.UhflOL-N\_H0

Replacing metal electrodes with graphite: http://tuxgraphics.org/electronics/200908/eth-flower-watering.shtml

Capacitive (i.e. not resisitive) moisture sensor: https://www.amazon.com/DFROBOT-Gravity-Capacitive-Corrosion-Resistant/dp/B01GHY0N4K/ref=cm\_cr\_arp\_d\_product\_top?ie=UTF8

Non-corrosive high quality sensor ($$$): https://www.vegetronix.com/Products/VH400/

# Answer
> 0 votes
I use in my project the fully waterproof sensor SMT50 (see http://www.truebner.de/en/smt50). It is specified from 3.3V to 30V power supply with a current of around 3 mA, so that should be possible to supply it from a GPIO. Please not that the GPIO output voltage decreases with current (see AVR datasheet pin driver strength).

---
Tags: power
---


# Question
Title: Adafruit Huzzah ESP8266 Battery Power issue
I'm trying to connect a ~5.5V (2 x 3V coin cells in series, but their voltage drops a little) to the VBat (or V+) of my **Adafruit Huzzah ESP8266** module (**not** the black Feather one, the smaller blue one: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/pinouts) Whenever I do that the voltage output from the 3.3V pin drops to **~0-1 V** and thus the ESP stops working.

However when I use the FTDI cable (3.3 V) and connect it to my laptop, there is no problem, I get almost 3 V.

I also added a 1000mF capacitor to smooth out voltage signals and actually that also helps to increase the volt a little (without it I get almost a 0 V on the 3.3V output)

Any ideas?

# Answer
After tinkering more, I figured out that the Huzzah module is happy to take in up **4.5V** via a 3 AAA battery cell so I guess it's ok up to 5V since my previous battery input was **over 5V**.

That's a little weird considering that in Adafruit's page, it says

> ..to make it easier to power, we put a high-current-capable 3.3V voltage regulator on the board. It can take 3.4-6V in but you should stick to 4-6V since the ESP8288 has high current usage when WiFi is on.

Hope this may help someone else.
> 1 votes

---
Tags: esp8266, adafruit
---


# Question
Title: Can the Arduino interface with a fingerprint sensor on my mobile?
I own a OnePlus 6 and it has a fingerprint sensor. Instead of using a fingerprint scanner module like the R305, could I just use my mobile for scanning the fingerprints? If yes, how do I implement this?

This is for creating a smart home security system.

# Answer
You'd need an app on your mobile to read the sensor and communicate the result to your Arduino *in a secure way* that cannot be spoofed by an intruder. That secure communication over an open channel (WiFi, I assume?) is not trivial to do right, so that would be a weak point in your security.

Blynk, an app+server+Arduino library combination provides an authentication token to pair with your Arduino in a relatively secure way. You quickly make (drag-and-drop) a control panel for your Arduino system with it. It doesn't offer fingerprint sensing directly, but if you keep your Blynk authentication token a secret, keep your Blynk app+token on your mobile, and the mobile is fingerprint-locked, you'd have essentially the same thing, and the pieces already exist. You'd only need to code the smart-home parts for the Arduino.
> 2 votes

# Answer
Technically, yes it is possible.

1. Write an app for your phone that scans your fingerprint and does "something" with it.
2. Decide on (and implement) some form of communication protocol between the phone and the Arduino and send data from the phone depending on what you decide the "something" above is.
3. Write a sketch for your Arduino that responds to that communication protocol and performs whatever task you require.

The Arduino side of things, effectively, has nothing at all to do with the fingerprint scanner - it just accepts data from your phone. The fact that the phone is generating that data using the fingerprint scanner as a stimulus is of no importance to the Arduino.

99% of the work for the fingerprint scanner will be done on the phone, and done using phone software. Not Arduino software.
> 1 votes

# Answer
Majenko in his answer described how to do it if you can code an application for phone. Other option is a little overkill, but should be a ready solution. You could use 1Shield. It is a shield, a library and a phone app to use phone resources with Arduino. It supports fingerprint sensor. I have no experience with it, I only read about it.
> 1 votes

---
Tags: sensors
---


title: Arduino with 8 LEDs and a switch

text:
# Question
Title: Arduino with 8 LEDs and a switch
I have an assignment wherein we have 8 LEDs connected to an Arduino Uno which has a switch. These LEDs light up according to the johnson counter but every time I turn the switch off it should reset back to the start. An example is if I turned the switch off while the pin is at 8 going back to 1 , then when i turn it on it should be back to 1 again. I got the 1 to 8 reset part right but the 8 to 1, I'm having trouble solving.

Here is my code:

```
int pin;
int sw3 = 10;

void setup() {
  // put your setup code here, to run once:
  for (pin = 2; pin <= 9; pin++) {
    pinMode(pin, OUTPUT);
  }
  pinMode(sw3, INPUT);
}

void loop() {
  pin == 2;
  if (digitalRead(sw3) == HIGH) {
    for (pin = 2; pin <= 9; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
    }
  }
  else {
    digitalWrite(pin, LOW);
  }

  delay(200);

  for (pin = 2; pin <= 9; pin++)
  {
    digitalWrite(pin, LOW);
  }
  delay(200);

  if (digitalRead(sw3) == HIGH) {
    for (pin = 9; pin >= 2; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
    }
  }
  else {

    digitalWrite(pin, LOW);
  }

  delay(200);

  for (pin = 9; pin >= 2; pin--) {
    digitalWrite(pin, LOW);
  }
  delay(200);
  {
    if (digitalRead(sw3) == LOW) {
      digitalWrite(pin, LOW);
    }
    else {
      digitalWrite(pin, LOW);
    }
  }
}

```

# Answer
Some fixes:

`pin==2;` should only be 1 `=` here. `==` is a comparison.

`pinMode(sw3,INPUT);` make this `INPUT_PULLUP`, to turn on the internal pullup resistor

`if(digitalRead(sw3)==HIGH){` change this to `LOW`, and wire your switch/button to connect the pin to GND when pressed. The internal pullup will unsure the pin is HIGH when not pressed, and the button/switch makes it LOW when pressed. The pin is thus not allowed to 'float' and return a random HIGH or LOW.
> 1 votes

---
Tags: arduino-uno, led
---


# Question
Title: Converting a standard setup/loop sketch to a low power application?
Suppose I have a typical setup/loop style sketch, such as this one which turns on an LED when a button is pressed.

How do I modify this so that it enters low power mode, awakes on the button press, and puts itself back into low power mode when its logic has finished?

```
void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // desired: enter low power mode here
}
void loop() {
  int buttonState = digitalRead(buttonPin);
  // desired: awake from low power mode here
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
  // desired: back to low power mode here
}

```

# Answer
This sketch is almost identical to the **powerDownWakeExternalInterrupt.ino** sketch that comes with the `LowPower` Library. I'm using `INPUT_PULLUP` and a N.O. push button switch to trigger it to wake up and turn an LED on.

```
#include "LowPower.h"
const byte wakeUpPin = 2;

// Just a handler for the pin interrupt.
void wakeUp(){}

void setup(){

  // Configure wake up pin as input.
  // This will consumes few uA of current.
  pinMode(wakeUpPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Allow wake up pin to trigger interrupt on low.
  attachInterrupt(0, wakeUp, LOW);

  // Enter power down state with ADC and BOD module disabled.
  // Wake up when wake up pin is low.
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

  // Disable external pin interrupt on wake up pin.
  detachInterrupt(0);

  // Do something here.
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
  digitalWrite(LED_BUILTIN, LOW);

}

```
> 6 votes

---
Tags: power, sleep
---


title: L9110H-bridge motor driver

text:
# Question
Title: L9110H-bridge motor driver
So I have this old RC car which doesn't seem to connect to the joystick very well so im going to modify it with an Uno with 433 MHz receiver/transmitter.

Both the steer and drive motors work as intended so long as you can reverse their current. I've seen people use the dual channel drivers which is what I know I probably what I should use to drive the motors. I bought a starter kit a while back which came with a single L9110H Chip. I thought maybe I could order another one and just solder them to a PCB and mount the PCB along with the Uno inside the car that way I don't have an extra chip just collecting dust. I've looked at the data sheet for the L9110H and came up with a diagram on Fritzing.

I was hoping someone could tell me if I'm on the right track with this?

# Answer
Yes, looks good to me. That looks to be identical to the "Application Circuit" on page 2 of the datasheet you link to.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: What do I do with the potentiometer on Adafruit RGB LCD
So I just got my Adafruit RGB backlight positive LCD 16x2 + extras - black on RGB In this picture it shows a potentiometer beside the LCD. Anyone know where this is supposed to go?

If it helps, I'm mounting the shields on an Adafruit I2C Controlled + Keypad Shield Kit for 16x2 LCD

# Answer
> 1 votes
The potentiometer is for setting the contrast level of the LCD. The Shield Kit shown also comes with a pot (the one with the orange face). Assembled it should look like this:

Notice the pot in the lower right corner to the right of the microcontroller ic and above the reset button.

# Answer
> 1 votes
The contrast is set by inputting an analog voltage into Pin 3 on the LCD header. The analog voltage is created using the potentiometer and is easily adjusted by the user when in operation.

The diagram below shows (only) the circuit needed to adjust the contrast on the LCD display.

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


# Question
Title: how to make GPRS/GSM SIM900 shield work with gps neo-6M module using Arduino UNO board
I'm a beginer to arduino program.i will like to make a program that will send latitude and longitude on my mysql database.so since 3 days i try to learn how to use all this material(GPRS/GSM SIM900 shield, gps neo-6M).But i only success to make them work alone.i also learn that i cannot use SoftwareSerial for GPRS/GSM SIM900 shield and gps neo-6M at the same time. so how can i make GPRS/GSM SIM900 shield and gps neo-6M work together using arduino uno

thank you for you help

# Answer
> 1 votes
I think you are searching for a solution like this Interfacing GSM and GPS Module using Arduino where GPS and GSM modules can run together and receive data at the same time.

I tried bringing up both inside setup() and it blocked the other device. Here is some extract of the code (Note that rx,tx and baud rates may differ according to the modules).

```
SoftwareSerial gsm(7,8);
SoftwareSerial gps(3,4);

void setup() {
    Serial.begin(9600);
    gps.begin(9600);
    gsm.begin(4800); <--- This stopped receiving GPS updates
}

```

If you look for an advanced way of handling this situation, you may need to implement some light-weight threads (e.g Protothreads) and assign GPS and GSM modules to run in separate threads, so one device may not block send/receive of the other device. These Arduino forum answers may help for such approach.

# Answer
> 0 votes
I will suggest you to use TinyGPS to connect only via GPS and get the position, make sure you are testing outside with good view of the sky or the gps will never get a lock down.

Then when you are familiar with TinyGPS and how to get the location, add the GSM module to send over this information to your mysql server.

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


# Question
Title: Sainsmart LCD 2004 - LiquidCrytal_I2C library issue unable to compile
I bought a Sainsmart LCD2004 from Amazon to use with my Arduino Uno. I understand that since this LCD uses I2C a new library needs to be downloaded.

From the sainsmart website I dowloaded the LCD 2004 rar http://www.sainsmart.com/arduino/arduino-shields/sainsmart-iic-i2c-twi-serial-2004-20x4-lcd-module-shield-for-arduino-uno-mega-r3.html

When I try to compile the example titled helloworld I get the following error:

*In file included from HelloWorld.pde:3: C:\Users\r\_yob\_000\Documents\Arduino\libraries\LiquidCrystal\_I2C/LiquidCrystal\_I2C.h:81: error: conflicting return type specified for 'virtual void LiquidCrystal\_I2C::write(uint8\_t)' C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino/Print.h:48: error: overriding 'virtual size\_t Print::write(uint8\_t)'*

There seems to be a conflict between two functions returning different types.

I've tried searching the issue and found a lot of posts with similar errors. The solution suggested is usually that a new version of the LiquidCrytal\_I2C needs to downloaded. Or that one should use Arduino IDE version 1.0

I have downloaded tons of LiquidCrytal\_I2C libraries and tried them all on IDE version 1.0 and 1.0.6 and I still get the same error message. I've even tried changing the LiquidCrytal\_I2C.h file so that it returns the correct type and still have no luck.

Could I please get some help with this issue.

Thank you very much.

# Answer
> 1 votes
I just bought 3 of these that work well with this library LiquidCrystal\_I2C2004V1.zip
(*License: CC BY-NC 2012 http://www.wikispaces.com/user/view/TerryKing*).

When installing this library in Arduino IDE (version 1.6 or later), use menu item **Sketch | Include Library | Add .ZIP Library...**, navigate to the folder where LiquidCrystal\_I2C2004V1.zip was downloaded, and then open the zip file.

Use the I2C address in the example "HelloWorld" supplied with LiquidCrystal\_I2C2004V1:

```
//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.init();
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setCursor(3,0);
  lcd.print("Hello, world!");
  lcd.setCursor(2,1);
  lcd.print("Ywrobot Arduino!");
   lcd.setCursor(0,2);
  lcd.print("Arduino LCM IIC 2004");
   lcd.setCursor(2,3);
  lcd.print("Power By Ec-yuan!");
}

void loop()
{
}

```

Do not change the other library directory name; this one is compatible with the existing library. Just add it as a contributed library.

# Answer
> 1 votes
I had problems with this library too, until I realized the default library name "LiquidCrystal" conflicts with that of another library, which makes that the files get mixed up. Simply place the files in a different folder (I named mine) "LiquidCrystal\_4x20". Solved it for me.

# Answer
> 0 votes
You must to upgrade your I2C library.

Here you can find it the last version:
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads/

And move the old one in another folder so you can use this one or after you install this one do like this:

1. Go in the `Arduino\libraries\Newliquidcrystal_1.3.5\`
2. Rename the `LiquidCrystal_I2C.h` like `LiquidCrystal_I2Ca.h`
3. When you use it in the sketch use include `LiquidCrystal_I2Ca.h`

---
Tags: i2c, lcd
---


# Question
Title: Powering Arduino Uno and Ardumoto Motor Driver Shield
I need to power an Ardumoto Shield to drive two 12V DC motors. I was planning to connect a 12V battery to the Max 18V input on the Ardumoto and a 9V battery to the barrel jack input of the Arduino Uno. Can you tell me if this should be ok or if it would cause any damage to the Arduino?

It mentions in the Ardumoto hookup guide:

There's no mention of the Max 18V input on the Ardumoto.. Advice appreciated, thanks.

# Answer
> **Do not supply power to both the Arduino barrel jack input and VIN on the shield!**

There goes the simple answer. Choose one.

If you power the system through arduino barrel jack input, you will have polarity protection, but the voltage output on VIN pin (which also used by Ardumoto shield) is slightly lower, about 0.6V lower than the input voltage because of the voltage drop on the protection diode.

If you have want to differentiate the supply for Ardumoto and Arduino (as described on your plan), you have to tamper the Ardumoto shield to isolate both supply. Although I never try it myself, it seems possible if you understands how L298 works.
> 1 votes

# Answer
The L298 used in the Ardumoto shield has a maximum supply voltage of 46V. Hence 18V should be sufficient to power it as long as the motors have enough power too.

The Arduino voltage regulator, on the other hand, won't be able to handle such a high voltage. Hence you will have to remove the Vin pin that connects the Arduino & the shield in order to isolate the power supplies of the two.

Only then should you attempt plugging in the shield & then powering the Arduino through the 9V battery.
> 1 votes

---
Tags: arduino-uno, power, motor, shields
---


title: Thermistor doesn't work

text:
# Question
Title: Thermistor doesn't work
Connecting all like shows the image, thermistor shows, that I'm going to be burnt:

The code is simple:

```
#define analogPin  A0 //the thermistor attach to
#define beta 4090
#define resistance 10

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

void loop()
{
  //read thermistor value
  long a =analogRead(analogPin);
  //the calculating formula of temperature
  float tempC = beta /(log((1025.0 * 10 / a - 10) / 10) + beta / 298.0) - 273.0;
  float tempF = 1.8*tempC + 32.0;
  Serial.print("Temp: ");

  Serial.print(tempC);

  Serial.print("  C");

  Serial.print("Fahr: ");
  Serial.print(tempF);
  Serial.print(" F");
  delay(200); //wait for 100 milliseconds
}

```

Do I have a wrong thermistor or wrong code?

# Answer
The series resistance is 220 Ohms (Red, Red, Brown).

You also need to take into account the thermistor resistance at 25C. Assuming its 10K. Hence choosing a 10K series resistance will make the calculations easier.

```
     int THERMISTORNOMINAL =  10000;
     int SERIESRESISTOR = 10000;
     int TEMPERATURENOMINAL = 25;

     a = 1023 / a - 1;
     a = SERIESRESISTOR / a;
     tempC = a / THERMISTORNOMINAL;     // (R/Ro)
     tempC = log(tempC);                  // ln(R/Ro)
     tempC /= Beta;                   // 1/B * ln(R/Ro)
     tempC += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
     tempC = 1.0 / steinhart;                 // Invert
     tempC -= 273.15;                         // convert to C

```
> 3 votes

---
Tags: arduino-uno, arduino-ide, c++, temperature-sensor
---


# Question
Title: Arduino secure two way communication over radio
I would like to implement a secure communication channels between 2 arduinos communicating over 433 mhz radio modules (to be more precise using the barebone Atmega 326 chips).

I know that the lack of resources are a problem with the Atmega chips. The best starting point I could find was this library, which never got written:

https://forum.arduino.cc/index.php?topic=314845.0

The way I see it it does not matter what kind of encoding we use if an attacker can capture and replay that OTA, there has to be a 2nd component between the devices which is not known for an attacker and changes the same way like a DS based timer. If a client could encrypt its messages using key=timeXpassword key-\>encrypt(datatobesent) then the server could decrypt it the same way if it arrived in a proper time period like +-/5 seconds where the time does not have to be the current accurate time just a clock which is in sync between the devices. When the message is received by the server it would calculate 5 different data possibilities for the 5 seconds and look into a decrypted data for certain string to determine if that is a VALID data packet.

For this again there would be the need of an external timer circuit like the DSXXXX series because the internal timer in the chip is not reliable/overflows after a while.

Any other ideas for secure communication?

# Answer
Since you have two-way communication you can be far more cunning that just including a timestamp. You can use real authentication.

The idea here is the "sender" first sends a request to the "receiver" saying "Let me in".

The "receiver" then sends back a message saying "Ok, here's your session key".

The "sender" then encrypts the connection credentials using that session key in some way (or encrypts it in some way including that key with the credentials) - ideally with a trapdoor hash algorithm, and sends it to the "receiver".

The "receiver" then does the same operation with the data it expects the "sender" should send, and compares it with what it received.

If they match, then the "receiver" can allow communication from that "client". The "receiver" would then send a new session key to the "sender" which would then be used to encrypt all communication thereafter. That key must be different to the first, and would need to use symmetric encryption.

This all means that:

* The authentication key changes every time - there is no chance of "replaying" it
* The communication key changes with each session, so again there is no chance of replaying messages at a later data, since the key will be wrong.

Yes, there are a lot of overheads with this method, but it's secure.

The authentication methodology is basically the Challenge Handshake Authentication Protocol (server sends challenge, client responds with credentials along with challenge, trapdoor encrypted, server compares with its own encryption and allows or denies). The rest is basic encryption of your choosing using the unique key the remote end of the connection provides.
> 2 votes

# Answer
You may want to take a look at my RC4-with-diffusion algorithm RC4D which is very resource friendly as it takes less than 500 bytes of flash space (when encrypting inplace) and is much faster than AES128 on an Arduino.
> 1 votes

---
Tags: rf
---


title: 7-12V Power supply + USB

text:
# Question
Title: 7-12V Power supply + USB
Im connecting a servo to my Arduino Uno Rev.3. The general recommendation is to put a 7V -12V power supply for servos as far as I understand. However I’d like to combine it with an USB to a computer since I use it to flush data from a different probe on the Arduino to my PC.

* Will it be safe to use both a AC/DC adapter and serial bus?
* Will it use the USB for power draw even if adapter is connected?

# Answer
> 2 votes
You will see that the Servos have 3 wires \[GND, Power, and Data/Signal\]. You can connect your external power supply to GND and Power of the servos, and connect the GND and Signal wires from the Servos to the Arduino.

By connecting the Grounds of the Arduino and Servos together, they share the same 0V reference and you will not damage either by powering the Servos from a higher voltage and the Arduino from USB.

It is not necessary to connect the Arduino Vin or barrel jack to the external power supply. Look at the Servos+power supply as one independent unit, and the Arduino+USB/Computer as a separate independent unit, and the only things connected between them should be GND and the servo signal/data wire.

---
Tags: arduino-uno, usb
---


# Question
Title: MAX232 chip fails to initialize properly with arduino
I have connected a MAX232 chip for RS232 communication with my Arduino. The chip input is connected to Arduino Tx and it is getting power from external 3.3 volt dc power source.

My Arduino is also getting power from 12 volt DC external power source.

While I connect and start the device, the PC is not getting any data until I reboot the MAX232.

How do I make a robust setup so that after I turn the powers on, it starts transmitting. Even if connection to my PC has been lost.

# Answer
> 3 votes
Datasheet for MAX232

> Section 7.3 Recommended Operating Conditions VCC Supply voltage
>
> MIN=4.5, NOM=5, MAX=5.5 (V)

The MAX232 has a minimum supply voltage of 4.5V, typically expecting 5V.

There are other alternatives, such as the MAX3232, which supports either 3.3V or 5V supply voltage.

---
Tags: serial, power, arduino-due, max232
---


# Question
Title: Problem with encoder count on a segway handlebar
I'm trying to implement a steering mechanism for a segway project. The idea is to sense the tilt of the segway's handlebar with an incremental rotary encoder (omron e6j-cwz 600ppr). This way when I turn the bar to the left or right the segway turns too. I'm using a Teensy 3.2 with the arduino IDE.

To drive the motors I use PWM. The pulse limits are the calibrated values for +/- 100% (+/- 24V) input. The pulse range is 1.0 to 2.0ms, with 1.5ms as the zero value.

Here is a picture of the turning mechanism.

The problem is that, the movement of the handle bar is not very smooth and sometimes after tilting the handlebar and returning it to the straight position, the count never really goes back to 0, but some value around -6 to 6 counts and sometimes even -15 to 15 counts. So the segway tries to turn even though the bar is straight.

The code I'm using to sense the tilt and set the motors is:

```
//Turn encoder
#define c_TurnEncoderPinA 15
#define c_TurnEncoderPinB 14
#define TurnEncoderIsReversed
volatile bool _TurnEncoderBSet;
volatile int _TurnEncoderTicks = 0;
/** Turn position */
int TurnAngular = 0;

/** Proportional gain */
int kp = 55;

/** voltage to the motor*/
float vol = 0;
float aux;
/** calulated pwm pulse*/
float uy = 0;

/**Left motor control*/
int motorL=9;
/**Right motor control*/
int motorR=10;

//Mapping voltage to pwm (Mc 160 controller)
float  p1 = -25.44, p2 = 0.1894, p3 = 146.6, p4 = -0.2874, p5 =  -480, p6 =  1500; //pwm3

//Discrete time values
const int samplingTime = 1000*10; // 10000 microseconds = 10ms
unsigned long previousTime, currentTime, timeDifference;
int estimationTimeCount = 1;

void setup() {
  delay(3000);
  Serial.begin(115200);
  delay(2000);
  previousTime = micros();
  // Turn encoder
  pinMode(c_TurnEncoderPinA, INPUT_PULLUP);      // sets pin A as input
  pinMode(c_TurnEncoderPinB, INPUT_PULLUP);      // sets pin B as input
  attachInterrupt(digitalPinToInterrupt(c_TurnEncoderPinA), HandleTurnMotorInterruptA, RISING);

  /*Initiate Output*/
  analogWriteResolution(11);
  pinMode(motorR,OUTPUT);
  pinMode(motorL,OUTPUT);
  analogWrite(motorR, 1500);
  analogWrite(motorL, 1500);

Serial.println("Start...");
}

void loop() {
  currentTime = micros();
  timeDifference = currentTime - previousTime;
  if (timeDifference > samplingTime)
  {
    previousTime = currentTime;
    sampleEncoders();
    setMotors();
    printData();
    estimationTimeCount++;
  }
}

void sampleEncoders() {
  TurnAngular = _TurnEncoderTicks; //update encoder reading every 10ms.
}

float turn(){
  if(TurnAngular<=6 && TurnAngular>=-6)
  {
    return 0;
  }
  else
  {
   //the voltage is calculated with a proportional gain
   //times the angle of the encoder in radians.
    return (kp*TurnAngular*(2*pi/(pprT)));
  }
}

void setMotors() {
    vol = turn();

    // this two lines map the calculated voltage to the pwm
    // in a range of 1000 to 2000.
    aux = (vol+0.01143)/13.13;
    uy = (int) p1*pow(aux,5) + p2*pow(aux,4) + p3*pow(aux,3) + p4*pow(aux,2) + p5*(aux) + p6;
    uy = constrain(uy, 1000,  2000);

    // this is just and idea I had to counter the problem.
    // if the control is within +/-50 pulses from 1500
    // set the pulse to 1500, and the last saved value of the count to 0.
    // every 2.5 sec if the condition in met, then also reset the actual
    // count of the encoder
    if (uy < 1550 && uy > 1450)
    {
      uy = 1500;
      TurnAngular = 0;
      if ( estimationTimeCount%250 == 0 && _TurnEncoderTicks != 0)
      {
        _TurnEncoderTicks = 0;
      }
    }
  }

  /**
 Left wheel (L): forward from 1500 to 1000, backward from 1500 to 2000.
 Right wheel (R): forward from 1500 to 2000, backward from 1500 to 1000.
  **/
 //set uy to each wheel to make the segway turn.
  analogWrite(motorR,uy);
  analogWrite(motorL,uy);
}

void printOutput()
{
  Serial.print("tout(");
  Serial.print(estimationTimeCount);
  Serial.print(", :) = [");
  Serial.print(TurnAngular);
  Serial.print(", ");
  Serial.print(_TurnEncoderTicks);
  Serial.print(", ");
  Serial.print(currentTime*pow(10,-6));
  Serial.println("];");
}

void HandleTurnMotorInterruptA()
{
  // Test transition; since the interrupt will only fire on 'rising' we don't need to read pin A
  _TurnEncoderBSet = digitalRead(c_TurnEncoderPinB);   // read the input pin
  // and adjust counter + if A leads B
  #ifdef TurnEncoderIsReversed
    _TurnEncoderTicks -= _TurnEncoderBSet ? -1 : +1;
  #else
    _TurnEncoderTicks += _TurnEncoderBSet ? -1 : +1;
  #endif
}

```

The original code for the encoder count can be found here.

In the code I put one of my own but it fails sometimes, I set a 0 voltage to the motors is the count is between +/- 6 counts. A secondary issue is that when the bar tilt's to for example +7 counts the control is to aggressive, so I keep trying to find an ideal proportional gain.

Lastly I did not add the code for the balance action of the segway, mainly because it is not the issue and the control effort is just set to 0 while I try to fix the problem. Also, it would be too long.

What kind of solution would you guys think of?

I've edited the turn function like this:

```
float turn(){
int8_t TurnVal = 0;
  //deadZoneSize = 6
  if(TurnAngular <= deadZoneSize && TurnAngular >= -deadZoneSize)
  {
    return 0;
  }
  else
  {
    if (TurnAngular<0)
    {
      TurnVal = TurnAngular + deadZoneSize;
    }
    else
    {
      TurnVal = TurnAngular - deadZoneSize;
    }
    Serial.println(TurnVal);
    return (kp*TurnVal*(2*pi/(float)(pprT)));
  }

```

I can't find a way to fix the error between the actual straight position and the measured straight position (0 count). Sometimes after some movement of the bar, the actual straight position lies outside the dead zone, and the segway wants to turn anyways.

Here is an illustration.

# Answer
> 1 votes
What you have come up with on your own is almost what is called a "dead zone", where the angle between -6 and 6 is ignored.

All you need to do now is not reference the actual angle when computing how much to turn, but to reference the distance from the edge of the dead zone:

```
const uint16_t deadZoneSize = 6;
[...]

float turn(){
  unint8_t TurnVal = 0;
  if(TurnAngular<=deadZoneSize && TurnAngular>=-deadZoneSize)
  {
    return 0;
  }
  else
  {
   //the voltage is calculated with a proportional gain
   //times the angle of the encoder in radians.
    if (TurnAngular<0) {
      TurnVal = TurnAngular + deadZoneSize)
    } else {
      TurnVal = TurnAngular - deadZoneSize)
    }
    return (kp*TurnVal*(2*pi/(pprT)));
  }
}

```

---
Tags: arduino-ide, rotary-encoder
---


# Question
Title: How can i split an incoming data in arduino?
So for my arduino project I need to split this line of servos data

```
180 0 0 0 90 90 0

```

Which would be parsed as:

```
servo position1 servo positin2 servo positin3 ...servo position 6

```

in to separate servo values, but i am new at arduino and c typе languges so a little bit help will be very good. So my question is how can I split these values up?

# Answer
> 1 votes
Scanning string formatted data can be done with `sscanf` (docs). It takes format strings just like `printf()` does, but instead of printing formatted data, it parses formatted data into the given variables.

For example,

```
String input = "180 0 0 0 90 90 0";
//parse input (6 integers)
int servoPositions[6];
int numScanned = sscanf (input.c_str(),"%d %d %d %d %d %d",
    &servoPositions[0], &servoPositions[1],&servoPositions[2],
    &servoPositions[3], &servoPositions[4],&servoPositions[5]);

//print positions again
Serial.println("Parsed servo positions:");

for(int i=0; i < 6; i++) {
    Serial.print("position ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(servoPositions[i]);
}

```

Outputs

```
Parsed servo positions:
position 0: 180
position 1: 0
position 2: 0
position 3: 0
position 4: 90
position 5: 90

```

---
Tags: serial-data
---


# Question
Title: Are any Arduino boards especially suited for low-power operation?
The Arduino project has done an excellent job in providing a portable software interface to a number of different hardware systems.

Are there any Arduino-compatible systems which are especially applicable for very low power battery-based operation? Specifically, in an application where a device wakes up periodically (e.g. for data collection) or activated by a user button press?

# Answer
> 4 votes
Technically you can use any arduino for that purpose with some modifications. I recommend to go with an arduino Pro Mini and remove the LED and the voltage regulator.  But if you don't need so much I/O you can go with a digispark Attiny board.

---
Tags: power, battery
---


# Question
Title: How to configure TinySine 3G module (SIM5320E) for HTTP GET request
I recently bought a 'TinySine 3G shield (SIM5320E) 900/2100Mhz' based on Adafruit\_FONA libraries to use with Arduino Mega 2560 R3. It successfully registered with Vodafone AU. Other functionality works (SMS, GPS) but not HTTP/TCP.

I'm following this TCP/UDP section of SimCom tutorial to receive data from a REST API. But I cannot set the APN for TCP as there is no support for `AT+CSTT` command as it seems.

I can see it's on WCDMA network.

```
    AT+CREG?
    +CREG:1,1

    AT+CPSI?
    +CPSI: WCDMA,Online,505-03,0x014E,xxxxxxx,WCDMA IMT xxxx,xxx,xxxx,0,12.0,97,12,18,500
    OK

```

**Error comes here**

```
    AT+CSTT="live.vodafone.com"
    ERROR

```

Is there a way to resolve this issue \- With the same setup/libraries OR \- By upgrading libraries/firmware of the module OR \- Using any other set of commands

Please provide if any of you have a sample code to access a REST API. Appreciate your help very much.

# Answer
CSTT works on GPRS modules like SIM900. I found a way to get SIM5320E working to download websites. Tested with TeraTerm and used `<Ctrl M>` and `<Ctrl J>` instead of `'<CR> <LF> OR /r/n'` characters.

**Network setup**

```
AT+CGDCONT=1,"IP","<your APN>","0.0.0.0"
AT+CGSOCKCONT=1,"IP","<your APN>"
AT+CSOCKSETPN=1

```

**Start HTTP service** You can stop and start service if it's not responding properly.

```
AT+CHTTPSSTART
AT+CHTTPACT="www.iforce2d.net",80

```

**HTTP GET request**

```
GET /test.php HTTP/1.1  <-- don't hit enter, instead hit the below 2 keys
<Ctrl M>
<Ctrl J>
Host: www.iforce2d.net  <-- don't hit enter, instead hit the below 2 keys
<Ctrl M>
<Ctrl J>
Connection: close  <-- don't hit enter, instead hit the below 4 keys. This is useful when connecting to REST APIs to download the the respective result only.
<Ctrl M>
<Ctrl J>
<Ctrl M>
<Ctrl J>

```

To end the command and to receive results:

```
<Ctrl Z>

```

You will receive a lot of data here.

**Stop HTTP service**

```
AT+CHTTPSCLSE
AT+CHTTPSSTOP

```

You will get the contents of the website. Probably it should contain the data you need (I didn't test the content. May be you will need to tweek the result a bit.)
> 0 votes

---
Tags: arduino-uno, arduino-mega, gsm, http, tcpip
---


# Question
Title: Wemos D1 EEProm put/get not getting correct value
Hey all I have the following code in my Arduino IDE:

```
#include <EEPROM.h>
#include <ArduinoJson.h>

bool debuggin         = true;
int brightness        = 255;
int ambientLight      = 30;
struct RGBLA {
  uint8_t R;
  uint8_t G;
  uint8_t B;
  uint8_t L;
  uint8_t A;
};

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

  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  EEPROM.begin(512);
  readSavedSettings();
  updateEEProm(255,255,255,200,35,true,false);
}

RGBLA readEEProm() {
  int addr = 0;
  RGBLA customVars;

  EEPROM.get(addr, customVars);
  return customVars;
}

void readSavedSettings() {
  RGBLA returnedVars = readEEProm();
  if (debuggin) { Serial.println("START readSavedSettings"); }

  if (returnedVars.A == 00 || returnedVars.A == 0) {
    if (debuggin) { Serial.println("'A' not found! Default 30"); }
  } else {
    ambientLight = returnedVars.A;
    if (debuggin) {
      Serial.print("'A' found! ");
      Serial.println(ambientLight);
    }
  }

  for(uint8_t i = 0; i < 3/*strip.numPixels()*/; i++) {
    if (debuggin) {
      Serial.print("LED ");
      Serial.print(i);
      Serial.print(" set to: R: ");
      Serial.print((uint8_t)returnedVars.R);
      Serial.print(", G: ");
      Serial.print((uint8_t)returnedVars.G);
      Serial.print(", B: ");
      Serial.println((uint8_t)returnedVars.B);
    }
  }

  if (debuggin) {
    Serial.println("Turned off RGB LEDS");
    Serial.println("END readSavedSettings");
  }
}

void updateEEProm(uint8_t R,
                  uint8_t G,
                  uint8_t B,
                  uint8_t L,
                  uint8_t A,
                  bool saveRGBL,
                  bool saveA) {
  int addr = 0;
  RGBLA customVars;

  //Save old json before clearing EEProm
  EEPROM.get(addr, customVars);

  //Clear EEProm
  for (unsigned int i = 0; i < EEPROM.length(); i++) {
    EEPROM.write(i, 0);
  }

  if (saveRGBL) {
    //Get A value so that we can save it the same value
    DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
    JsonObject& root = jsonBuffer.createObject();

    if (debuggin) {
      Serial.print("Old JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)customVars.R);
      Serial.print(" G: ");
      Serial.print((uint8_t)customVars.G);
      Serial.print(" B: ");
      Serial.print((uint8_t)customVars.B);
      Serial.print(" L: ");
      Serial.print((uint8_t)customVars.L);
      Serial.print(" A: ");
      Serial.println((uint8_t)customVars.A);
    }

    root["R"] = (uint8_t)R;
    root["G"] = (uint8_t)G;
    root["B"] = (uint8_t)B;
    root["L"] = (uint8_t)L;
    root["A"] = (uint8_t)customVars.A;

    if (debuggin) {
      Serial.print("New JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)root["R"]);
      Serial.print(" G: ");
      Serial.print((uint8_t)root["G"]);
      Serial.print(" B: ");
      Serial.print((uint8_t)root["B"]);
      Serial.print(" L: ");
      Serial.print((uint8_t)root["L"]);
      Serial.print(" A: ");
      Serial.println((uint8_t)root["A"]);
    }

    EEPROM.put(addr, root);
  }

  if (saveA) {
    //Get R,G,B,L values so that we can save it the same value
    DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
    JsonObject& root = jsonBuffer.createObject();

    if (debuggin) {
      Serial.print("Old JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)customVars.R);
      Serial.print(" G: ");
      Serial.print((uint8_t)customVars.G);
      Serial.print(" B: ");
      Serial.print((uint8_t)customVars.B);
      Serial.print(" L: ");
      Serial.print((uint8_t)customVars.L);
      Serial.print(" A: ");
      Serial.println((uint8_t)customVars.A);
    }

    root["R"] = (uint8_t)customVars.R;
    root["G"] = (uint8_t)customVars.G;
    root["B"] = (uint8_t)customVars.B;
    root["L"] = (uint8_t)customVars.L;
    root["A"] = (uint8_t)A;

    if (debuggin) {
      Serial.print("New JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)root["R"]);
      Serial.print(" G: ");
      Serial.print((uint8_t)root["G"]);
      Serial.print(" B: ");
      Serial.print((uint8_t)root["B"]);
      Serial.print(" L: ");
      Serial.print((uint8_t)root["L"]);
      Serial.print(" A: ");
      Serial.println((uint8_t)root["A"]);
    }

    EEPROM.put(addr, root);
  }
}

void loop() {
}

```

And this is the output of that code:

```
START readSavedSettings
'A' found! 96
LED 0 set to: R: 48, G: 255, B: 255
LED 1 set to: R: 48, G: 255, B: 255
LED 2 set to: R: 48, G: 255, B: 255
Turned off RGB LEDS
END readSavedSettings
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

```

Now when I reset it this is the output:

```
⸮dOX⸮,R⸮X⸮4xC⸮⸮⸮START readSavedSettings
'A' found! 96
LED 0 set to: R: 48, G: 255, B: 255
LED 1 set to: R: 48, G: 255, B: 255
LED 2 set to: R: 48, G: 255, B: 255
Turned off RGB LEDS
END readSavedSettings
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

```

How come the **Old JSON** has the **'L'** value as **63** again when it should be the **New JSON** value of **200**? Why did it not save it but saved all the others? Also, Why is **'R' 48** when it should be **255** like **G** and **B**?

Is there something wrong in my code?

**Update 1**

This is the output after adding .end() to it:

```
START readSavedSettings
'A' found! 160
LED 0 set to: R: 48, G: 255, B: 255
LED 1 set to: R: 48, G: 255, B: 255
LED 2 set to: R: 48, G: 255, B: 255
Turned off RGB LEDS
END readSavedSettings
Old JSON: R: 48   G: 255  B: 255  L: 63 A: 160
New JSON: R: 255  G: 255  B: 255  L: 200 A: 160
Old JSON: R: 128  G: 12   B: 17   L: 17 A: 60
New JSON: R: 128  G: 12   B: 17   L: 17 A: 35

```

and the code i use:

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

  EEPROM.begin(512);
  readSavedSettings();
  updateEEProm(255,255,255,200,35,true,false); //Save all but 'A' value
  EEPROM.end();
  updateEEProm(255,255,255,200,35,false,true); //Save just 'A' value
  EEPROM.end();
}

```

# Answer
> 2 votes
The esp8266 EEPROM emulation library requires a commit() call to save the memory image of EEPROM to flash.

Add `EEPROM.commit();` or `EEPROM.end();` as last line in your `updateEEProm()` function. Documentation link:

Second problem is that you don't write the RGBLA struct to EEPROM, instead you try to write the variable `root`, which is an instance of class JsonObject. Class types can't be put into EEPROM.

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