# Question
Title: Time information from GPS receiver: how to tell whether it is fresh or stale?
I see that TinyGPS++ library extracts time information from `GxRMC` and `GxGGA` NMEA sentences streamed by GPS receiver. However, in my experiments I observed that both of my GPS receivers generate `GxRMC` sentences with time data in them at least once a second even when they have no access to satellites.

I presume that the time data comes from the internal clock of the receiver (and is maintained between warm startups). This is perfectly OK. However, I would like to know what measures are required by NMEA specification to ensure the reliability of this time data.

Am I correct in assuming that the device itself is supposed to understand that after certain period of time its internal clock will diverge? And that after that period the device will by itself stop pumping out these `GxRMC` sentences, until it gets a chance to see a satellite and re-sync its internal clock? Or should I expect to see the next field in `GxRMC` sentence to change from `A` to `V`?

If not, then what is the proper way to ensure that I receive "satellite time" (or close to that) or nothing at all?

# Answer
Most of the GPS modules keep on sending the data in the NMEA format whether they have a GPS fix or not, however, you can parse the GPS data to find whether the data is the latest data received from the GPS or not. If you look at the definition of the NMEA data here, there are a few variables in the data that you can use to find whether the data is the latest data from the GPS or not.

You can use the "Fix Quality" in GPGGA as well as "Validity/Receiver warning" in GPRMC for your module. The tinyGPS indeed has both of these variables being parsed.

In the tinyGPS library, if **\_gps\_data\_good** is true then the data coming from the GPS module is the latest data it received from the GPS satellites. The program uses either the fix or validity to determine this (Refer to the library here and here).

You should just keep checking this variable to find whether the current data is the latest from the GPS or is it being calculated internally.
> 3 votes

---
Tags: gps, time, tinygps
---


# Question
Title: Is there a library for non-SAMD Arduinos to use the DMP on MPU9250
I would like to use the DMP of the MPU9250 with my BTLE Feather board but the docu of the official library says that only SAMP-Processors are supported.

Is the a different library I can use?

# Answer
> 1 votes
I did have a look at the MPU9250 DMP library provided by Sparkfun and it seems that it is specifically built for their own board which has an M0 chip on the board. However looking at the library, there seems to be no reasons why it would not work with any other board. The main reason why it might not work with something like the 32u4 board would be because the end firmware is too large or the program need too much RAM that what the 32u4 has.

There is a fix provided on the github issues page for using it with a Nano, which might help you get it work with the 32u4 here and there is another library here that you might be able to use or build up on.

However the best way might be to use a M0 chip itself if you really want to use the same IMU since getting the library to work can turn out tricky. Adafruit does sell a M0 with a Bluetooth board here that you might be able to use.

---
Tags: imu
---


# Question
Title: Problems integrating Reed Switch and Solenoid Lock in Arduino Code
I am trying to integrate solenoid lock, reed switch in my Arduino Code. The flow that I am trying to achieve is - first, the solenoid lock is set to LOW and then the program checks if reed switch is High or Low. Only if its High I want to proceed further. However, even when the reed switch is HIGH the program is not executing further. Here is my code below:

```
    #include<HX711_ADC.h>
    #include<math.h>

    //pins for lock
    int solenoidPin = 7;

    //pins for reed switch
    int reedSwitch = 2;
    bool reedSwitchStatus;

    //pin for led
    int led_pin= 9;

    void setup()
    {
      Serial.begin(38400);
      pinMode(solenoidPin, OUTPUT);
      pinMode(reedSwitch, INPUT);

      doorUnlock();
    }

    void loop()
      {}

    void doorUnlock()
    {
      digitalWrite(solenoidPin, LOW);
      delay(5000);
      checkReedSwitchStatus();
    }

    void checkReedSwitchStatus()
    {
      reedSwitchStatus = digitalRead(reedSwitch);

      if(reedSwitchStatus == 1)
      {
        Serial.println("Beginning Transaction");
        beginTransaction();
        }
      if (reedSwitchStatus == 0)
        {
          Serial.println("Ending trasaction");
          endTransaction();
          }
      }
      void beginTransaction()
      {
      digitalWrite(led_pin, HIGH);
      delay(500);
      digitalWrite(led_pin, LOW);
      delay(500);
      }

```

My issue is the beginTransaction function is never executed. Serial monitor continuously prints 'Beginning Transaction'. Attached the screenshot of the serial monitor. Please suggest me what is the error in my code. Thanks in advance!

# Answer
The problem is, that you don't initiate the LED's pin to an output. On reset the pin is configured as input. Doing a `digitalWrite(led_pin, HIGH)` in this state just enables the internal pullup resistor. If you measure the voltage without the LED connected, it will be 5V, but since the pin only provides a very small amount of current through the pullup resistor, the LED cannot light up when connected.

You need to configure the LED's pin as an output through

```
pinMode(led_pin, OUTPUT);

```

in your `setup()` function.

So actually the `beginTransaction()` function was correctly executed. You just couldn't see it.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Particle Electron to RS232 Serial gibberish
I've spent all day trying to monitor serial console output of a router. I'm using an "ebay" MAX3232 RS232 to TTL converter connecting only GND, TX and RX to the Electron. Trying to simply monitor the console output during bootup - all I get is gibberish.

Even connected to computer's COM1 port and was unable to echo back and forth. All I get is 0 or weird symbols. (this was tried with more code than below)

Here's my most basic code. I'm about ready to give up. Any ideas?

```
#include "Particle.h"

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600); // tried with 2400/even 1200 really should be 9600
  Serial.println("Starting up Serial");
  Serial1.println("Starting up Serial1");
}

void loop() {
 while(Serial1.available()>0)
 {
   Serial.write(Serial1.read());
 }
 delay(50);
}

```

# Answer
> 1 votes
If the OP has correctly stated that only three connections to the MAX3232 have been made, power to the device is missing. Code tested with an RS232 transmitting device (Maxbotix 7092) with Sparkfun MAX3232 breakout and Particle Photon. Serial monitor correctly displays continuous range reading.

# Answer
> 0 votes
You do not need any hardware between the Particle and the router. Both the router and the Particle work at 3.3V logic levels.

* Connect the GND of the router the GND of the Particle
* Connect the TX of the router to the RX1 of the Particle
* Connect the RX of the router to the TX1 of the Particle

You only need the MAX3232 if you want to connect direct to your computer's RS232 port:

* Connect the GND of the MAX3232 to the GND of the computer and the GND of the router
* Connect the TX of the computer to RIN of the MAX3232
* Connect the RX of the computer to DOUT of the MAX3232
* Connect the TX of the router to the DIN of the MAX3232
* Connect the RX of the router to the ROUT of the MAX3232
* Connect the VCC of the MAX3232 to +3.3V from the router.

---
Tags: serial, rs232
---


# Question
Title: ESP8266 ESP-07 does not respond to commands
I just bought an ESP8266 ESP-07 V1.0 Serial Wifi Transceiver. Similiar to this: https://www.ebay.com/itm/ESP8266-Serial-Wifi-Transceiver-Module-for-Arduino-ESP-07-V1-0-New-/331868488091

I have connect the RX and TX pins to the RX and TX pin of the Arduino (RX to TX and TX to RX), VCC is connected to 3.3V and GND is connected to Arduino ground. I have used the following code and writing commands to the module using the serial monitor:

```
#include <SoftwareSerial.h>

int RX_PIN = 3;
int TX_PIN = 4;

SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

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

    while (!Serial){
    ;
  }

    while (!mySerial){
    ;
  }
  Serial.println("Ready");
}
void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( mySerial.available() )   {  Serial.write( mySerial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  mySerial.write( Serial.read() );  }
}

```

Whatever I type (for example AT+GMR) in the serial monitor at 9600 baud I don't get any response. What could be the reason? Both NL and CR is added to the command.

When pressing reset on the ESP-module I get this in the Serial monitoring:

Thanks for any help!

# Answer
> 1 votes
The esp8266 is without AT firmware. Even with SoftwareSerial at 115200 baud you should see "ready" from AT firmware and get some response to AT commands.

This esp8266 module adapter is simple to flash. It makes the 5 V to 3.3 V conversion for power and RX pin and has a program switch (io 0) and a reset button to put the esp8266 into flashing mode.

Use an USB-to-TTL-Serial adapter or an Arduino with USB chip to connect the adapter to PC. Then switch to "program" and reset it and it will be in flashing mode.

You can download the AT firmware here. I recommend ESP8266 NonOS AT Bin V1.7.1. Don't try 2.0, it is very different (ESP32 AT firmware build for esp8266).

To flash it, use esptool

The command to flash the AT firmware binaries to any module with at least 1 MB flash memory is:

```
esptool.py write_flash --flash_size 2MB-c1 0x0 boot_v1.7.bin 0x01000 at/1024+1024/user1.2048.new.5.bin 0x1fb000 blank.bin 0x1fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x1fe000 blank.bin

```

don't wonder about the 2MB-c1 setting and don't change it. The AT binaries are build for 2MB-c1 partitioning. On 1 MB flash it will not support AT firmware OTA update.

If you want to use the Espressif Flash Download Tool, use the same settings as on esptool command line.

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


title: SIM800L is not registering on network

text:
# Question
Title: SIM800L is not registering on network
I'm testing SIM800L module by registering to network manually and I'm getting an `error` message. Here are the commands I tried.

```
AT+CSQ

+CSQ: 31,0

OK

AT+CBAND?

+CBAND: EGSM_MODE,ALL_BAND

OK

AT+COPS=?

+COPS: (1,"Bharat Karnataka","CellOne","40471"),(2,"Airtel","AIRTEL","40445"),(3,"Hutch-Kamataka","HUTCH","40486"),,(0-4),(0-2)

OK

AT+COPS=1,1,"40471"

ERROR

```

`AT+COPS=1,1,"40471"` is this command right? My SIM card is CellOne and it's 4G.

Power supply -7.4 li-ion 1100mAh battery with an adjustable 5V-5A buck converter(3.8v is supplied to SIM800L)

# Answer
> 1 votes
For the `AT+COPS` command you are setting manual with long alphanumeric network name but then using the numeric network name. Try `AT+COPS=1,2,"40471"`

REF

```
//Manually select T-mobile as carrier using short format alphanumeric network name
AT+COPS=1,0,"TMO"

//Manually select T-mobile as carrier using long format alphanumeric network name
AT+COPS=1,1,"T-Mobile USA"

//Manually select T-mobile as carrier using numeric network name
AT+COPS=1,2,"310260"

```

---

`AT+CSQ` checks the signal strength, you can check the reply range with a question mark,

```
AT+CSQ=?

+CSQ: (0-31,99),(0-7,99)

OK

```

The first number, 31, shows you have a good signal strength locally.

---

`AT+CBAND?` shows the mobile operating band set

---

`AT+COPS=?` will search for networks, your response indicates you found a few.

---
Tags: arduino-uno, gsm, network
---


# Question
Title: Where do class files go in Sloeber Eclipse project?
I'm attempting to create a new Arduino project using Sloeber (Eclipse). Assume it's a newly-created project whose main entry file is ".\ArduinoMainClass.ino"

Now... assume I want to create a half dozen new classes:

* ExecutionState-- a C++ class that's intended to be functionally equivalent to a Java Interface. If you're wondering, I'm attempting to implement the 'State' pattern.
* GoodState, BadState, UglyState, WeirdState-- C++ classes that all extend ExecutionState. If they were Java, they'd technically be implementing an interface... but since this is C++ and I'm still taking baby steps, for now ExecutionState is just a class with one method that does nothing, and all of THESE classes override it to do the actual work.
* StateContainer-- a C++ class whose only purpose in life is to hold single instances of GoodState, BadState, UglyState, and WeirdState. If this were Java, they'd be Singletons... GoodState (and the others) would have something like:

```
    private static ExecutionState instance = new GoodState();
    // ...
    public static ExecutionState getInstance() { return instance; }

```

... but it's obviously not Java, and I'm nowhere close to knowing enough about C++ to properly implement static singletons yet, so for now, I'm just going to create an instance of StateContainer to create and hold those single instances.

So... I now have Sloeber/Eclipse loaded, and I've created my project. If this were Java, I'd create a subdirectory like .\src\java\com\packagename\executionstate and stick the .cpp and .hpp files for ExecutionState, GoodState, BadState, UglyState, WeirdState, and StateContainer in it, and add "include com.packagename.executionstate.\*" to it.

* I know C++ namespaces have no direct connection to directory names
* I've gotten the impression that "Arduino"-ish C++ auto-generates the #include files for things it regards as libraries. I have a hunch that I probably want to put all of the classes I mentioned above in a directory somewhere and present them to the IDE as an Arduino "library" so they'll all get implicitly included in one go within the .ino file.
* I'm completely confused about what I need to #include in the classes I mentioned above so they can mutually find each other... and whether those #includes rightfully belong in the .hpp or .cpp files.

So... getting back to the big picture. If my project is in c:\users\moi\Documents\Slober-workspace\FirstSloeberArduinoApp...

1. Where do the .cpp and .hpp files for ExecutionState, GoodState, BadState, UglyState, WeirdState, and StateContainer go? (Assume I'd be inclined to put them all in a directory named "executionstates" somewhere in the project's directory hierarchy, but I'm not sure where that exact directory should go).
2. What #includes do I need to put in ExecutionState, Good/Bad/Ugly/WeirdState, and StateContainer... and do they go in the .hpp file, or the .cpp file for their respective class?
3. What do I have to do so the .ino file can find StateContainer?

In case you're totally confused at this point, my actual .ino file will look something like this:

```
void setup() {
    // executionStates is a global variable declared higher up
    executionStates = new StateContainer();
    executionState = executionStates.getGoodState();
    // StateContainer's constructor itself creates instances of the various subclasses of ExecutionState,
   // and passes references to itself to their constructors so they can
   // get the references to the others states as they need to return them.
}

void loop() {
    executionState = executionState->doSomething();
    /* executionState holds a pointer to an instance of an ExecutionState subclass.
       Each time doSomething() executes, it returns a pointer to its new state
     */
}

```

... and in reality, there will be dozens of subclasses of ExecutionState, each representing a unique execution state.

# Answer
With Sloeber Eclipse plugin the ino files go to root of the project and the cpp, c and h files can be in root or in subfolders. example:

Folders created by Sloeber: `core` subfolder is a virtual folder with links to Arduino core files and variant files of the selected board. `libraries` folder is a virtual folder with links to libraries selected for the project. `Release` folder contains the generated make file, the .o files and the resulting elf, hex, bin files. (And sloeber.ino.cpp is a file generated by Sloeber)

Project folders: `data` folder in example picture is a convention for a folder with esp8266 SPIFFS files. `utility` is a subfolder with additional source files of the project.
> 1 votes

# Answer
I put my class files, \[class\].cpp and \[class\].h, in the same folder as my project.ino file, at least during development. Then, if they're sufficiently general, I'll move them to \[workspace\]/libraries/\[class\]/ for future use.

But even if they're only for this project (so they might as well stay in the project's source code folder), it's good organization to keep them in their own files, since by nature, classes only expose their interfaces, not their "guts".
> 0 votes

---
Tags: c++, sloeber
---


# Question
Title: Is std::array (from the C++ STL) safe to use on arduino? Does it use dynamic memory allocation?
I'd like to use std::array on a project that will need to be very stable, and have all memory pre-allocated to avoid heap fragmentation.

I am reading in characters from the serial port, following a known protocol. Each received byte will be written to a char array of ample size to hold the longest possible string I will receive. I will then perform some minor on the fly operations, (i.e. skipping certain characters, replacing one with another, etc.) and write those out another serial port.

This device needs to function indefinitely. I will not be calling malloc or new anywhere in my code. All of my control objects are singletons, (audible gasp from the high-level crowd!) created during setup, and never being destroyed.

Is the STL array template safe to use in this context?

After reading this post, and this post, the only potential issues I can see are exception handling. As far as I'm concerned, an exception is as fatal as an access violation. I would not expect to ever attempt recovery from an exception, so I don't care that Arduinos don't support them.

But what will happen if the program tries to throw one? Will the arduino compiler even allow the use std::array if it supports exceptions? Is there an Arduino-friendly array template that uses fixed size arrays and supports iterators?

Thanks!

# Answer
`std::array` does not use dynamic memory allocations to store its elements. If you use static or stack-allocated `std::array`s, you don't have to worry about memory fragmentation (contrary to `std::vector` or `String`, for example).
Of course, if you allocate arrays on the stack, you can have a stack overflow if you call too many functions, either by design, or because of a bug.

That brings us to the problem of exceptions. If you look in the standard, you'll see that most of the member functions of `std::array` are marked `noexcept`, with the notable exception of the element accessors. Obviously, the `at()` accessor can throw, but you'd expect that `operator[]` doesn't.
In practice, `operator[]` is marked `noexcept` in the version of the STL (GCC9) that I have on my computer, so if you check it in the STL implementation you're using, you can be pretty confident that it won't throw. Just keep in mind that this is not mandated by the standard.

**/usr/include/c++/9/array**

```
      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

```

The debug version is also marked `noexcept`, but it can throw/abort if the index is out of bounds:

**/usr/include/c++/9/debug/array**

```
      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      {
    __glibcxx_check_subscript(__n);
    return _AT_Type::_S_ref(_M_elems, __n);
      }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      {
    return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n)
     : (_GLIBCXX_THROW_OR_ABORT(_Array_check_subscript<_Nm>(__n)),
        _AT_Type::_S_ref(_M_elems, 0));
      }

```

The STL implementations for Arduino I found online don't seem to have the `<array>` header.

Luckily, you can easily create your own array container, for example:

```
template <class T, size_t N>
struct Array {
    // Storage
    T data[N];

    static size_t length() { return N; }
    using type = T;

    // Item access
    T &operator[](size_t index) { return data[index]; }
    const T &operator[](size_t index) const { return data[index]; }

    // Iterators
    T *begin() { return &data[0]; }
    const T *begin() const { return &data[0]; }
    T *end() { return &data[N]; }
    const T *end() const { return &data[N]; }

    // Comparisons
    bool operator==(const Array<T, N> &rhs) const {
        if (this == &rhs)
            return true;
        for (size_t i = 0; i < N; i++)
            if ((*this)[i] != rhs[i])
                return false;
        return true;
    }
    bool operator!=(const Array<T, N> &rhs) const {
        return !(*this == rhs);
    }
};

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

  // Create an array
  Array<int, 5> myArray = {1, 2, 3, 4, 5};
  // On older compilers, use double braces:
  //    Array<int, 5> myArray = {{1, 2, 3, 4, 5}};

  // Iterate over the array
  for (int element : myArray)
    Serial.println(element);

  // Access elements of the array
  myArray[2] = 30;
  Serial.println(myArray[2]);
}

void loop() {}

```
> 4 votes

---
Tags: c++, array, stl
---


# Question
Title: UART communication - Serial is always empty
I have a payment terminal which uses UART (or simply speaking `Rx`, `Tx`, `Gnd` pins) and I have an `Android` tablet app which is connected to the terminal using `USB` to `DB9` adapter based on `PL2303` chip. The Android app works well and it uses https://github.com/felHR85/UsbSerial to support serial communication. The protocol is very simple, basically Android sends strings like "*REQINFO,4*", "*L2,xxx,xxx,*\*" etc. and recieves back a string statuses.

I'm trying to replace Android app with `Arduino UNO`, for which I naively assumed would be enough just to connect `Tx`,`Rx` of the terminal with `Rx`,`Tx` pins of the Arduino and also to connect `Gnd` pins. But I can't get it working. The only thing I noticed is when I connect Arduino `Rx` to terminal `Tx`, the terminal's screens briefly shows "Connecting..." but that's probably because it detects some incoming voltage. When it comes to reading `Serial` (or also I tried `SoftwareSerial`) nothing is ever returned.

```
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
    } else {
      data += c;
    }
  }
}

```

So do I miss anyting in order to have a proper communication? Thanks.

# Answer
Check (e.g. with a multimeter) the DB9 voltages! Mostly RS-232 is used on those kind of connectors with voltages +-12Volts (there are other variants as well, up to 15V), but your Arduino's UART uses TTL levels (0V as logic low or 5V as high on a 5V Arduino). You'll need to convert these, possibly with a chip like MAX232 or similar.

Also, for reverse engineering this I recommend using an Arduino with multiple serial ports (e.g. Mega), or at least multiple software serials (with proper level shifting of course). You connect your Android tablet to your reader through your Arduino, and when you receive a byte from one device, send it to the other one, and also send it to your PC along with the information about direction. This way you can understand all the used commands if you sniff long enough. You could also use an SD card on SPI if you need your sniffer system to be mobile (walking in a warehouse scanning items).

If you have access to a logic analyzer, it can also be used as a sniffer. This has an additional advantage, you can change BAUD rates later if your guess was wrong.

(started as a comment but ran out of characters, so I thought I'll explain it a bit more)

https://www.db9-pinout.com/db9-pinout/db9-pinout.gif

If it's a standard cable for RS-232, this diagram shows which pin is which. DCE-DCE and DCE-DTE cables were different back then (one connects a PC to a modem, the other 2 PCs), so you should check both voltages from 5 (GND) to either 2 or 3. An empty line has logic high, which is 5V in case it uses TTL, and -5 or lower (like -12 or -15) for RS-232.

Test different BAUD rates as well!
> 0 votes

# Answer
There is already an answer and comment about possible hardware / flow control issues, so this answer is only dealing with your Arduino sketch. Iv’e added a couple of print statements and the `FreeMemory` library to test your sketch.

```
#include <MemoryFree.h>
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    } else {
      data += c;
    }
  }
}

```

When I repeatedly enter the following text in the serial monitor "1234567890", here is the results of the print statements:

```
REQINFO,4
1234567890
freeMemory()=1770
1234567890
freeMemory()=1770
12345678901234567890
freeMemory()=1760
12345678901234567890
freeMemory()=1760
123456789012345678901234567890
freeMemory()=1750
123456789012345678901234567890
freeMemory()=1750
1234567890123456789012345678901234567890
freeMemory()=1740
1234567890123456789012345678901234567890
freeMemory()=1740
12345678901234567890123456789012345678901234567890

```

Every time you receive new data, it is appended to the `data` string, causing the string to grow and available memory to disappear. Using the `String` object should be avoided.

Here is a simple sketch that uses a `char` array as a buffer for the incoming data:

```
// Set the buffer size to accomodate the largest
// "chunk" of data you will be receiving.
const byte bufferSize = 64;
char inputBuffer[bufferSize + 1];

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

void loop(){
  if(Serial.available() > 0){
    Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    Serial.print("inputBuffer=");
    Serial.println(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}

```
> 1 votes

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


title: ADS1115, ACS712 and ESP8266

text:
# Question
Title: ADS1115, ACS712 and ESP8266
I have an ACS712 (5v sensor), an ADS1115 (5 or 3.3v) and an ESP8266 board (3.3v).

I know I can't directly use the ACS with the ESP without a voltage divider on the analog pin. So I figured I could run the ADS and the ACS off 5 volts as the ADS communicates over I2C. Does this cause any issues with the SDA/SCL lines on the ESP?

What is the correct way in going about this?

# Answer
The SDA line of of ADS1115 will use 3.3 V if you power it with 3.3 V, but then the maximum analog input voltage would be 3.6 V (VDD + 0.3 V).

The ACS712 has the middle value at 2,5 V so to read it you need the 5 V range and must power the ADS1115 from 5 V. Then the SDA line of esp8266 will be connected to 5 V logic level, but the esp8266 pins can handle 5 V TTL communication currents.

The SCL line is driven from master (esp8266) at 3.3 V and the ADS1115 is good with it.
> 2 votes

---
Tags: esp8266, current, adc
---


# Question
Title: Can I connect esp32 to a phone USB charger?
I have a USB charger. Is it ok to connect it as a power supply for esp32?

Edit: i have a dev board esp32

# Answer
In principle yes (see also comment in update).

The voltage is ok (5V), typically USB, and it doesn't differ from the output of a computer USB port.

The output current is max 2000 mA, so check if your project (ESP + related hardware powered by this USB), is not exceeding 2000 mA. The ESP needs much less than 2000 mA, so if you didn't have a lot of external components or motors than you will be safe.

**Update**

Important omment from Sim Sson: The bare esp32 is not 5V-tolerant, so using a usb-charger is only ok for esp modules that have a voltage regulator onboard.
> 5 votes

---
Tags: esp32
---


# Question
Title: Connecting Peltier module to Arduino Nano
I am a beginner to Arduino programming and started working on my first Arduino project recently to power a Peltier cooling pad. Below is the code I used and in the circuit, I connected the positive (red wire) end of the Peltier to D12 of Nano Arduino board and the negative end( black wire) to the negative end of the 6V battery. Then I powered the Arduino board by connecting Vin(Arduino) and battery(+) using a jumper wire. The GND pin of the Arduino was connected to the battery(-) using a jumper wire.

The Peltier is not working and it would be a great help if someone can help me to understand what I did wrong.

```
int p=12;

void setup() {
   pinMode(p,OUTPUT);
}

void loop() {
   digitalWrite(p,HIGH);
   delay(2000);
}

```

# Answer
> 0 votes
I prepared a little circuit that should help you safely connect the Peltier module to Arduino. It uses a single n-channel MOSFET and 1K resistor.

I couldn't find any Peltier in Tinkercad so instead I used a simple light bulb. (In previous version of this answer I used a DC motor, but it was not a good replacement for Peltier module)

When Arduino Pin12 is HIGH light is bright (high current flows through it just like it should through the Peltier) when Pin12 is LOW light bulb goes dark (no current is flowing)

---
Tags: arduino-nano, peltier
---


# Question
Title: LCD screen won't stop printing the same characters twice
I'm hoping that someone might be able to help me figure out how to prevent my LCD from giving me double digits (i.e. 55, 66, 77 - instead of 5,6,7);

I have 2 functions that are printing, so I'm expecting the issue to be related to this.

Here's the code:

```
#include <Wire.h>

#include <Adafruit_LiquidCrystal.h>
#include <Keypad.h>

unsigned int deBounce = 100;
int curs = 0;

Adafruit_LiquidCrystal lcd(8, 9, 3, 10, 11, 12, 13);

const byte numRows = 4; //number of rows on the keypad
const byte numCols = 4; //number of columns on the keypad

char keymap[numRows][numCols] =
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'.', '0', '#', 'D'}
};

char keymap2[numRows][numCols] =
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'.', '0', '#', 'D'}
};

//Code that shows the the keypad connections to the arduino terminals
byte rowPins[numRows] = {25, 27, 29, 31};
byte colPins[numCols] = {17, 19, 21, 23};

//initializes an instance of the Keypad class
Keypad myKeypad = Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);
Keypad myKeypad2 = Keypad(makeKeymap(keymap2), rowPins, colPins, numRows, numCols);

char enteredDigits[10]  = " ";//null terminated character array to hold entry
char enteredDigits2[10]  = " ";//null terminated character array to hold entry
boolean entryComplete = false;
boolean entryComplete2 = false;
boolean first = 0;

float result; // Create an integer for the result of 'A' and 'B' (in this case, it will be the 'Inductance' x 'Capacitance')
float power = .5; // Used in the equation
float r1; // Result 1
float r2; // Result 2
float r3; // Result 3
float r4; // Result 4
float fc; // Result 5
float power2 = 6; // Used in the last part of the equation
float result2 = 10; // Also used in the last part of the equation
#define TWO_PI 6.283185307179586476925286766559 // two Pi (:
float num1;
float num2;

void setup()
{
  myKeypad.setDebounceTime(deBounce);
  myKeypad2.setDebounceTime(deBounce);

  lcd.begin(16, 2);
}

void loop()
{
  getNumber();
  if (entryComplete)
  {
    entryComplete = false;
    lcd.setCursor(0, 1);
    num1 = atof(enteredDigits);
    first = 1;
  }

  if (first == 1) {
    getNumber2();
    if (entryComplete2)
    {
      entryComplete2 = false;
      lcd.setCursor(0, 1);
      num2 = atof(enteredDigits2);
      values();
      first = 0;
    }
  }
}

void getNumber()
{
  static byte index = 0;
  char key = myKeypad.getKey();
  if (key != NO_KEY)
  {
    switch (key)
    {
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9': case'.':
        lcd.print(key);//print entry on top row
        enteredDigits[index] = key;//build character string
        index++;
        enteredDigits[index] = '\0'; //null terminate
        break;

      case '#':
        lcd.setCursor(8, 0);
        lcd.print(F("= Ind."));
        delay(1000);
        entryComplete = true;
        index = 0;//reset for next entry
        break;

      case 'D'://clear entry and display
        memset(enteredDigits, '\0', 10); //clear buffer
        lcd.clear();
        index = 0;
        entryComplete = false;
        break;
    }
  }
}

void getNumber2()
{
  static byte index2 = 0;
  char key2 = myKeypad2.getKey();
  if (key2 != NO_KEY)
  {
    switch (key2)
    {
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9': case'.':
        lcd.print(key2);//print entry on top row
        enteredDigits2[index2] = key2;//build character string
        index2++;
        enteredDigits2[index2] = '\0'; //null terminate
        break;

      case '#':
        lcd.setCursor(8, 1);
        lcd.print(F("= Cap."));
        delay(1000);
        entryComplete2 = true;
        index2 = 0;//reset for next entry

        break;

      case 'D'://clear entry and display
        memset(enteredDigits2, '\0', 10); //clear buffer
        lcd.clear();
        index2 = 0;
        entryComplete2 = false;
        break;
    }
  }
}

void values() {

  result = num1 * num2; // If a 'comma' key is pressed (in this case, the # key on a 4x4 keypad)

  lcd.clear(); // Clear the writing from the LCD
  lcd.setCursor(0, 0); // Set the cursor position to the first block on the first line
  lcd.print(F("Ind. =")); // Display 'Ind. =' onto the LCD Screen
  lcd.setCursor(7, 0); // Set the cursor position to display after the previous text
  lcd.print(num1, 4); // Display the number value given to num1
  lcd.setCursor(0, 1); // Set the cursor for the first block on the second line
  lcd.print(F("Cap. ="));// Display 'Cap. =' onto the LCD Screen
  lcd.setCursor(7, 1); // Set the cursor position to display after the previoust text
  lcd.print(num2, 2); // Display the number value given to num2
  delay(2500);

  r1 = pow(result, power);
  r2 = r1 * TWO_PI;
  r3 = 1 / r2;
  r4 = pow(result2, power2);
  fc = r3 * r4;
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(F("Res. Peak =")); // Display the answer onto the LCD Screen
  lcd.setCursor(0, 1);
  lcd.print(fc);
  lcd.setCursor(9, 1);
  lcd.print(F("(Hz)"));
}

```

# Answer
I had to remove this line from the getNumber2 function!

lcd.print(key2);

works now (:
> 1 votes

# Answer
You need to break your code into parts and debug it part by part. Start by printing a single character to the LCD once, and setting a bool so you don't do it repeatedly. If that works, the LCD is not your problem.

As DataFiddler suggested, bounce problems with your switch seem like a likely culprit. Add serial print statements to your button handling code and see if it's being triggered more than once. If so, research debouncing code.
> 0 votes

---
Tags: lcd, switch, keypad
---


title: Brownout detector triggered

text:
# Question
Title: Brownout detector triggered
I'm running a pretty basic setup. When I run a small program just doing some `serial.println`, it works fine, when I try to do operations that needs more power, the brownout detector gets triggered. I'm running my chip on an ok buff power supply so I don't get what the problem is.

# Answer
> 1 votes
The ESP typically runs on 3.3 Volt, not 3.0 Volt.

Secondly, it looks like the board has a voltage regulator, all power goes through the voltage regulator. If that's the case the voltage you need to supply must be lower that the drop-out voltage of the regulator (which is typically around a volt).

---
Tags: esp8266, arduino-ide, esp32, electronics
---


# Question
Title: Burning servos like crazy, what am I doing wrong?
For some reason my servos keep burning out.

My code is simple, if condition, rotate to 0 degrees, else rotate to 180.

However, what that does to the motor is keep it in a constant struggle to stay in rotation 0 or 180, when there is no movement in between. Sure enough, leave it running for 1 hour, the motor burns out.

```
if (!strcmp("1",output)){
    myservo.write(0);
}
else {
    myservo.write(180);
}

```

Is there something like myservo.release or something? I presuming i need to get the servo in to position, then release it so it doesnt try to stay in position.

Please help, i've burned through 4-5 of them so far, it's not fun :(

# Answer
Some servos are actually not able to do full 0..180 rotation - or to rephrase it better, the standard 0.5ms and 1.5ms pulse will force them to a position which can not be reached. Therefore the motor keeps on rotating in a constant struggle.

* change 0 to something like 20, and 180 to something like 150
* check that the motor has stopped once reaching 20 or 150. I.e. it does not produce any sound, and if you touch the motor body it is not producing any vibration (so no constant stuggle)
> 5 votes

# Answer
Ensure your voltage source matches the motors specs and that your wiring to the arduino or driver shield is correct and try the code I've posted which has worked for me to test servos.

```
#include <Servo.h>  // servo library
// You can control a maximum of twelve servos on the Uno
// using this library. (Other servo libraries may let you
// control more). Note that this library disables PWM on
// pins 9 and 10!

Servo servo1;  // servo control object

void setup()
{
  //  Attach the servo1 object to digital pin 4.
  servo1.attach(4);
}

void loop()
{
  int position;
  // Change position at full speed:

  servo1.write(90);    // Tell servo to go to 90 degrees
  delay(1000);         // Pause to get it time to move
  servo1.write(180);   // Tell servo to go to 180 degrees
  delay(1000);         // Pause to get it time to move
  servo1.write(0);     // Tell servo to go to 0 degrees
  delay(1000);         // Pause to get it time to move

  // Change position at a slower speed:
  // Tell servo to go to 180 degrees, stepping by two degrees

  for(position = 0; position < 180; position += 2)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }

  // Tell servo to go to 0 degrees, stepping by one degree

  for(position = 180; position >= 0; position -= 1)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }
}

```
> 2 votes

# Answer
I wanted to answer my own question: I had purchased some really cheap servos from AliExpress. These are not good. They burn out really fast, which has been confirmed by some friends of mine that had purchased the same servos. The voltage was correct, it was 5V. When using more quality servos that cost $15 I did not see any of these issues. Do your self a favor. Do not get servos from AliExpress. Get them from DFRobot or some other more reputable website.
> 1 votes

---
Tags: servo
---


title: Have I fried my arduino uno?

text:
# Question
Title: Have I fried my arduino uno?
I made a smart dustbin using arduino, servo motor, & ultrasonic sensor. It worked pretty well for a few number of days. But once I don't know how but the Arduino 'ON' light started to become dim and switched off. I used a 9V HW battery. So I decided to plug in my arduino with a 7V AC charger, still no luck, the arduino did not turn on nor the ON light. Then I plugged the arduino to my PC, the ON light turned on for 2 to 4 seconds and switched off. I realized it became too when I touched the usb port. The ATMEGA chip did not become hot. Please help?

# Answer
> 0 votes
If the USB chip is hot, you are out of luck.

---
Tags: programming, motor, servo, voltage
---


# Question
Title: Extending pulses of a square wave signal
My idea is to modify a diesel injection system to increase the fueling into the engine.

The signal to an injector is a series of 0.1-1.5ms pulses. I would like to analyse the pulses and then send out my own pulse to extend some of the injection pulses. I want to do this all in real time.

Is this possible on an arduino? I have never used one before so I'd like to know if it is possible and what product would be suitable.

# Answer
Yes, assuming the calculations are not that time consuming.

The Arduino is 16 MHz, so this is in the us scale which is way within limits. I don't know how critical the rise and fall times are, but even that should be possible.

You need some additional circuitry though, because the Arduino itself cannot handle 12V signals. For the input, you need so called level shifting (from 12 V to 5 V), see A-Quick-Guide-on-Logic-Level-Shifting for more explanation.

For the output, you need a 12 V signal (or use a voltage booster to 12V), and a transistor (and probably some resistors) that is connected to the Arduino for the signal and to the 12V and the diesel injection system for the 12V.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Monitoring Power Down Using Arduino UNO and ZMPT101B
I am in the process of implementing power down alerting system suing Arduino UNO and ZMPT101B Single phase relay.

My code as follows,

```
#include <Filters.h> //Easy library to do the calculations

float testFrequency = 50;                     // test signal frequency (Hz)
float windowLength = 40.0/testFrequency;     // how long to average the signal, for statistist

int Sensor = 0; //Sensor analog input, here it's A0

float intercept = -0.04; // to be adjusted based on calibration testing
float slope = 0.0405; // to be adjusted based on calibration testing
float current_Volts; // Voltage

unsigned long printPeriod = 1000; //Refresh rate
unsigned long previousMillis = 0;

void setup() {
    Serial.begin( 9600 );    // start the serial port
}

void loop() {

    RunningStatistics inputStats;                //Easy life lines, actual calculation of the RMS requires a load of coding
    inputStats.setWindowSecs( windowLength );

    while( true ) {
        Sensor = analogRead(A0);  // read the analog in value:
        inputStats.input(Sensor);  // log to Stats function

        if((unsigned long)(millis() - previousMillis) >= printPeriod) {
            previousMillis = millis();   // update time every second

            Serial.print( "\n" );

            current_Volts = intercept + slope * inputStats.sigma(); //Calibartions for offset and amplitude
            current_Volts= current_Volts*(40.3231);                //Further calibrations for the amplitude

            Serial.print( "\tVoltage: " );
            Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

            if (current_Volts <229) {
                test_loop();
            }
        }
    }
}

void test_loop(){
    Serial.print( "Warning!! Server Room Power Down" );
    delay(1000);
}

```

I am getting the correct voltage reading. When power down it says power down. But when power got up, it still shows power down with older reading. I think the reason for this because my code unable to stop the loop. And if I remove the delay (1000) in test\_loop function it works, But my intention to use this sms alerting system and for that I need this delay to stop unnecessary alerts.

My code for SMS Alerting,

```
Serial.print( "\tVoltage: " );
Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

if (current_Volts <229) {
    SendMessage();
}

void test_loop() {
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
    delay(1000);  // Delay of 1000 milli seconds or 1 second
    mySerial.println("AT+CMGS=\"xxxxxxxxx\"\r"); // Replace x with mobile number
    delay(1000);
    mySerial.println("Warning!! Server Room Power Down");
    delay(100);
    mySerial.println((char)26);// ASCII code of CTRL+Z
    delay(150000);
    mySerial.println("AT+CMGD=2");
}

```

This code works for the very first outage but after power up also it send power down. First part of serial priniting in test\_loop code of Serial.print is used for debugging.

# Answer
> 1 votes
Got a answer for the issue,

Attaching code for anyone interested.

```
/*
   Design by Vinod Amarathunga 26.08.2018
   FSSG R&D Team
*/

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SoftwareSerial.h>
#define ONE_WIRE_BUS 2
SoftwareSerial mySerial(11, 10); //SIM800L Rx Tx
char msg;
String textMessage;

bool D7_alarmSent = false;
bool Temp_alarmSent = false;

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void PowerSMS()
{
  Serial.println("Warning!! Server Room Power Down");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void SendMessage()
{

  Serial.println("Warning!! Server Room Temperature is Critical");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void loop()
{
  sensors.requestTemperatures(); // Send the command to get temperature readings
  delay(1000);
  Serial.println(String("Temp Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  Serial.println(String("Voltage Digital: ") + digitalRead(7));
  Serial.println(Temp_alarmSent ? "True" : "False" );
  Serial.println(D7_alarmSent ? "True" : "False" );
  Serial.println("***********");
  ReceiveMessage();

  if (digitalRead(7) == 1 || sensors.getTempCByIndex(0) > 29 || D7_alarmSent == true || Temp_alarmSent == true ) {
    if (digitalRead(7) == 1 ) {
      if (!D7_alarmSent) {
        D7_alarmSent = true;
        PowerSMS();
      }

    }

    else if (sensors.getTempCByIndex(0) > 29 ) {
      if (!Temp_alarmSent) {
        Temp_alarmSent = true;
        SendMessage();
      }

    }

    else {

      if (D7_alarmSent){                  //alarmSent == true means that previous state was "Power Down"
          SendMessage_After_Power_Down();          //Send message
          D7_alarmSent = false;
          Temp_alarmSent = false;             //Reset alarmstate
        }

    }
  }

}

void SendMessage_Normal()
{
  Serial.println("Temperature and Power is OK");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

}
void SendMessage_After_Power_Down(){

  Serial.println("Power Back Online");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  }

void ReceiveMessage()
{
  if (mySerial.available() > 0)
  {
    mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
    delay(1000);
    textMessage = mySerial.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if (textMessage.indexOf("Status") >= 0) {
    SendMessage_Normal();
    mySerial.println("AT+CMGD=2");

  }
}

```

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


title: About boot-loader ic used in DEV boards

text:
# Question
Title: About boot-loader ic used in DEV boards
I have problem with Arduino MEGA, Arduino Deu etc... Those Development board are having separate MCU except main MCU... Why? For what purpose are they used for?

as FTDI or bootloader chip or protection for main MCU or what other purpose?

I don't have an idea about that?

what are they called?

Please any one clarify me this?

# Answer
> 0 votes
There are two different reasons for a second MCU on a development board.

1) If the main MCU has a bootloader for serial upload, but doesn't include USB peripheral and the dev board should have for convenient development an USB port, then the board must include a USB-to-TTL-Serial adapter ('FTDI'). The adapter can be an FTDI USB chip, some other manufacturers USB chip (most common is CH340) or an MCU (with a USB peripheral) programed as USB-to-TTL-Serial with a firmware. Original Arduinos use ATmega 8u2 or 16u2 for this.

2) Some dev boards include a programmer for upload without bootloader. The programmer is a second MCU running a programmer firmware and is wired to programming pins of the main MCU. For example Arduino Zero, M0 Pro or Uno WiFi Rev 2, Nano Every have this concept.

---
Tags: usb, electronics, ftdi
---


title: Control 5V from ESP8266 Wemos D1 mini

text:
# Question
Title: Control 5V from ESP8266 Wemos D1 mini
I am making a simple heater with the help of ESP8266 wemos d1 mini. Heaters will use 12V DC power suply and ESP8266 must turn the heater on and off with the help of 5V DC relax. I want to avoid the use of anything else then ESP8366 and relay. I will need 2 such relays. So the question is, can i control 5V output on ESP8266 ? Or do i need to find a 3V DC relay and use that ? If the latter is the case, can i get some ebay link to 3V DC relay ?

# Answer
Voltage is only part of what a relay uses. Check the current requirements for the relay coil/input as well.

For example the common result for "3V relay arduino" will produce results for relay MODULEs that contain something akin to a SRD-03VDC-SL-C relay (labeled on the relay itself). Spec for the RELAY (separate search by relay part no) yields a data sheet that says the coil resistance is 25 ohms for a 3V and would use 120 mA at that voltage (25 Ohm * .120A = 3). Note if the same coil were run on 5V it would draw 200 mA (25 Ohm * .200A = 5V).

120 mA is bloody high to be coming from a logic pin which is why the MODULE has more than just the relay. What the MODULE likely contains is an additional gate device that takes less current that then supplies the relay (with 120mA) from another port.

You might also be looking at a solid state relay that uses less input current but generally has some slight leakage when "Off"
> 1 votes

# Answer
Do *NOT* try to drive a simple relay from an MMU like a ESP8266, Arduino, or Pi. That would likely destroy the digital pin on the MMU, and might destroy the whole processor.

You want a "digital relay module" which has a driver circuit to control the relay, plus some form of isolation to protect the digital pins.

A relay like this would be perfect: https://www.amazon.com/Icstation-3-3V-Optocoupler-Trigger-Development/dp/B01300ZY5M

Note that those come in 1, 2, 4, and 8 channel modules. Such a relay needs an external power supply, and your ESP8266 may or may not be able to provide enough current for the relay from its voltage regulator. Check the current requirements on the relay and the output specs on the ESP8266's voltage regulator.
> 0 votes

---
Tags: esp8266, relay
---


# Question
Title: How can I receive signal from remote control using tcrt5000 sensor module
how can I use tcrt5000 sensor module instead of TSOP31238 (TSOP1738) IR receiver to get signal from remote control? I want to create remote control for my PC to navigate through my slide shows. Thanks in advance.

# Answer
> 0 votes
The TCRT5000 and the TSOP31238 are very different. The TCRT5000 is actually a reflective distance sensor. It has an IR LED and a simple IR phototransistor, not more. The TSOP31238 in contrast is meant to receive data from IR remotes. IR remotes work with modulation of IR light. The IR LED is pulsed with a frequency of 38kHz (in the case of the TSOP31238). This frequency is modulated with the actual data, meaning there are different time lengths were there is no IR signal and where there is a 38kHz IR signal.

The TSOP31238 detects the IR light with a phototransistor, like the TCRT5000 has. But then the signal is processed with an amplifier, a band pass to filter out all frequencies but the 38kHz and then demodulated, so that you don't see the 38kHz signal on the output, but only the pulse lengths.

The demodulation should actually be the least complex part to build yourself. That can be even done by code. But to get good results, you also need the other parts. You would have to build an amplifier circuit with an opamp. And would have to build the bandpass (for example with an LC element).

You can build these things yourself, **but:** The sensor, that you have, is not meant for receiving IR remote signals. The parts, that you would need to make the signal usable, will cost way more, than just buying a TSOP. Also it will be a lot easier and most likely better working (processing the signal from a phototransistor can be tedious). I suggest, that you buy a TSOP chip fitting to your remote control.

---
Tags: sensors, arduino-pro-mini, ir
---


# Question
Title: difference between the nano and the nano every
So I wondered what the difference between the nano and the nano every is and why the nano every is so much cheaper than the nano.

I'm new to the microcontroller business and I would like to know what would be better for what situation.

# Answer
> 5 votes
The classic Nano has ATmega 328p MCU, same as Uno. The 328p is classic AVR ATmega as used in Arduinos from the start and before in many AVR MCU projects for over 20 years now. There is large knowlege base for this MCUs, many ready codes in form of libraries, snippets, tutorials.

The Nano Every and Uno WiFi Rev 2 use a modern version of the AVR based MCU a so called megaAVR\_0-series, an ATmega4809. It uses the same AVR CPU architecture in core of the MCU so the compiler is the same as for 328p and co., but the MCU peripherals configuration is very different then in the classic ATmegas. So the old knowledge base about AVR MCU peripherals doesn't help here.

The lower price is not related to manufacturing costs. The possible reasons are:

1. better price by MCU manufacturer at introduction of the new MCU family to market
2. higher price of classic Nano because it is popular and together with classic Uno founds Arduino as company
3. getting the new chip to Arduino power users to build up the knowledge and code base for the new MCU

To mention some more differences of classic Nano and Nano Every: Nano uses a bootloader for sketch upload and an external USB chip for USB communication. Nano Every doesn't use a bootloader, it has an on board UPDI programmer in form of a small SAMD MCU which serves as USB adapter for serial communication too.

---
Tags: arduino-nano
---


title: how to convert date to timestamp?

text:
# Question
Title: how to convert date to timestamp?
How should I convert date format(dd-mm-yyyy) to timestamp value . Can anyone suggest code how to convert and where to put code .

# Answer
It is good for you?

```
struct tm tm;
time_t fecha;
if ( strptime(timestamp, "%Y-%m-%d %H:%M:%S", &tm) != NULL )
  fecha = mktime(&tm);
else

// Another thing

```
> 0 votes

---
Tags: web-server, time
---


# Question
Title: Mapping values from analog input giving unexpected values?
Mega 2560

I am reading in values from 3 pots then mapping them to values between 0 - 255

```
#define REDPIN   7
#define GREENPIN 8
#define BLUEPIN  9

int red_pot   = A0;  // analog pin used to connect the potentiometer
int green_pot = A1;
int blue_pot  = A3;

void setup() {

  pinMode(REDPIN,   OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN,  OUTPUT);

  Serial.begin(38400); //Debug port
  Serial.setTimeout(50);
}

void loop() {

  int red, green, blue;

  red   = analogRead(red_pot);
  green = analogRead(green_pot);
  blue  = analogRead(blue_pot);

  Serial.print(" r = ");
  Serial.print(red);

  Serial.print(" b = ");
  Serial.print(blue);

  Serial.print(" g = ");
  Serial.print(green);
  Serial.print("\n\n\n");

  // map values
  red   = map(red,   20, 650, 0, 255);
  green = map(green, 20, 570, 0, 255);
  blue  = map(blue,  20, 570, 0, 255);

  Serial.print("red map : ");
  Serial.print(red);

  Serial.print(" green map : ");
  Serial.print(green);

  Serial.print(" blue map : ");
  Serial.print(blue);
  Serial.print('\n\n\n');

  analogWrite(REDPIN,   red);
  analogWrite(GREENPIN, green);
  analogWrite(BLUEPIN,  blue);
}

```

`red` & `green` behave as expected but `blue` is not, from the serial monitor...

When blue is at its lowest value,

When blue is at its highest value,

I have changed `blue`'s analog pin assignment but the same issue.

Any clues what's happening?

**EDIT #1**

I thought it might be some `int` sign error so I changed the `map` operation to,

```
blue  = map(abs(blue), 20, 670, 0, 255);

```

It made no difference.

# Answer
> 1 votes
Note that the Arduino function "map" is really this:

```
long map(long x, long in_min, long in_max, long out_min, long out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

```

...so, if you pass a "minimum from" value which is less than the actual value you are mapping from you will get a negative number given your "minimum out" is zero.

In several of your examples you have set the minimum to 20 but pass a value of 19. If your program is intolerant of negative numbers (for instance, how would a negative number effect the PWM hardware), consider testing for lower than minimum and higher than maximum values before using the map function.

---
Tags: arduino-mega, analogread, map
---


# Question
Title: How much current needed to power arduino uno?
I am planning to build an rc car based on arduino uno. I will use 3S 11.1 V Li-po to power whole circuitry. So my question is;

First, can arduino be powered directly with 11.1V from its Vin pin? Would it be a problem or not? If it is OK, then no need to answer the bold part below.

**If it is not, then one solution comes to my mind is to use a voltage regulator which will convert 11.1 V to 5 V. But while choosing a regulator, I saw that max output current is one of the important specs. So what is the minimum amount of current needed to run Arduino UNO?**

# Answer
The maximum voltage at the Vin pin is 12V, so using your battery is fine!

Considering the current consumption: The arduino itself will usually source less than 200mA, but your whole setup will probably sink more than that.
> 1 votes

---
Tags: arduino-uno, voltage
---


title: 3v to 3.5v step up?

text:
# Question
Title: 3v to 3.5v step up?
I would like to run my esp32 on coin cell batteries, tho it needs at minimum 3v, that means if there just is too much resistance in the vires or anything else, stuff like Bluetooth will make it brownout,

So what is the best way to step up 3v to 3.5v?

# Answer
> 0 votes
To be honest you are better off stepping *down* rather than stepping *up*. Simply because step down converters tend to be a higher efficiency and can deliver more current than a step up converter.

With step up converters you effectively convert current into voltage. With step down it's the other way around - voltage into current. Since button cells have very very little current capacity stepping up will reduce it even more and starve the ESP32 of power. By stepping down you increase the current.

Two 3V button cells in series will provide nominal 6V and about 40mA current. By adding a step down converter to 3.3V you are almost halving the voltage, but at the same time almost doubling the current. Adding a third cell in series will give you even more current output.

It is possible to get some incredibly tiny and high efficiency step-down modules. I myself make and sell one based around the TPS82130SILT which has the ability to run at as low as 3.7V with a 3.3V output (it has a "pass through" mode which allows a zero dropout voltage, but I include a protection diode with 0.4v drop). That means you get the entire 6V to 3.7V range out of your batteries before the voltage starts to droop (assuming the batteries still operate at 1.85V).

# Answer
> 0 votes
Generally, to step up voltages you can use a boost converter. But I doubt that using coin cells to supply an esp32 is a good idea, because they probably won't last very long and are relatively expensive. Even if you use sleep modes, the voltage margin will be small (of course, that depends on the boost converter).

# Answer
> 0 votes
Why not use *three* button cells and a buck converter to lower the voltage from 4.5V down to 3V?

---
Tags: voltage-level, esp32, electronics
---


# Question
Title: pin going high not allowing analog read to change
I have the following problem:

My arduino takes analogRead(A0) from a potentiometer whose position I can't adjust directly.

When analogRead(AO) goes to a value X, I want pin 8 to go HIGH, this causes the circuit to open. and stop A0 getting higher . so I do an if statement:

```
if(analogRead(AO)> X) {

digitalWrite(pin, HIGH)  \\opens the circuit}

else {
digitalWrite(pin, LOW)  \close the circuit
 }

```

The issue I have here, is when then circuit is open, I would like to change the value of the potentiometer (A0) which is controlled by a motor which is also in the circuit: but doesnt depend on the arduino board. Given I can't control A(0) then the circuit will remain on A(0) \>X forever.

The system going to LOW pin or close circuit, after it reaches HIGH pin for 2 seconds would be great, but then the program goes to the beginning and realizes that still A(0)\> X , and goes back to a open circuit state, therefore not allowing me to have the close circuit anymore in order to make A(0) \< X and leave the circuit closed . Maybe something that cyclically turns pin on an off for t mseconds? but this is not ideal as it would cause high wear on the system

Edited the post to be more precise. I hope now its clearer
thanks

---

thank you for your answers, but after playing for a while with your codes, and the ideas behind it, still cannot get it to work.

for instance, Chrisl with your first:

when potentiometer is at \> X, It cuts the circuit which is good, but still doesn't go off until both potentiometer goes to \< X and 3 seconds lapse , but this is not going to be possible to achieve anyways because the value of the potentiometer is fixed on X

THis is what Id need-

if (PinState == HIGH)

after 3 seconds go low,

and not turn HIGH until at least these two conditions are met; analogRead has gone to \< X and then analogRead \> X ,and in that moment we are back at
PinState HIGH is even possible to achieve something like this?

the circuit is something like this:

simulate this circuit – Schematic created using CircuitLab

UPDATE: I have using this code, which does almost what I want: if(analogRead(A0) \> X) { unsigned long currentMillis = millis();

```
if ((unsigned long)(currentMillis - previousMillis) >= interval) {

   pinState = !pinState;
   digitalWrite(pin, pinState)
   // save the "current" time
   previousMillis = millis();
}}

```

When it gets to analogRead(A0)\> X the problem of this code is that it switches the pin On and OFF continuosly,

but instead of switching it off/on after the interval time , I want it to be LOW always. Of course as long as time is more than interval,and not get to a HIGH, until It has gone back to analogRead(A0)\> X and time is less than interval. And repeat the process... When time is more than interval it will go from where it was digitalWrite(pin, HIGH) to the new state digitalWrite(pin, LOW)

I made this table to be more clear

Table: analogRead(A0) \> X?

1-yes --\>now check if time in this state is less than interval = 3000:

1.1-YES, ---\> digitalWrite(pin, HIGH)
1.2- if no ( time is more than interval ) ---\> digitalWrite(pin, LOW)

2- No, analogRead(A0) \< X . So --\> keep digitalWrite(pin, LOW)

*NEW UPDATE:*

The state diagram for the new ranges should be something like this. I hope it is clear. I also removed the delays and replaced (V \< X ) for (V \< Y ) , it works great. Thank you Edgar.

Z in the diagram being the variable for the new range, Z \<\< X

**LAST UPDATE:**

Question Solved by Edgar Bonet

# Answer
> 0 votes
The description you give for the desired behavior is very unclear and hard to follow. I am going to rephrase what I think I understood in terms of a finite state machine, which is the correct way of describing this kind of systems. Please, review the description below, as chances are I did not completely understand what you really want.

Let's say the system can be in any of these three states:

* In the `V_LOW` state, the input voltage is below the threshold `X` and the output is `LOW`. If the input raises above `X`, we set the output to `HIGH` and transition to the `V_HIGH` state.
* In the `V_HIGH` state, the input is above the threshold X and the output is `HIGH`. If the input falls below `X` we go back to the `V_LOW` state. If we remain in `V_HIGH` for three seconds, we switch the output to `LOW` and go to the `TIMEOUT` state.
* In the `TIMEOUT` state, the input is above the threshold, yet the output is `LOW`. When the input falls below `X` we go to the `V_LOW` state.

Below is a state graph for this machine. The states with a gray background have the output `LOW`, whereas the state with a white background has the output `HIGH`. Each possible transition is drawn as an arrow, labeled by the condition that triggers the transition:

Is this the behavior you have in mind? If no, try to describe the behavior you want in terms of a finite state machine, as I have done here. If yes, then I suggest you follow chrisl's advice and implement some hysteresis, by having different thresholds for going into and out of `V_LOW`.

Anyhow, below is a translation of the FSM above in C++. It may not be the most efficient way to write it, but I believe it is straightforward enough to not require any additional explanation:

```
void update_output()
{
    static enum { V_LOW, V_HIGH, TIMEOUT } state;
    static uint32_t time_entered_v_high;
    int V = analogRead(A0);

    switch (state) {
    case V_LOW:
        if (V >= X) {
            digitalWrite(pin, HIGH);
            state = V_HIGH;
            time_entered_v_high = millis();
        }
        break;
    case V_HIGH:
        if (V < X) {
            digitalWrite(pin, LOW);
            state = V_LOW;
        } else if (millis() - time_entered_v_high >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V < X) {
            state = V_LOW;
        }
        break;
    }
}

```

---

**Edit 1**: Here is how to implement the hysteresis: you need to choose a second, lower threshold, for going back to the state `V_LOW`. Let's call it `Y`, which is smaller than `X`. Then, both on the diagram and the code, replace every instance of “V \< X” by “V \< Y”. That's it. There is absolutely *nothing* more to change.

---

**Edit 2**: Addressing the updated question. Now the output should go `HIGH` when the input is out of a defined range. I'll add hysteresis right away by using *four* thresholds V0 \< V1 \< V2 \< V3:

* the input is *in range* if it is within \[V1, V2)
* the input is *out of range* if it is *not* within \[V0, V3)
* the ranges \[V0, V1) and \[V2, V3) provide hysteresis.

Note that for consistency I like to have all the intervals closed on the same side. I will also rename the states `V_LOW` and `V_HIGH` to `IN_RANGE` and `OUT_OF_RANGE` respectively. Here is the updated code:

```
void update_output()
{
    static enum { IN_RANGE, OUT_OF_RANGE, TIMEOUT } state;
    static uint32_t time_exited_range;
    int V = analogRead(A0);

    switch (state) {
    case IN_RANGE:
        if (V < V0 || V >= V3) {
            digitalWrite(pin, HIGH);
            state = OUT_OF_RANGE;
            time_exited_range = millis();
        }
        break;
    case OUT_OF_RANGE:
        if (V >= V1 && V < V2) {
            digitalWrite(pin, LOW);
            state = IN_RANGE;
        } else if (millis() - time_exited_range >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V >= V1 && V < V2) {
            state = IN_RANGE;
        }
        break;
    }
}

```

# Answer
> 0 votes
Using different threshold values to switch states - a higher threshold to go HIGH and a lower value to go LOW - is called hysteresis. It makes a dead-zone between the two switching values that prevents jitter, or flickering the LED in this case, that would happen with a single switch-point and the analog value was very close to it.

To do that, you just need the second clause of your `if` block, now an `else`, to become an `else if`. So it would look like this (in pseudo-code):

```
if analog > 5,
   open the circuit;
else if analog < 4
   close the circuit;
// else must be >4 but <5, so do nothing.

```

> for 3 seconds I make circuit close ... when the system goes more than X again, it does the IF..else statement again

Update:

So instead of hysteresis, you want close the circuit for a fixed amount of time? Then try something more like this:

```
if millis() - stop_time > 0 && analog > 5,
   save stop_time = (millis()+3000);
   open the circuit;
end

```

# Answer
> 0 votes
As I wrote in my comment, you can use `millis()` to solve your problem. First you should ditch the `else` statement, since you don't want the analog signal to turn the output of.

```
unsigned long timestamp=0;
unsigned long interval = 3000;

void loop(){
    if(millis() - timestamp > interval){
        digitalWrite(pin, LOW);
        if(analogRead(A0) > X){
            timestamp = millis();
            digitalWrite(pin, HIGH);
        }
    }
}

```

This code will check, if the time difference between now and the last activation is over 3s. If yes, it will first set the output to LOW. Then it checks, if the analog input is above X. If yes, the output will be set to HIGH and the timestamp will be set to the current time. On the next loop iteration the time difference will be lower than 3s (since we just set the timestamp to now). Thus nothing will change, keeping the output to HIGH for 3s. After that the output will be set to LOW and the code will be sensible to A0 again.

If you the output to just trigger once ever, you can use a simple flag.

```
unsigned long timestamp=0;
unsigned long interval = 3000;
byte flag=1;

void loop(){
    if(millis() - timestamp > interval){
        digitalWrite(pin, LOW);
        if(flag && analogRead(A0) > X){
            timestamp = millis();
            flag = 0;
            digitalWrite(pin, HIGH);
        }
    }
}

```

The flag is initially set to 1, which actives the `analogRead()` part. Then it is set to zero, which deactivates it.

Note that this code is relatively simply and comes with some caveats, that might or might not matter to you:

* The code will not react to changes in the first 3 seconds after startup, since the timestamp is set to zero initially.
* After about 50 days runtime, the `millis()` counter will overflow. So, if the inner if statement doesn't get triggered for this long, the code will again not be able to react for 3s (until the time has run 3s after the timestamp).

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


# Question
Title: How to send keystroke with shift modifier?
This is a bit of a newbie question, but here it goes anyway. So basically I want to send a keystroke using the DigiKeyboard library, but with shift held down. I looked through the code and saw this comment in scancode-ascii-table.h:

```
//Format: most signifficant bit indicates if scan code should be sent with shift modifier
remaining 7 bits are to be used as scan code number.

```

I dont really understand where to specify this, whether it's when you call the sendKeyStroke function, or somewhere in the code. Help appreciated.

# Answer
> 0 votes
I never used this library, but in the header file there are this constants for modifiers:

```
#define MOD_CONTROL_LEFT    (1<<0)
#define MOD_SHIFT_LEFT      (1<<1)
#define MOD_ALT_LEFT        (1<<2)
#define MOD_GUI_LEFT        (1<<3)
#define MOD_CONTROL_RIGHT   (1<<4)
#define MOD_SHIFT_RIGHT     (1<<5)
#define MOD_ALT_RIGHT       (1<<6)
#define MOD_GUI_RIGHT       (1<<7)

```

and a function

```
void sendKeyStroke(byte keyStroke, byte modifiers)

```

so I would use this to send a key with Shift like this

```
sendKeyStroke(KEY_F2, MOD_SHIFT_LEFT);

```

---
Tags: digispark
---


# Question
Title: SIM900/Arduino UNO R3 serial communication not working
For some reason I cannot establish serial connection between the two devices. The shield is connected to the network because my number can be called, but I cannot send it any commands via the serial. I tried several ways to wire it up: shield rx&tx (the ones that require female jumper) to 7 & 8 of arduino, declaring 7 & 8 in the serial. shield pins 7 & 8 (they have (serial) as label) to 7 & 8 of arduino, declarting 7 & 8 in the serial. shield rx&tx the little holes to 7 & 8 of arduino, declaring 7 & 8 in the serial. Tried even different pins other than 7 & 8. None worked. I'm powering the shield with 12v transformator that can provide up to 3Ah and the arduino is connected to laptop. Any suggestions ? Here's the code:

```
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

```

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

# Answer
> 1 votes
To make everything work fine with this exact code and wiring from the *lastminuteengineers*, you need to change the jumper (black plastic piece) position in J11. it has to connect the pins **D8(RX)** and **D7(TX)**, which are the pins at the top of the **yellow plate**, to the two pins in the middle of the **yellow plate**.

# Answer
> 0 votes
> And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

There aren't. There is only one of each. They just have them in multiple convenient places.

J11 selects the pins to use on the shield. Make sure that is set to D7 and D8. You then use pins D7 and D8 on the shield. Normally that would be mounted directly onto an Arduino and you would just use those pins in your code.

However, if you want to attach it to something that doesn't have an Arduino UNO footprint you can solder wires to the TX/RX pins in the J10/J17 "UART" header. That ignores the J11 jumpers, which only pertain to using the Arduino UNO shield headers.

As to why you can't communicate, my guess is:

* You have 9600 baud in your code:

---

```
mySerial.begin(9600);

```

However, on the Amazon product you linked to:

> The factory default setting for the GPRS Shield UART is 19200 bps 8-N-1. (Can be changed using AT commands).

Using 19200 instead of 9600 should improve matters somewhat.

---
Tags: arduino-uno
---


title: Arduino 10bit ADC is not accurate?

text:
# Question
Title: Arduino 10bit ADC is not accurate?
I'm reading the voltage with voltage divider:

simulate this circuit – Schematic created using CircuitLab  | *Arduino is connected to both USB and a 9V adapter.*

```
float r1 = 100000;
float r2 = 9980;
float adc, voltage, analog;
void setup() {
  Serial.begin(9600);
  analogReference(EXTERNAL);
  pinMode(A0, INPUT);
}

void loop() {
  for (int i = 0; i < 256; ++i) {
    analog += analogRead(A0);
  }
  analog = analog / 256;
  adc = analog * 1.228 / 1023;
  voltage = adc / (r2 / (r1 + r2));
  Serial.print(analogRead(A0));
  Serial.print(", ");
  Serial.print(analog);
  Serial.print(", ");
  Serial.print(adc);
  Serial.print(", ");
  Serial.print(voltage);
  Serial.println(" ");
  delay(100);
}

```

Here's the accuracy test result:

```
Input | Arduino | Difference
 1V      0.89V     -110mV
 2V      1.90V     -100mV
 3V      2.92V     -80mV
 4V      3.93V     -70mV
 5V      4.95V     -50mV
 6V      5.97V     -30mV
 7V      6.98V     -20mV
 8V      8.00      0
 9V      9.01      +10mV
 10V     10.02     +20mV
 11V     11.04     +40mV
 12V     12.06     +60mV

```

*The input voltages measured by DMM and was spot on voltage, like 1.000V.*

I didn't test voltages above 12V but it seems the difference is gonna increase by 20mV with each 1V increase, that means at 50V voltage reading is gonna be off by ~1V!

Even with 10bit resolution of Arduino I should have had steady accuracy with some percentage of difference(right?), but as you can see the result shows that the reading is not steady at all!

Why the voltage difference decrease/increase when voltage changes at the input?

# Answer
As stated by Majenko, the ADC can *in principle* have all sorts of errors. However, if you look at your data, you should notice that the error is essentially linear with the voltage. This means that the non-linearity error is quite small, and you are mainly seeing the offset and gain errors. This is fortunate, because these errors are easy to remove, given good calibration data.

The table you wrote in in your question happens to be a perfectly good calibration table. By fitting a straight line to it you can get a calibration function, and then correct the readings simply by adding this to your code:

```
voltage = 0.9848815 * voltage + 0.125354;

```

Or you could instead figure out the correction at the ADC level and replace

```
adc = analog * 1.228 / 1023;

```

by

```
adc = (analog + offset) / scale;

```

where `offset` and `scale` are computed from the calibration.

---

**Edit**: Here is how I extracted the calibration coefficients from the data.

First, I saved the data in a text file calibration.tsv and cleaned it up to remove the units and add a comment marker (#) in front of the column labels:

```
#Input | Arduino | Difference
 1      0.89     -110e-3
 2      1.90     -100e-3
...

```

Then I looked at the data with gnuplot. Since I want to know how to correct the readings, I plot the amount I have to add (minus column 3) v.s. the Arduino reading (column 2):

```
plot 'calibration.tsv' using 2:(-$3)

```

At this point it appears it's linear with what looks like mostly quantization noise. I model this as a line of equation `a*x+b`, and compare the line with the data:

```
a = -1e-2
b = 0.12
plot 'calibration.tsv' using 2:(-$3), a*x+b

```

The line is quite off the data, but it's a reasonable first approximation. Now I ask gnuplot to perform a least squares fit, then take another look:

```
fit a*x+b 'calibration.tsv' using 2:(-$3) via a, b
replot

```

Now the fit looks quite good. When it completed the fit, gnuplot displayed:

```
Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = -0.0151185       +/- 0.0002953    (1.953%)
b               = 0.125354         +/- 0.002173     (1.734%)

```

so now I know I can correct the data with:

```
voltage += -0.0151185 * volatage + 0.125354;

```

which is equivalent to what I wrote above.
> 3 votes

# Answer
Yes, you are right that the Arduino ADC is not accurate. If you read the datasheet (ATMega328P section 28.9, ADC Characteristics) you can see a lot of "error" and "non-linearity" characteristics.

These all add up to inaccuracies in your readings. For example the "Offset error" at your VREF could be as much as ±4.4mV, and the "Gain error" the same. Non-linearity can be as bad as 2mV, etc.

The Arduino ADC is not meant to be accurate. It's meant to be simple and cheap to implement. (It is a "Successive Approximation ADC" - approximation here is the keyword...) If you want a higher accuracy then there are more suitable ADC chips available that give that accuracy.
> 2 votes

---
Tags: adc, voltage-divider
---


# Question
Title: Serial monitor when port is being used by another application
I am controlling some LEDs via the USB serial port using a Tkinter/Python3x script to debug what I suspect is a hardware problem.

```
from tkinter import *
import serial

usbport = 'COM3'
ser = serial.Serial(usbport, 9600, timeout=1)

def init():
    print("Started")

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()
        self.scale1 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(1), bd=5, bigincrement=2, length=360, width=30, label='RED')
        self.scale1.set(128)
        self.scale1.pack(side=LEFT)
        self.scale2 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(2), bd=5, bigincrement=2, length=360, width=30, label='GREEN')
        self.scale2.set(128)
        self.scale2.pack(side=LEFT)
        self.scale3 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(3), bd=5, bigincrement=2, length=360, width=30, label='BLUE')
        self.scale3.set(128)
        self.scale3.pack(side=LEFT)
        self.centre = Button(frame, text="Centre All", command=self.centre)
        self.centre.pack(side=TOP)

    def getBright(self, slider):

        if slider==1:
            brt = self.scale1.get()

        if slider==2:
            brt = self.scale2.get()

        if slider==3:
            brt = self.scale3.get()

        ser.write(255)
        ser.write(slider)
        ser.write(brt)

    def centre(self):

        for LED in range(0, 4):

            ser.write(255)
            ser.write(LED)
            ser.write(128)

        self.scale1.set(128)
        self.scale2.set(128)
        self.scale3.set(128)

init()
root = Tk()
app = App(root)
root.mainloop()

```

On the Arduino Mega 2560 side I read in from serial a start byte, LED label & a brightness value...

```
int user_input[3];
int start_byte;
int LED;           // which LED to pulse? r=1 g=2 b=3
int brightness;
int i;

// LED pins
#define REDPIN 7
#define GREENPIN 8
#define BLUEPIN 9

void setup()
{

  // LED outputs
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  Serial.begin(9600);
}

void loop()
{
  if (Serial.available() > 2) {

    start_byte = Serial.read();
    if (start_byte == 255) {

      for (i = 0; i < 2 ; i++) {
        user_input[i] = Serial.read();
      }

      LED = userInput[0];
      brightness = user_input[1];

      switch (LED) {

        case 1:
          analogWrite(REDPIN, brightness);
          break;

        case 2:
          analogWrite(GREENPIN, brightness);
          break;

        case 3:
          analogWrite(BLUEPIN, brightness);
          break;

      }
    }
  }
}

```

Now I would like to see what is actually being sent via the serial port to the Arduino using the serial monitor (yes I know I can just print the values in the Python terminal that's not what I'm asking).

The problem is that the Arduino Serial Monitor is locked out. I'm guessing this is a Windows thing (Win10 x64)? Has anybody here come across this?

# Answer
> 1 votes
Serial data can only go to one place at a time. Either your Python program can receive the data, or the Serial Monitor can receive the data. Similarly the serial port can only receive data from one place at a time.

So Windows prevents you doing something invalid by locking you out of the serial port when something else is using it.

This is normal, and entirely desired functionality.

Your simplest option is to just print what you receive in your Python program.

---
Tags: serial, arduino-mega, serial-data
---


# Question
Title: Increase or decrease the brightness of Nextion display
I have a nextion display. I want to implement this issue of it. Start the program. If for example I don't touch the display for 15seconds, it should to turn off its brightness. If I touch the screen on any point, it should to increase its brightness.

For this I m build this code:

In PreinitializeEvent of page 0, I have insert this code:

```
tm0.tim=0
tm0.en=1
dim=30

```

In Touch Release Event of page 0, I have insert this code:

```
dims=100

```

But if I try to start the program, the brightness is always the same. Not increase.

/EDIT

I use Nextion Edito 0.58

# Answer
> 1 votes
*The original question has been improved (which is appreciated) to include the IDE which the poster is using. In this stackexchange.com space we primarily concern our selves with answering questions about developing using the Arduino IDE. While the Nextion Editor looks interesting, some may consider it off topic.*

*For those who come here interested in controlling the brightness of their Nextion Display and are using the Arduino IDE, there is this answer:*

There appears to be several Nextion Arduino Library efforts to choose from. If you are using this Nextion Display Library, here is the example code which set the screen brightness. The part of the code which sets the screen brightness is rather simple and resides in the Arduino loop() function. In the loop() function the brightness is set repeatedly as the program continues to run:

```
void loop() {
  int brightness = analogRead(A0);
  int bright = map(brightness, 0, 1024, 0, 100);
  String dim = "dim=" + String(bright);
  myNextion.sendCommand(dim.c_str());

}

```

*For those of you using the Nextion editor and the Nextion Arduino Libraries, there is this github.com Issue which talks about adding multiple missing Nextion features including a screen brightness function. This issues appears to still be OPEN (Bad support? / Bad house-keeping?). But is over a year old so may have be incorporated. If so, here is the example code from that link:*

```
/**
* Set the brightness of the display.
*
* @param buffer - number (0 - 100).
*/
bool setBrightness(byte buffer);

```

---
Tags: display, tft
---


# Question
Title: Error when compiling code NODE MCU ESP8266-12E module in Arduino ide
Here is my sketch:

```
#include<ESP8266WiFi.h>

char* ssid = "xxxxxxxx";
char* pass = "xxxxxxx";

void setup() {
 WiFi.begin(ssid,pass);
 Serial.begin(9600);
 while(WiFi.status()!=WL_CONNECTED)
 {
  Serial.print(".");
  delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.print(WiFi.localIP());
}

```

Here is the error:

```
Traceback (most recent call last):   File "C:\Users\ASUS\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2/tools/upload.py", line 25, in <module>
    esptool.main(fakeargs)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 2653, in main
    esp.connect(args.before)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 460, in connect
    last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 440, in _connect_attempt
    self.sync()   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 379, in sync
    timeout=SYNC_TIMEOUT)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 322, in command
    self.write(pkt)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 285, in write
    self._port.write(buf)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/pyserial\serial\serialwin32.py", line 323, in write
    raise writeTimeoutError serial.serialutil.SerialTimeoutException: Write timeout the selected serial port
serial.serialutil.SerialTimeoutException: Write timeout  does not
exist or your board is not connected

```

# Answer
> 2 votes
The section

```
void loop() {
}

```

Is missing in the code, add it and recompile and.....

---
Tags: esp8266, nodemcu, error
---


# Question
Title: How do I change pin assignments for the LUFA AVRISPMkII?
I just managed to get Dean Camera's LUFA AVRISP clone working on my Arduino Pro Micro, when to my dismay I found that to use PDI for my XMega, I need to have PD5 exposed for the clock source! The Pro Micro has PD5 connected to an LED, so I am not easily able to use it.

If worst comes to worst, I can desolder the LED and wire a jumper, but that would be a pain in the butt. So I am wondering if any of you know if I can change the clock pin assignment from PD5 to PD6 or some other accesible pin. Thank you in advance for your help!

--\[\[ EDITS \]\]-- Sorry for my lack of clarity, I am using the Pro Micro as the programmer, and the AVRISP clone supports PDI to the XMEGA. The 32u4 is actually directly supported by the programmer firmware. Here is what I am doing:

--\[\[ EDITS II \]\]-- There is a schematic.. umm.. draw-o? I don't know but anyway the cathodes of D1 and D3 are NOT connected. That wire is an error.

simulate this circuit – Schematic created using CircuitLab

--Cantos

# Answer
I found the answer searching through the Doxygen files. I had to go to AppConfig.h under Config in the project root directory, and edit AUX\_LINE\_MASK to change the pin. Thanks to everyone who helped!
> 1 votes

# Answer
Can you give more details on your problem? Schematics or something like that?

As I see from here, the Arduino Pro Micro uses ATmega32u4 chip, which is not part of XMega family, so I'm not sure if their internals are mutually compatible. In any case, if you configure PD5 as an input for your clock, it will work as an input, since it's a GPIO pin `(DDRD &= ~(1<<PIN5))`. You'll just additionally have the LED blinking :). You can also configure PD6 as an input in the same way `(DDRD &= ~(1<<PIN6))`.
> 0 votes

# Answer
just in case anyone else is trying to use a Pro Micro as a makeshift PDI programmer with the AVRISPMKII firmware included in the LUFA library: contrary to what the OP claims to have accomplished by editing AppConfig.h, it is NOT possible to reassign the XCK pin on ATMEGA devices (at least not to my knowledge). I can only conjecture as to why he made that claim (perhaps he confused XMEGA/ATMEGA, and thus ISP/PDI). I do not wish to blame the OP, but his post had sent me and others down a dead end for a minute, too bad there is no easy fix like that. :(

The XCK function is hard-wired to the pin, in this (ATMEGA32U4) case PD5. The LUFA code utilizes the ATMEGA's USART transmitter configured for synchronous operation, hence a clock signal must be provided to transfer data to the target device. That's why XCK must be used and there is no other way, at least not with LUFA. The call that enables the PDI target has nothing to do with the AUX\_LINE define in AppConfig.h

The only way a Pro Micro board can be used is by either soldering a wire to the XCK pin or by holding a wire against it (if you can hold it steady for a couple of seconds without slipping, that is). Thus, if you need a makeshift PDI programmer that will not require soldering, get a Teensy 2.0 or something else that breaks out PD5 as a GPIO pin.
> 0 votes

---
Tags: usb, isp, arduino-pro-micro, programmer
---


# Question
Title: How to generate .a and .so files to add in arduino project
I know to make a library on arduino ide with source codes, but I cant send my source code to another users who want to use my lib.

So I need to make a library with precompiled=true info at library.properties. And I need to put my .a and .so files at src/{build.mcu} (in my case, src/avr/mylib.a and mylib.so).

But, where is that files (.a and .so)?!

Does the arduino compiler generate this files? If so, where? If dont, how compiler I need to use?

I found the .o file at appData\local\Temp\arduino\_build\_XXXX\libraries\mylib\

Thank you very much and sory about my english.

# Answer
\[library\] = library name

1) edit the \[library\] library.properties file and add dot\_a\_linkage=true to the end ... (/home/name/Arduino/libraries/\[library\]/library.properties)

2) build the example ...

3) After the build is complete navigate to the build folder (In Linux it's located in the /tmp/arduino\_build\_xxxxxx folder) then copy the dot\_a file from under library folder (libraries/\[library\].a) to the arduino library folder for the \[library\] library (/home/name/Arduino/libraries/\[library\]/src/esp8266/lib\[library\].a)

4) edit the \[library\] library library.properties file again and remove dot\_a\_linkage=true and add precompiled=true and ldflags=-l\[library\] to the end of the file ...

5) build the example ... this time it links to the dot\_a file ...
> 1 votes

# Answer
* **Note: I have never done this with the Arduino IDE, so I don't know if the resultant file will be of any use to you.**

A `.a` file (you don't want a `.so` file - that's a shared library that makes no sense on a platform without an OS) is merely an archive (`ar` archive, specifically) that contains one or more .o files.

You create one simply enough using:

```
avr-ar rcs myLib.a myLib.o

```

You will find the `avr-ar` program in the tools installation within your Arduino IDE somewhere.

---

As an aside, UECIDE (which I wrote) uses library files like these to cache its libraries and other compiled code. You can use UECIDE to directly grab a .a file for your library, which you would find in the `cache` folder of the UECIDE data folder (find it through the Help -\> Debug menu).
> 0 votes

# Answer
Thank you Majenko!

But, the program is not avr-ar for me, I use the avr-gcc-ar.

After that, I must to dot\_a\_linkage=true in my library.properties and manually add mylib.a at AppData\Local\Temp\arduino\_build\_115676\libraries\mylib\

I dont know why, but this help for me.

I hope help other.

Best regards.
> 0 votes

---
Tags: arduino-uno, arduino-mega, arduino-ide, arduino-nano, library
---