title: DHT11 sensor providing -999 outputs

text:
# Question
Title: DHT11 sensor providing -999 outputs
I'm new here, trying to learn Arduino by hacking, that is plugging stuff in, looking for code and then trying to understand it bit by bit so I can move on to bigger and better projects.

My issue is that I am getting a periodic readout of -999.0 from a 3 pin DHT11 temperature and humidity sensor in between actual readouts. I can't find anything online explaining this but maybe I haven't looked hard enough. Attached is a screenshot containing both the code and serial monitor readout. Mechanical engineering background, so no electronic knowledge but feel free to get techy with your response.

if the image doesn't load this is the code;

```
#include <dht.h>

dht DHT;

#define DHT11_PIN 7

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

void loop()
{
  int chk = DHT.read11(DHT11_PIN);
  constrain (DHT.temperature, -25, 70);
  constrain (DHT.humidity, 0, 90);

  if((DHT.temperature || DHT.humidity) > -25)
  {
  Serial.print("Temperature, Humidity = ");
  Serial.print(DHT.temperature);
  Serial.print(", ");
  Serial.println(DHT.humidity);
  delay(1000);
  }
}

```

Thanks in advance for help or direction to help.

# Answer
-999 means that it didn't get a result from the DHT. You need to filter them out - which you are attempting to do, but wrongly.

Your line of code:

```
if((DHT.temperature || DHT.humidity) > -25) {

```

is not doing what you thing it is.

If you start from the inner most brackets and "reduce", you get:

```
Is DHT.temperature or DHT.humidity?

```

That makes no real sense - except in C any number that isn't 0 is "true" and 0 is "false", so that really means:

```
Is DHT.temperature not 0 or DHT.humidity not 0?

```

And of course that will be "true" in 99.99999% of situations. So insert that into the if again:

```
if (true > -25) {

```

Is true more than -25? Well, the reverse of what I stated above is also true: "true" is 1 and "false" is 0. So is 1 greater than -25? Yes. It is.

Instead you should be testing each value separately:

```
if ((DHT.temperature > -25) && (DHT.humidity > -25)) {

```

Also your constraints are doing nothing. `constrain()` doesn't modify (limit) the variable you pass to it. Instead it takes the value in that variable, constrains it, and returns the new constrained value to you for you to assign to a new variable. So you should:

```
float temperature = constrain (DHT.temperature, -25, 70);

```

And then you can use the `temperature` variable instead of `DHT.temperature`, and you can guarantee that it will be between -25 and +70.
> 1 votes

# Answer
As I recall you're not supposed to read from a DHT11 or DHT22 more frequently than every 2 seconds. If you wait until 2 seconds pass before reading again you should avoid -999 readings.

Majenko's answer shows you how to check for and skip out-of-range readings, but only reading once every 2 seconds should let you avoid them entirely.

Note that you should also check for NaN (not a number) values returned. That means there was a read error, which does happen from time to time.
> 0 votes

# Answer
Try to use Pull up resistor. Connect the 4.7K resistor parallel to 5v (if your supply for DHT11 is 5v 4.7K is Good, for other voltage, you need another value of resistor) and Data pin.
> 0 votes

---
Tags: sensors, temperature-sensor
---


# Question
Title: ESP32 Alexa Integration; Cannot correctly control more than one device
I created a garage door opener recently that is controllable through Alexa, using this library: https://github.com/Aircoookie/Espalexa

Everything is operating as expected, meaning I was able to detect my device and control the garage (using routines).

The issue came when I went to integrate Alexa into another previously completed/operational project. I was able to successfully discover and control the second board, kind of.

At this point I have added two ESP32 boards to Alexa, named differently of course. When I went to test the second board(meaning that it was successully discovered, and the ESP was receiving most commands) I noticed that Alexa was also opening my garage. If i unplugged my garage door opener(first board to be added) the second board starts to all receive commands, although degraded; for example;

In the above noted library Alexa should be able to control 'brightness' of dimmable lights. Of course this device is not a dimmable light but for the purposes of the integration, this library emulates smart lights. I am never able to see Alexa trying to set a brightness whose value is not 0.

Example, this is successfully executed on board 2, sometimes only when board 1 is unplugged:

```
void alexa_change_hdmi(EspalexaDevice* d) {
    Serial.println("Executing");
    uint8_t brightness = d->getValue();
    Serial.println(brightness);
    doing more things....

```

Here, brightness is always printed as 0.

So, after I added board X to alexa and tested successfully, I added board Y to alexa. Board X receives both commands for X and Y most of the time. Vice versa if board Y is the only device on. This is not intended by design. I would like to control them separately(preferably through the use of one alexa device).

I'm not sure if this (^) is related to the inability of Alexa to tell the two distinct board apart. I'm not sure why i'm not getting a brightness level, I would like to use it to make decisions, example;

```
if (brightness == '2.55') {
unsigned int irSignal[] = {9000, 4450, 600, 550, 550, 550, 600, 550, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1650, 600, 1650, 550, 1700, 550, 550, 600, 550, 550, 1700, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550}; // NEC FF906F
irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
}

```

Has anyone seen this issue integrating several ESP32 devices with one Amazon Echo? Has anyone ever gotten brightness to successfully pass into the function that alexa triggers?

## EDIT\*

After doing some more testing it appears that ESPALEXAWITHASYNCWEBSERVER is causing Alexa to not be able to differentiate between the distinct boards. This implies that if you want to use more than one device with this library, you cannot use the async example.

As a side effect, brightness always returns 0 when not using the async library, meaning you can really only use this library to control on and off state, not brightness, if you have more than one ESP device. ASYNC example correctly returns brightness, all other examples return 0, no matter what you set the brightness to.

# Answer
> 1 votes
Try this library , in past i have used 5 device at a time

fauxmoesp

---
Tags: esp32
---


# Question
Title: Arduino SIM5320e HTTP GET request to 000webhost.com
Im having trouble getting a successful HTTP GET request to a domain under 000webhost.com

I am trying to do a GET request which sends data to a php file on my domain and save it to MySQL database. I also did this first on my browser and it works fine so I don't think there are problem in my php file.

**MY DOMAIN:** ***wastedb.000webhostapp.com***

But if I try to send a request to dweet.io, it works as expected.

I am using a modified version of Adafruit\_FONA library and will post the code snippet and response from serial monitor below.

Here are the parameters that I used for the ***WORKING*** GET request:

**Host Address:** *www.dweet.io*

**Host:** *dweet.io*

**Response from Serial monitor for dweet.io (working):**

```
---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="www.dweet.io",80,1
<--- OK
---> AT+CHTTPSSEND=64
<--- >
---> GET /dweet/for/gearhead?hello=world HTTP/1.1
Host: dweet.io

<--- OK
---> AT+CHTTPSSEND
<--- OK
<--- +CHTTPSSEND: 0
---> AT+CHTTPSRECV?
<--- +CHTTPSRECV: LEN,361
---> AT+CHTTPSRECV=361
<--- OK
+CHTTPSRECV: DATA,361
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Date: Wed, 30 Jan 2019 00:16:43 GMT
Connection: keep-alive
Content-Length: 196

{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing
---> AT+CHTTPSCLSE
<--- OK
---> AT+CHTTPSSTOP
<--- OK

```

As we can see, the Arduino received a JSON response from the website.

Here are the parameters that I used for the ***NOT WORKING*** GET request:

**Host Address:** *wastedb.000webhostapp.com*

**Host:** *wastedb.000webhostapp.com*

**Response from Serial monitor for wastedb.000webhostapp.com (NOT WORKING):**

```
---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="wastedb.000webhostapp.com",80,1
<--- OK
---> AT+CHTTPSSEND=113
<--- >
---> GET /wastedb/get_location.php?lat=14.640155&lon=120.974920&stat=LOW HTTP/1.1
Host: wastedb.000webhostapp.com

<--- OK
---> AT+CHTTPSSEND
<--- ERROR

```

Am I missing something here? Seems like the shield cannot find the Host Server I provided for my website.

***EDIT:*** It is working now. The only solution that worked for me is to find another hosting site.

# Answer
It is working now. The only solution that worked for me is to find another hosting site.
> -1 votes

# Answer
Try just using IP address for the Host line instead. I did the same thing for POST and it works fine for me.

Example:

Host: 13.xxx.xx.xx
> 4 votes

---
Tags: http, iot
---


# Question
Title: [Solved]How to make my stepper motor run clockwise and counterclockwise?
I'm relatively new to Arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

I am using AccelStepper Library

Here is my code:

```
#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
}

```

I have tried to add delay and counterclockwise code but its not working.

```
#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  Serial.println("clockwise");
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
  Serial.println("counterclockwise");
  stepper.setSpeed(-1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
}

```

# Answer
> 2 votes
Hi here it the reference to the library functions that are available in accelstepper library.

Go through the link, it will provide you the issues with your code and example for your application like @smajli said **steps more than 1000 is unreliabe**, here you can see `setSpeed(float)` function where setting negative or positive sign selects the direction and value set the speed of rotation.

# Answer
> 0 votes
From the AccelStepper website: link

> Speeds of more than 1000 steps per second are unreliable

Try to change the speed to lower value, and let us know what is the outcome.

---
Tags: stepper-motor
---


title: Change data-type String

text:
# Question
Title: Change data-type String
I'm currently working with an ESP8266 NodeMCU V3 and an IR transmitter breakout board. The module receives NEC IR commands trough a HTTP request and then sends them trough the IR transmitter. Getting the command from the HTTP request and sending static (pre-programmed) IR NEC commands works perfectly. The problem however is that the NEC IR command I receive trough HTTP is in a `String` variable/data type (after processing). `irsend.sendNEC();` however requires `uint64_t` as the input type, according to the error message I get in the Arduino IDE.

I don't really know my way around C data types to be honest. Searches like "Arduino String to uint64\_t" have came up empty or reversed. One post came close to what I'm trying to accomplish, but `irsend.sendNEC(strtoul(irrequest));` didn't do the trick either.

Arduino code;

`Sketch.ino`

```
// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_PORT      = 80;
const int   CONFIG_TIMEOUT   = 5000;
const int   CONFIG_IRTPIN    = 2;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <IRrecv.h>
#include <IRutils.h>

// Create webserver object
WiFiServer server(CONFIG_PORT);

// Create IR Send object
IRsend irsend(CONFIG_IRTPIN);

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

  // Wait for WiFi connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected!");

  // Print WiFi connection information
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  Local IP: ");
  Serial.println(WiFi.localIP());

  // Start webserver
  Serial.println("Starting webserver...");
  server.begin();
  delay(1000);
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Host: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Port: ");
  Serial.println(CONFIG_PORT);

  // Start IR Send
  Serial.println("Starting IR Send...");
  irsend.begin();
  delay(1000);
  Serial.println("IR Send started!");

  // Setup complete
  Serial.println("Setup completed");
  digitalWrite(LED_BUILTIN, 0);
  Serial.println();

}

// Loop instructions
void loop() {

  // Wait for new client
  WiFiClient client = server.available();
  if (client) {

    // New client
    digitalWrite(LED_BUILTIN, 1);
    Serial.println("New client connected");

    // Wait nicely for the client to complete its full request
    unsigned long timeout = millis() + CONFIG_TIMEOUT;
    Serial.println("Waiting for client request to finish...");
    while (!client.available() && millis() < timeout) {
      delay(1);
    }

    // End client connection when timeout is reached to not hold up availability
    if (millis() < timeout) {
      Serial.println("Client request finished!");
    } else {
      Serial.println("Client request timeout!");
      client.flush();
      client.stop();
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();
      return;
    }

    // Catch client request
    String req = client.readStringUntil('\r');
    Serial.print("Request header: ");
    Serial.println(req);
    if (req.indexOf(F("/rest/ir/nec/")) != -1) {

      // Get IR Send NEC request
      String irrequest = req;
      irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
      irrequest.remove((irrequest.indexOf(" ")));
      Serial.print("IR Send NEC code: ");
      Serial.println(irrequest);

      // Send IR NEC command
      Serial.println("Sending IR NEC command");
      irsend.sendNEC(irrequest);    // <<< here lays the problem
      irsend.sendNEC(0xFB0042BD);   // This works
      irsend.sendNEC("0xFB0042BD"); // This doesn't

      // Send HTTP response
      Serial.println("Sending HTTP/1.1 200 OK");
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/plain");
      client.println("Connection: close");
      client.println();
      client.println("OK");

    } else {

      // Invalid request
      Serial.println("Invalid client request");
      Serial.println("Sending HTTP/1.1 404 response");
      client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html><body>Not found</body></html>");

    }

    // Flush output buffer
    Serial.println("Flushing output buffer");
    client.flush();
    digitalWrite(LED_BUILTIN, 0);
    Serial.println();
    return;

  }

}

```

# Answer
> 4 votes
`irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 10));` did the trick with the help of Juraj. Much thanks! I only had the set `10` to `16` to get it to work.

Working code:

```
// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_PORT      = 80;
const int   CONFIG_TIMEOUT   = 5000;
const int   CONFIG_IRTPIN    = 2;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <IRrecv.h>
#include <IRutils.h>

// Create webserver object
WiFiServer server(CONFIG_PORT);

// Create IR Send object
IRsend irsend(CONFIG_IRTPIN);

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

  // Wait for WiFi connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected!");

  // Print WiFi connection information
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  Local IP: ");
  Serial.println(WiFi.localIP());

  // Start webserver
  Serial.println("Starting webserver...");
  server.begin();
  delay(1000);
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Host: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Port: ");
  Serial.println(CONFIG_PORT);

  // Start IR Send
  Serial.println("Starting IR Send...");
  irsend.begin();
  delay(1000);
  Serial.println("IR Send started!");

  // Setup complete
  Serial.println("Setup completed");
  digitalWrite(LED_BUILTIN, 0);
  Serial.println();

}

// Loop instructions
void loop() {

  // Wait for new client
  WiFiClient client = server.available();
  if (client) {

    // New client
    digitalWrite(LED_BUILTIN, 1);
    Serial.println("New client connected");

    // Wait nicely for the client to complete its full request
    unsigned long timeout = millis() + CONFIG_TIMEOUT;
    Serial.println("Waiting for client request to finish...");
    while (!client.available() && millis() < timeout) {
      delay(1);
    }

    // End client connection when timeout is reached to not hold up availability
    if (millis() < timeout) {
      Serial.println("Client request finished!");
    } else {
      Serial.println("Client request timeout!");
      client.flush();
      client.stop();
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();
      return;
    }

    // Catch client request
    String req = client.readStringUntil('\r');
    Serial.print("Request header: ");
    Serial.println(req);
    if (req.indexOf(F("/rest/ir/nec/")) != -1) {

      // Get IR Send NEC request
      String irrequest = req;
      irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
      irrequest.remove((irrequest.indexOf(" ")));
      Serial.print("IR Send NEC code: ");
      Serial.println(irrequest);

      // Send IR NEC command
      Serial.println("Sending IR NEC command");
      irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 16));

      // Send HTTP response
      Serial.println("Sending HTTP/1.1 200 OK");
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/plain");
      client.println("Connection: close");
      client.println();
      client.println("OK");

    } else {

      // Invalid request
      Serial.println("Invalid client request");
      Serial.println("Sending HTTP/1.1 404 response");
      client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html><body>Not found</body></html>");

    }

    // Flush output buffer
    Serial.println("Flushing output buffer");
    client.flush();
    digitalWrite(LED_BUILTIN, 0);
    Serial.println();
    return;

  }

}

```

---
Tags: esp8266, string, ir, data-type
---


# Question
Title: Serial input values only working for very short seconds
I just made a very basic circuit with a LED and a resistor. I also wrote a program that's supposed to take an input for how long to keep the LED on for. It works fine for shorter times like 10 seconds but as soon as I try to input a time like 120 seconds the LED never turns off.
My code's below. What could be wrong?

```
int light=9;

void setup() {
  Serial.begin(9600);
  pinMode(light, OUTPUT);
  }

void loop() {
  Serial.println("How long do you want the light on for (in seconds)?");
  while(Serial.available()==0){}
  int on_time = (Serial.parseInt() * 1000);
  digitalWrite(light, HIGH);
  delay(on_time);
  digitalWrite(light, LOW);
  Serial.print("The light was just on for ");
  Serial.print(on_time/1000);
  Serial.print(" seconds. ");
}

```

# Answer
If you add `Serial.println(on_time);` right after `int on_time = (Serial.parseInt() * 1000);` you will see the problem. Once you enter the number 33 for example, the `integer` value printed is **-32536**. The Allowed data type for `delay()` is `unsigned long`, so the negative number is causing a problem.

Using `Serial.println()` judiciously can be very helpful when you are trying to debug a sketch.
> 2 votes

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


# Question
Title: Should L, TX, RX led light on while connected with laptop
Dear Sir, I need to know that should led light named as L, TX, RX should be on when we connect it with laptop? Because when I connect it with laptop led light turns on for 1 or 2 second then turns off. That's why I am asking you this question. Hoping for a favourable answer. Your's faithful, Nir Patel.

# Answer
> 1 votes
On Arduino Uno (and most basic Arduinos), the 'L' LED is operated by whatever code is on the Arduino. RX and TX flicker whenever the Arduino is sending data to the PC (TX) or is receiving data from the PC (RX).

If you have never re-programmed your Arduino, it is running whatever code was in it when it was shipped to you. It sounds like your Arduino has a bootloader but no code yet. The bootloader listens for the PC to try upload a new program. While it is listening, it blinks the L LED.

If the PC tries to upload, you will see the RX and TX lights flicker as the two communicate, until the upload is finished. Then whatever program was uploaded will run, and *it* will control the LEDs.

If the PC doesn't try to upload a new program within a few seconds (how long depends on which bootloader version is in the Arduino), the bootloader will start whatever program is already in the Arduino. Again, that program will then control the LEDs.

---
Tags: power, stepper-motor
---


# Question
Title: NTP rollover-safe design with ESP8266 (Curiosity)
The Arduino NTP implementation is rather naive in some respects. It basically just grabs the time in seconds from the raw packet, and then converts it to Unix time via subtraction. How would it be possible to create an implementation that is safe from at least this next NTP rollover (due in 2036)? I'd rather not design something that might suddenly fail in strange ways in a decade or two when I have forgotten why it might do so (but it's not horribly important if it's not easily fixed).

If it can make it to 2100, I'd have larger problems (the RTC would crap itself), so just this rollover is fine.

The existing implementation (https://github.com/arduino-libraries/NTPClient/blob/master/NTPClient.cpp):

```
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;

this->_currentEpoc = secsSince1900 - SEVENZYYEARS;

```

# Answer
> 4 votes
This implementation is perfectly fine. The calculations are done with unsigned numbers, so they are naturally rollover safe. The day NTP time rolls over, `secsSince1900` will become a very small number, and subtracting `SEVENZYYEARS` from it will cause an extra roll over. Owing to the rules of modular arithmetics, these two rollovers compensate and you are guaranteed to get the correct result modulo 232 s.

In the end, you get a Unix time as an unsigned 32-bit integer. Unix time is traditionally signed, which makes the 32-bit representation roll over in January 2038. The authors of this library have instead chosen to represent it as an *unsigned* number, which means it will roll over in February 2106.

---
Tags: esp8266, time
---


# Question
Title: Bit Number to Byte Value conversion (AVR Docs)
I have hard time to understand what this doc tells me: https://www.microchip.com/webdoc/AVRLibcReferenceManual/FAQ\_1faq\_use\_bv.html

I has a macro called `_BV` that

> convert a bit number (usually within a byte register) into a byte value

And the example tells this

> \_BV(3) =\> 1 \<\< 3 =\> 0x08

I am kinda used to bits and bytes etc. But I don't understand what the **3** in this example is? It says it converts a bit number but **3** is not binary it is an integer. And the macro resolves it to **0x08** which is the value of 8 in decimal.

I am very confused. I hope someone can explain to me what is happening here!

# Answer
The bits within a byte are numbered 0 through 7 from right to left. The rightmost (least significant) is bit 0, next is bit 1... and the leftmost (most significant) is bit 7.

The expression `_BV(3)` builds a byte where bit 3 is set (is 1) and all other bits are clear (are 0). In binary it looks like this:

```
position:   7  6  5  4  3  2  1  0
bit value:  0  0  0  0  1  0  0  0

```

The macro expands to `1<<3`, which takes the integer 1 (0b00000001 in binary) and shifts all its bits by three positions to the left. The result can be written 0b00001000 in binary, 0x08 in hexadecimal, and 8 in decimal.
> 3 votes

---
Tags: library, atmega328, bit
---


title: LED dimmer not fading out

text:
# Question
Title: LED dimmer not fading out
I'm trying to make an LED go from no brightness to max and back down on a loop and I've encountered a problem I can't seem to crack. The LED will go to maximum brightness steadily as it should but then it will drop to zero brightness and start again... Why?

```
int blue_led=10;

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

void loop() {

  int voltage=0;

  for(int i=0;i<=255;i+1){

    analogWrite(blue_led,voltage);
    voltage=voltage+1;
    delay(8);
  }
   int volts=255;

   for(int i=0;i<=255;i+1){

    analogWrite(blue_led,volts);
    volts=volts-1;
    delay(8);
   }

}

```

# Answer
your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)
> 2 votes

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


title: Running Python on Arduino

text:
# Question
Title: Running Python on Arduino
I've been using **Python** for quite long, and I was wondering if it can be used as a programming language for **Arduino**, rather than **C/C++**.

When I'm using the Arduino IDE, the sketch is compiled into a **hex** file that contains the program **binary**.

Knowing that micro controllers execute only binary, I would like to know if there is a tool to **convert** Python code into binary, so that I can **upload** it directly to Arduino using AVR or other programmers.

I read about **Micro Python**, a lightweight adaptation of Python that can fit in boards, but can only work with **PyBoard**, which I have never used yet.

I believe that Arduino manufacturers should start developing boards that can run Python, because it's very simple to use, unlike C/C++. It also has a lot of builtin modules that can make development very easy, which will achieve a remarkable progress in **IOT**.

# Answer
To my knowledge, there is not a "python to ATMega architecture" compiler out there.

However, it's not true that MicroPython only runs on PyBoard. There are versions for installation also on the ESP8266 and ESP32 chips, and so the popular NodeMCU and Wemos D1 development boards, or any of the other similar products with those processors, can easily run Python code. Many of these are available at a very low cost from the usual retailers/sources.

Be aware that MicroPython is somewhat limited compared to the full version due to the limited RAM available on these boards.
> 2 votes

---
Tags: c, c++, python
---


title: Check if Arduino Uno connected with PC

text:
# Question
Title: Check if Arduino Uno connected with PC
I'm using Arduino Uno controller

How it is possible to know if controller connected to PC via USB, to detect if wire is plugged and get condition for variable in sketch.

I've tried `Serial.available()`, but I'm not sure, if I can do it this way:

```
if (Serial.available())
{
   val = true;
}
else
{
   val = false;
}

```

I want use this condition to avoid `setup()` commands by some unexpected reason in case if controller powered only with adapter

# Answer
You can't determine if there is a valid USB source on the UNO without modifications, because the Atmega328P just receives serial data when the host sends some data. Some approaches that you can keep in mind.

1. If you want to determine whether you are connected through the USB or barrel connector, you can connect an analog pin to the Vin pin through a voltage divider (you should calculate the values so that you do not exceed 5V on the analog pin). This way if you detect a voltage greater than 6.6V you will know that you are being powered from the barrel jack.
2. If you want to detect a particular PC, you can write a SW in the PC which scans for new ports, then opens them and sends a particular string. If you receive that within X seconds, you know that you are connected to the PC
3. If you want to determine if you are connected to any valid PC, then I think you will need to modify the program in the Atmega16u2 which is used as a serial bridge between the two. I'm not sure whether it is possible or not, but I think that the Atmega16u2 knows when a valid USB session is started, and so can tell the Atmega328 this information (through the serial interface)
> 1 votes

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


title: GPS Module don't provide full data

text:
# Question
Title: GPS Module don't provide full data
I connected my gps module (NEO-6M) with esp32doit-devkit-v1 board. The module provided data but many data are missing.

### My pin configuration:

GPS ------- ESP32
VCC ------- 3v3
GND ------- GND
TX -------- RX2 (pin 16)
RX -------- TX2 (pin 17)

### Baud Rate: 9600

My code:

```
#include <Arduino.h>
#include <TinyGPS++.h>

#define TXD2 17
#define RXD2 16

TinyGPSPlus gps;

void setup()
{
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.println("Started......");
}

void loop()
{
  while (Serial2.available())
  {
    Serial.write(Serial2.read());
    // gps.encode(Serial2.read());
    // if (gps.location.isValid())
    // {
    //   Serial.print("Latitude= ");
    //   Serial.print(gps.location.lat(), 6);
    //   Serial.print(" Longitude= ");
    //   Serial.println(gps.location.lng(), 6);
    // }
  }
}

```

### OUTPUT

# Answer
GPS seems to be working and informing you that you have no signal. Usually happens inside buildings, when far from a window or when antenna isnt properly connected.

Testing out of doors is many times not possible, so try placing your antenna next to a window with a partial view of the sky. Wait for a couple of minutes until you get a fix on 4 or 5 satellites.
> 0 votes

---
Tags: serial, gps, esp32
---


title: Arduino IDE upload error

text:
# Question
Title: Arduino IDE upload error
I've recently been trying to make program using IRremote(library) in my Arduino IDE(v1.8.9), but whenever I hit the upload button this error message is returned

> Sketch uses 7514 bytes (23%) of program storage space. Maximum is 32256 bytes. Global variables use 415 bytes (20%) of dynamic memory, leaving 1633 bytes for local variables. Maximum is 2048 bytes.
>
> avrdude: verification error, first mismatch at byte 0x0002
>
> 0x5d != 0x62 avrdude: verification error; content mismatch
>
> avrdude: verification error; content mismatch

I'm using **Arduino UNO R3**

This is the code I'm trying to run

```
    #include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
    {
     Serial.println(results.value, HEX);
     irrecv.resume(); // Receive the next value
    }
}

```

Also, every other code(not using the IRremote library) uploads just fine without any errors.

# Answer
There can be power/connection problem or somehow the bootloader has been damaged. So

* Check power
* Check Connection

If there no problem found, then by using usbasp, avrisp, usbtinyisp, etc reflash the bootloader. I hope your problem will be solved.
> 0 votes

---
Tags: arduino-uno, arduino-ide, library, ir, remote-control
---


title: C++ trim char array

text:
# Question
Title: C++ trim char array
I have a char array of length 10. It gets filled with an unpredictable number of chars, usually up to 6.

```
char charDummy[10] = "";

```

When i concatenate the char array with another, I get spaces, which are unwanted in later parsing.

```
char postStr[300] = "";
strcat(postStr, "&field1=");
strcat(postStr,dtostrf(rain05m,6,2,charDummy));

```

How do I trim a char array directly?

Workaround: loop thru the array and copy valid characters to a new char array with perfect number of rows. Due to memory constraints, I need to be parcimonious with the amount of variables created.

# Answer
Your problem is that `dtostrf()` right-aligns the value in the space allotted to it. The simple answer is to tell it to left-align instead:

> Conversion is done in the format "\[-\]d.ddd". The minimum field width of the output string (including the possible '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. **width is signed value, negative for left adjustment.**
>
> AVR LIBC Manual

So, just make your width negative and it will left align.
> 3 votes

---
Tags: c++
---


title: Trying to communicate with an ESP8266

text:
# Question
Title: Trying to communicate with an ESP8266
G'day guys, I'm trying to get an ESP8266 to work with an Arduino Uno.
Here is the wiring.

When I go to the serial monitor (115200 baud) and type: AT, there is not response from the ESP8266.
Is there something that I am missing?
I also have a servo motor connected, it works fine.

```
include "Arduino.h"
include "ESP8266.h"
include "dweet.h"
include "Servo.h"

define ESP8266_PIN_RX 10
define ESP8266_PIN_TX 11
define SERVO9G_PIN_SIG 2

const int servo9gRestPosition   = 20;
const int servo9gTargetPosition = 150;
const char *SSID     = "Wireless Network";
const char *PASSWORD = "wireless_password";

ESP8266 wifi(ESP8266_PIN_RX,ESP8266_PIN_TX);
Servo servo9g;

const int timeout = 10000;
char menuOption = 0;
long time0;

void setup()
{
   Serial.begin(9600);
   while (!Serial); //await connection.
   Serial.println("start");

   wifi.init(SSID, PASSWORD);
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gRestPosition);
   delay(100);
   servo9g.detach();

}

void loop()
{
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gTargetPosition);
   delay(500);
   servo9g.write(servo9gRestPosition);
   delay(500);
   servo9g.detach();
}

```

I'm using the ESP8266 Library.
When trying to connect it just says `Initializing device...`

# Answer
> 1 votes
Unless you have some project constraints which make it mandatory to use naked ESP8266, why not use a NodeMCU to communicate with the Arduino in a master/slave relation over I2C?

```
#include <Wire.h>
#define I2CAddressESPWifi 8

```

in `setup()`

```
Wire.begin(D1,D2); // SCL D1 SDA D2

```

then call from anywhere inside your `loop()` call this function

```
char readSlave(int x) { // send current time
  String xY = String(x);
  char c;
  int charArrayLength = xY.length()+1;
  char bufferChar[charArrayLength];
  Wire.beginTransmission(8);
  xY.toCharArray(bufferChar, charArrayLength);
  Wire.write(bufferChar);
  Wire.endTransmission();
  delay(10);
  Serial.print("wire sent: [");
  Serial.print(x);
  delay(50);//Wait for Slave to calculate response.
  int counter = 0;
  char buffMe[32];
  int bytesIn = Wire.requestFrom(8,32);
  while (Wire.available()) {
    delay(2);
    buffMe[counter] = Wire.read();
    /*
    c = Wire.read();
    Serial.print(c);
    */
    counter++;
  }
  delay(10);
  Wire.endTransmission();
  delay(500);
  Serial.print("] bytesIn: [");
  Serial.print(bytesIn);
  Serial.print("] buffMe: [");
  Serial.print(buffMe);
  Serial.print("]");
  return buffMe;
}

```

and your arduino will be waiting (`setup`)

```
Serial.begin(9600);
// slave listens for call from master NodeMCU
Wire.begin(I2CAddressESPWifi);  // predefined as `8` or whatever address you choose
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);

```

and at the end of your code

```
void receiveEvent(int howMany) {
  if (howMany) {
    Serial.print("bytes[");
    Serial.print(howMany);
    Serial.print("] Received[");
    char charIn[howMany];
    int counter = 0;
    while (Wire.available()) {
      char c = Wire.read();
      charIn[counter] = c;
      //Serial.print(c);
      counter++;
    }
    delay(10);
    //do something with command from master
  }
}
void requestEvent() {
  char bufferChar[20] = "slave answer string";  // automatically null terminated extra character at end
  Serial.println(bufferChar);
  Wire.write(bufferChar);
}

```

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


title: WS2812 Matrix colour problem. Power?

text:
# Question
Title: WS2812 Matrix colour problem. Power?
I have 8 8x8 WS2812 Matrix LED boards connected together to make 2 16x16 matrices. I have them connected with Dupont wires.

I also power the 2 16x16 with Dupont wires that are connected to a 5v 60Amp PSU (More Leds will be added later). The PSU power should easily support the LED power requirements however, if I set the brightness anything over 30...the first matrices start to get reddish at the end. They start white but as the end they are orange/red. If I set the brightness to 20-25 they are white. So there must be something with the power but I have 60amps...Can it be that the Dupont cables are the bottleneck? The cables don't get hot...so I guess they are ok?

Any help is highly appreciated.

Thanks V.A

# Answer
Use at least AWG20 and power each possible spot on the matrices (in and out). All the energy not reaching the LEDs is fried in the DuPont wires. Use Ohms law.
> 0 votes

---
Tags: led, ws2812
---


# Question
Title: Best way of storing extra data for Arduino project
I am an arduino beginner and I am trying to make a speed camera alert system, it would start beeping if I am above the speed limit and getting close to the speed camera. There is this website where I can get all the data I need, coordinates, direction and speed limit of every 36000 speed cams in my country.

I would need some extra memory space to be able to store all this data, would an eeprom chip do the job? and would it be able to keep up with a for loop going through all those 36000 speed cam locations to check if i am close to it and above the speed limit?

Edit: since going through all those locations on a loop would be a lot for the processor to handle, someone recommended the creation of a temp file that would narrow that list down by direction, and when that direction changed it would recalculate that temp file. This is what I came up with:

```
void setup() {
  int tempDirection = gpsDirection;
  writeTempFile();
}

void loop() {
  //this will recalculate the temp file when the gpsDirection changes
  if(gpsDirection > tempDirection +5 || gpsDirection < tempDirection -5){
    tempDirection = gpsDirection;
    writeTempFile();
  }

  for(temp file){
    if(distance <= 100 && speed > speedlimit){
      //start beeping
    }
  }
}

void writeTempFile(){
  //this will write a temp file with every cam with a direction that's similar the gps direction
  for(each line of the file){
    if(gpsDirection + 10 > camDirection || gpsDirection - 10 < camDirection ){
      add cam to temp file;
    }
  }
}

```

# Answer
> 2 votes
EEPROM writes are limited to about 100k cycles. They are for permanent or semi-permanent data (like your absolute speed threshhold - 120kmh, for example).

You should not store your speed camera base here.

Get a MicroSD adapter and save your data there. Looping thru 36000 speed trap locations is going to put a toll on your processor and memory. I recommend that you determine a binding box (+/- 2 degrees, for example) and save a temp file with only those traps inside the box. recheck every time your position changes a full degree (N/S or E/W).

Notice: in some countries, Brazil for example, distributing information regarding speed trap locations is illegal (obstruction of justice).

---
Tags: gps, eeprom, memory
---


# Question
Title: Accelstepper - how to switch from fullstep to halfstep in loop?
I am using `Accelstepper` library to control a unipolar stepper motor. In my project, I would like to run the stepper in full-step mode when I need speed and in half-step mode when I need precision. As you know, the full-step/half-step selection is done in the very beginning of the sketch...

I found a workaround by creating two instances of `Accelstepper` for the same stepper. That is:

```
Accelstepper fast(FULL4WIRE, 2,3,4,5);

Accelstepper slow(HALF4WIRE, 2,3,4,5);

```

With this, when I call (skipping other details of the code) `fast.run()` the motor moves fast (full-step) and when I call `slow.run()` it moves slowly as it is in half step mode.

But;

When it comes to determine to current motor position, this workaround fails, since there are two different values returned by the two functions: `fast.currentPosition()` and `slow.currentPosition()`. So this workaroud becomes useless.

My first question is: is there a way in `Accelstepper` to switch from full-step to half-step and vice versa in the execution(let say in the loop)? If so, the second question can be skipped.

The second: `XX.currentPosition()` function returns the value of a variable, namely "\_currentPos" which is calculated in `Accelstepper.cpp` file. As I understand, there become, as many `_currentPos` values as `Accelstepper` instances. In my case, one for fast and another for slow, and somehow they are kept and calculated individually without any confusion. Is there a way to access (extern?) and set this variable from the sketch, by referencing the specific `Accelstepper` instence? Briefly, is there a way to copy one motor position to another?

Many thanks.

# Answer
> 1 votes
The documentation notes a `setCurrentPosition()` function.

> ```
> void AccelStepper::setCurrentPosition ( long position )
>
> ```
>
> Resets the current position of the motor, so that wherever the motor happens to be right now is considered to be the new 0 position. Useful for setting a zero position on a stepper after an initial hardware positioning move. Has the side effect of setting the current motor speed to 0.
>
> Parameters
>
> **position** The position in steps of wherever the motor happens to be right now.

---

Use the `currentPosition()` function to get the current position from either mode. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.

---
Tags: c++, stepper, variables
---


# Question
Title: Problem with reading data from HMC5883L in GY-86
I am trying to read the data from GY-86 with my arduino UNO. While reading MPU6050 and MS5611, it works quite well. But somehow I can't read anything from HMC5883L. Here is the code I used:

```
#include <Wire.h>
#include <HMC5883L.h>

HMC5883L compass;

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

  // Initialize HMC5883L
  Serial.println("Initialize HMC5883L");
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }

  // Set measurement range
  // +/- 0.88 Ga: HMC5883L_RANGE_0_88GA
  // +/- 1.30 Ga: HMC5883L_RANGE_1_3GA (default)
  // +/- 1.90 Ga: HMC5883L_RANGE_1_9GA
  // +/- 2.50 Ga: HMC5883L_RANGE_2_5GA
  // +/- 4.00 Ga: HMC5883L_RANGE_4GA
  // +/- 4.70 Ga: HMC5883L_RANGE_4_7GA
  // +/- 5.60 Ga: HMC5883L_RANGE_5_6GA
  // +/- 8.10 Ga: HMC5883L_RANGE_8_1GA
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  // Idle mode:              HMC5883L_IDLE
  // Single-Measurement:     HMC5883L_SINGLE
  // Continuous-Measurement: HMC5883L_CONTINOUS (default)
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  //  0.75Hz: HMC5883L_DATARATE_0_75HZ
  //  1.50Hz: HMC5883L_DATARATE_1_5HZ
  //  3.00Hz: HMC5883L_DATARATE_3HZ
  //  7.50Hz: HMC5883L_DATARATE_7_50HZ
  // 15.00Hz: HMC5883L_DATARATE_15HZ (default)
  // 30.00Hz: HMC5883L_DATARATE_30HZ
  // 75.00Hz: HMC5883L_DATARATE_75HZ
  compass.setDataRate(HMC5883L_DATARATE_15HZ);

  // Set number of samples averaged
  // 1 sample:  HMC5883L_SAMPLES_1 (default)
  // 2 samples: HMC5883L_SAMPLES_2
  // 4 samples: HMC5883L_SAMPLES_4
  // 8 samples: HMC5883L_SAMPLES_8
  compass.setSamples(HMC5883L_SAMPLES_1);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.print("Selected range: ");

  switch (compass.getRange())
  {
    case HMC5883L_RANGE_0_88GA: Serial.println("0.88 Ga"); break;
    case HMC5883L_RANGE_1_3GA:  Serial.println("1.3 Ga"); break;
    case HMC5883L_RANGE_1_9GA:  Serial.println("1.9 Ga"); break;
    case HMC5883L_RANGE_2_5GA:  Serial.println("2.5 Ga"); break;
    case HMC5883L_RANGE_4GA:    Serial.println("4 Ga"); break;
    case HMC5883L_RANGE_4_7GA:  Serial.println("4.7 Ga"); break;
    case HMC5883L_RANGE_5_6GA:  Serial.println("5.6 Ga"); break;
    case HMC5883L_RANGE_8_1GA:  Serial.println("8.1 Ga"); break;
    default: Serial.println("Bad range!");
  }

  Serial.print("Selected Measurement Mode: ");
  switch (compass.getMeasurementMode())
  {
    case HMC5883L_IDLE: Serial.println("Idle mode"); break;
    case HMC5883L_SINGLE:  Serial.println("Single-Measurement"); break;
    case HMC5883L_CONTINOUS:  Serial.println("Continuous-Measurement"); break;
    default: Serial.println("Bad mode!");
  }

  Serial.print("Selected Data Rate: ");
  switch (compass.getDataRate())
  {
    case HMC5883L_DATARATE_0_75_HZ: Serial.println("0.75 Hz"); break;
    case HMC5883L_DATARATE_1_5HZ:  Serial.println("1.5 Hz"); break;
    case HMC5883L_DATARATE_3HZ:  Serial.println("3 Hz"); break;
    case HMC5883L_DATARATE_7_5HZ: Serial.println("7.5 Hz"); break;
    case HMC5883L_DATARATE_15HZ:  Serial.println("15 Hz"); break;
    case HMC5883L_DATARATE_30HZ: Serial.println("30 Hz"); break;
    case HMC5883L_DATARATE_75HZ:  Serial.println("75 Hz"); break;
    default: Serial.println("Bad data rate!");
  }

  Serial.print("Selected number of samples: ");
  switch (compass.getSamples())
  {
    case HMC5883L_SAMPLES_1: Serial.println("1"); break;
    case HMC5883L_SAMPLES_2: Serial.println("2"); break;
    case HMC5883L_SAMPLES_4: Serial.println("4"); break;
    case HMC5883L_SAMPLES_8: Serial.println("8"); break;
    default: Serial.println("Bad number of samples!");
  }

}

void loop()
{
  Vector raw = compass.readRaw();
  Vector norm = compass.readNormalize();

  Serial.print(" Xraw = ");
  Serial.print(raw.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(raw.YAxis);
  Serial.print(" Zraw = ");
  Serial.print(raw.ZAxis);
  Serial.print(" Xnorm = ");
  Serial.print(norm.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(norm.YAxis);
  Serial.print(" ZNorm = ");
  Serial.print(norm.ZAxis);
  Serial.println();

  delay(100);
}

```

I download it from https://github.com/jarzebski/Arduino-HMC5883L.

The program always stuck at

```
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }

```

Here is the begin function in HMC5883L.cpp

```
bool HMC5883L::begin()
{
    Wire.begin();

    if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
    || (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
    || (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
    {
    return false;
    }

    setRange(HMC5883L_RANGE_1_3GA);
    setMeasurementMode(HMC5883L_CONTINOUS);
    setDataRate(HMC5883L_DATARATE_15HZ);
    setSamples(HMC5883L_SAMPLES_1);

    mgPerDigit = 0.92f;

    return true;
}

```

So, it seems that the begin function always returns False. What should i do to solve this problem?

This is how I connect GY-86 to UNO:

VCC-IN -\> 5V

GND -\> GND

SDA -\> 4A

SLC -\> 5A

# Answer
> 2 votes
Did you run a i2c scanner? Is it found with i2c address 0x1E?

Looking at the schematic, the magnetometer HMC5883L is connected to XDA and XCL. That is not the normal I2C bus, but a second I2C bus from the MPU-6050.

The reason for that is that the 'dmp' firmware in the MPU-6050 can read the magnetometer and do calculations with it, in the MPU-6050.

If you want to communicate with the magnetormeter via the normal I2C bus, then you have to turn on the bypass-mode.

The libraries from Jeff Rowberg and Jarzębski are large. I suggest to enable the bypass-mode and run a i2c scanner.

Do you have a logic analyzer? Perhaps you can use a simple multimeter. Keep the SDA low (shortcut it to GND) and try to measure if XDA is low as well in the bypass mode.

There is a chance that something is broken.

# Answer
> 3 votes
Thank to Jot, your answer actually helps me. Now I am using this code and it is working very well.

```
#include <Wire.h>
#include <HMC5883L.h>
#include <MPU6050.h>

HMC5883L compass;
MPU6050 mpu;

int previousDegree;

void setup()
{
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif
  Serial.begin(38400);

  // Initialize MPU6050
  mpu.initialize();

  // Enable bypass mode
  mpu.setI2CMasterModeEnabled(false);
  mpu.setI2CBypassEnabled(true);
  mpu.setSleepEnabled(false);

  // Initialize HMC5883L
  while (!compass.begin())
  {
    delay(500);
  }

  // Set measurement range
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  compass.setDataRate(HMC5883L_DATARATE_30HZ);

  // Set number of samples averaged
  compass.setSamples(HMC5883L_SAMPLES_8);

  // Set calibration offset. See HMC5883L_calibration.ino
  compass.setOffset(0, 0);
}

void loop()
{
  long x = micros();
  Vector norm = compass.readNormalize();

  // Calculate heading
  float heading = atan2(norm.YAxis, norm.XAxis);

  // Set declination angle on your location and fix heading
  // You can find your declination on: http://magnetic-declination.com/
  // (+) Positive or (-) for negative
  // For Bytom / Poland declination angle is 4'26E (positive)
  // Formula: (deg + (min / 60.0)) / (180 / M_PI);
  float declinationAngle = (4.0 + (26.0 / 60.0)) / (180 / M_PI);
  heading += declinationAngle;

  // Correct for heading < 0deg and heading > 360deg
  if (heading < 0)
  {
    heading += 2 * PI;
  }

  if (heading > 2 * PI)
  {
    heading -= 2 * PI;
  }

  // Convert to degrees
  float headingDegrees = heading * 180/M_PI;

  // Fix HMC5883L issue with angles
  float fixedHeadingDegrees;

  if (headingDegrees >= 1 && headingDegrees < 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 0, 239, 0, 179);
  } else
  if (headingDegrees >= 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 240, 360, 180, 360);
  }

  // Smooth angles rotation for +/- 3deg
  int smoothHeadingDegrees = round(fixedHeadingDegrees);

  if (smoothHeadingDegrees < (previousDegree + 3) && smoothHeadingDegrees > (previousDegree - 3))
  {
    smoothHeadingDegrees = previousDegree;
  }

  previousDegree = smoothHeadingDegrees;

  // Output
  Serial.print(norm.XAxis);
  Serial.print(":");
  Serial.print(norm.YAxis);
  Serial.print(":");
  Serial.print(norm.ZAxis);
  Serial.print(":");
  Serial.print(headingDegrees);
  Serial.print(":");
  Serial.print(fixedHeadingDegrees);
  Serial.print(":");
  Serial.print(smoothHeadingDegrees);
  Serial.println();

  // One loop: ~5ms @ 115200 serial.
  // We need delay ~28ms for allow data rate 30Hz (~33ms)
  delay(30);
}

```

By the way, the code on https://github.com/jarzebski/Arduino-HMC5883L should add

```
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif

```

in the begin of setup.

---
Tags: arduino-uno, i2c
---


# Question
Title: Can I power Arduino with 12V 1.2A adapter
I am new to arduino and i am making a smart energy meter for my home. I want to run the arduino months so, how to power arduino with a adapter, I have a 12V 1.2A adapter is it ok to power arduino with it or not?. Thanks in advance. As i said i want to run it long time.

# Answer
> 2 votes
If it is an Arduino Uno Rev3 SMD, the documentation (see Juraj's comment) is of relevance here, click the tab "Tech Specs" to find:

> Operating Voltage 5V
>
> Input Voltage (recommended) 7-12V
>
> Input Voltage (limit) 6-20V

While the microcontroller's (ATmega328P) operating voltage is 5 V there is an on-board voltage regulator to make the board work within the input voltage range of 6 to 20 V (max limits) or the recommended range of 7 to 12 V.

Operating this Arduino with a 12 V power adapter is within spec and therefore safe to do. The current rating of the adapter of 1.2 A is also more than sufficient to run the Arduino.

# Answer
> 2 votes
Yes, you can power an Arduino with 12V into the barrel connector. It will then use it's internal voltage regulator to drop that to the 5V it needs internally. However, that is on the high side of it's recommended range, and will make the Arduino's voltage regulator run hot. A 7.5V supply would be better, and you could probably get more total current out of the 5V regulator without overheating if you fed it 6V or 7.5V instead of 12V. (6V is the lower limit. \>= 7V is better.)

(A linear voltage regulator like the one in most Arduino boards essentially uses a transistor as a variable resistor to lower the voltage from the input voltage to 5V, which converts the excess voltage to heat. The higher the input voltage, and the more current you draw from the regulator, the more heat it generates.)

---
Tags: arduino-uno
---


title: Float division returns "inf" and 0

text:
# Question
Title: Float division returns "inf" and 0
I'm new to Arduino and I'm doing an ultrasonic project where I test for the speed of sound. My code is below and for some reason, this is what the serial port returns:

This is the measured speed of sound: inf m/s This is the measured speed of sound: 0m/s This is the measured speed of sound: 0m/s etc...

Here's my code. Any help's massively appreciated:)

```
int trig = 13;
int echo = 11;
float target_distance = 0.3;
float recieved;
float speed_of_sound;

void setup() {
    Serial.begin(9600);
    pinMode(trig, OUTPUT);
    pinMode(echo, INPUT);
}

void loop() {
    digitalWrite(trig, LOW);
    delayMicroseconds(2000);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);

    recieved=pulseIn(echo, HIGH);
    recieved = recieved*1000000.0;
    speed_of_sound = (2*target_distance)/recieved;
    Serial.print("This is the measured speed of sound: ");
    Serial.print (speed_of_sound);

    Serial.println("m/s");
    delay(3000);
}

```

# Answer
> 1 votes
Assuming the speed of sound is of the order of 330 m/s, you expect the round-trip to the target and back to last about 1.8 ms. Then

```
recieved = pulseIn(echo, HIGH);

```

should give a value close to 1,800, and

```
recieved = recieved * 1000000.0;

```

should make `received` something like 1.8 × 109. Then

```
speed_of_sound = (2*target_distance)/recieved;

```

gives a speed of sound of 3.3 × 10−10. It is the correct value if you want that speed in meters per picosecond, but this is inconsistent with your program printing “m/s” after the value.

The Arduino's `Serial.print()` is quite dumb with floating point numbers. It defaults to printing two digits after the decimal point, irrespective of the order of magnitude of the number. Thus, anything smaller than 0.005 gets printed as “0”.

I don't quite understand why you got ∞ on the first loop. Looks like `pulseIn()` missed the pulse and returned zero, in which case the speed is computed as 0.6 ÷ 0 = ∞.

The solution is to compute `received` as

```
recieved = pulseIn(echo, HIGH) * 1e-6;

```

This can be remembered by thinking that a quantity (round-trip time) is a numeric value (`pulseIn(echo, HIGH)`) multiplied by a unit (`1e-6`, which stands for “microseconds”).

---
Tags: arduino-uno
---


# Question
Title: Segmentation fault and huge SRAM need for Serial.println
I have written my own 'assert' since I want to use it for both Windows and Arduino. The class is called from many files (about 10).

AssertUtils.h:

```
#pragma once

#define assert(expr) AssertUtils::Assert2((expr), (__func__), (__FILE__), (__LINE__));

class AssertUtils
{
public:
    static void Assert2(bool expression, const char* funcName, const char* fileName, int line);
};

```

AssertUtils.cpp:

```
#include "AssertUtils.h"
#include "Arduino.h"

/* static */ void AssertUtils::Assert2(bool expression, const char* funcName, const char* fileName, int line)
{
    if (!expression)
    {
        Serial.println(funcName);
        Serial.println(fileName);
        Serial.println(line, DEC);
        Serial.flush();

        // Abort program execution.
        abort();
    }
}

```

When I compile this, the SRAM usage is 1469 bytes (together with the rest of my sketch and classes).

When I comment the line below, I get a segmentation fault in a random assert call (when I comment out that call, I get it in the next, etc.).

```
    //Serial.println(funcName);

```

When I also comment out the second print statement, the compiler reports only 1137 bytes SRAM usage (which I expect since this was about equal until before I added the Assert class).

```
    //Serial.println(funcName);
    //Serial.println(fileName);

```

Questions:

1. How can I get rid of the segmentation fault?
2. How can it be that about 332 bytes are used for one two additional print statements? (maybe related to the const char\* buffering (?)

# Answer
> 2 votes
Note, this answer is not MY answer, but approximately the combination of the first 5 comments from my original question.

What I did was:

* (Juraj) Changed the compiler version to 6.21
* (juraj) Added an F in `F(__FILE__)`
* (KIIV) Removed **func**; this did not work with the `F` flash helper, but I can find back the code anyway unambiguously because of the file name + line number.
* (Majenko) I removed the class and use a macro. This costs some more Flash memory (depending on the number of asserts I use, but I'm still around 40% (was 35%).

The SRAM usage is now 1125 bytes, even less than where I'm started with.

The resulting code is below:

```
#define assert(expression) \
  if (!(expression)) \
  { \
    Serial.println(F(__FILE__)); \
    Serial.println(__LINE__, DEC); \
    Serial.flush(); \
    abort(); \
  }

```

---
Tags: serial, programming, arduino-nano, class, c-preprocessor
---


# Question
Title: Whats the maximum external voltage/current i can apply through an Arduino Uno ? + a couple mini questions
i'm just starting out with electronics and Arduino's and was wondering about the extent of an Arduino's ability. Will i eventually be able to program and power very high voltage/current requiring devices such as a full sized fan motor? Also at what point would i not be able to use normal wires, components and breadboards due to a high current/voltage (not sure which one would break them).

I know these are total noob questions but thanks in advance!

# Answer
**Arduino Uno**

First, never use too high voltages on GPIO pins of an Arduino. if you want to know, search for 'absolute maximum current' or 'absolute maximum voltage'. Probably any pin of an Arduino is about 5 V (plus some headroom).

**External power**

So since your fan will use more voltage high likely, you are not lost, in contrary, you should use a separate power source (giving the voltage you need for the fan), and use either a relay, or a transistor or MosFet. Than you can program it with a 5 volts pin and control a much higher voltage device (your fan).

**Wires**

Do not send high voltages/currents through breadboards and jumper wires neither. Use separate wiring, and you can check tables using AWG (thickness of wires) to see how much current they can support. Note that I say current, not voltage. The voltage will drop depending on the length of the wire and the size, so calculate that you have enough voltage at the end of the wire.

**Safety**

Also for safety, do not forget a fuse, and remember that the external power source and all wires have the same voltage as the fan, which may kill you if you touch them.
> 0 votes

# Answer
arduinos, and microcontrollers in general, handle only very small ammounts of current, and they work at what is called 'logic level' voltage, usually much lower than 'line' voltage or 'mains,' which is your wall outlet. in general an arduino will put out 30-50 mAh per pin, and max of about 200mAh combined. again, the total ouput for the entire board is a max of about 0.2 amps. the idea is that the pins are pulled high or low (+5 or ground) depending on the logic of the programming. these signals trigger logic level components to act, usually mosfets/transistors and relays turn higher loads on/off

basically, you dont want to power even a single led without a current limiting resistor. its just a micro*controller* after all
> 0 votes

---
Tags: arduino-uno, electronics, electricity
---


# Question
Title: How to write code to make the LED’s ﬂash in the following sequence?
How to write code like this sequence? What is the meaning of 4 decimal? For this, we had to add a delay in the code

```
led_Pin_1 1 0 0 0
led_Pin_2 0 1 0 0
led_Pin_3 0 0 1 0
led_Pin_4 0 0 0 1

```

my code, It is working. But I need to convert this code to above sequence?

```
int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  digitalWrite(led_Pin_1, HIGH);
  delay(200);
  digitalWrite(led_Pin_2, HIGH);
  delay(200);
   digitalWrite(led_Pin_3, HIGH);
  delay(200);
   digitalWrite(led_Pin_4, HIGH);
  delay(200);
  digitalWrite(led_Pin_1, LOW);
  delay(300);
   digitalWrite(led_Pin_2, LOW);
  delay(300);
   digitalWrite(led_Pin_3, LOW);
  delay(300);
   digitalWrite(led_Pin_4, LOW);
  delay(300);
}

```

# Answer
> 0 votes
```
int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

int led_on = 0; // Start with first (led_Pin_1)

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(led_Pin_1, (led_on == 0) ? HIGH : LOW);
  digitalWrite(led_Pin_2, (led_on == 1) ? HIGH : LOW);
  digitalWrite(led_Pin_3, (led_on == 2) ? HIGH : LOW);
  digitalWrite(led_Pin_4, (led_on == 3) ? HIGH : LOW);
  delay(250);

  led_on = (led_on + 1) % 4;
}

```

led\_on will start with 0 (pin 1), switching only that pin on. Some explanation:

```
(led_on == 0) ? HIGH : LOW

```

This means: if (led\_on == 0), than the value will be HIGH, otherwise LOW. Resulting in only pin 1 going on, if led\_on is 0, and in the next loop, only pin 2 oing on, because led\_on is 1 etc.

```
led_on = (led_on + 1) % 4;

```

This increases the value of led\_on, but when it reaches 4, it reverts back to 0.

I don't know about the delay times you need. I guess you want to change all LEDs at once, than wait.

You can make the 4 almost identical digitalWrite lines into a function as small improvement.

If you want to do more with the LEDs, than consider storing the leds into an array and use a for loop to iterate through them.

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: NodeMCU Modbus interfacing with Pressure Multi-Switch
I've been trying to interface between a **NodeMCU** and a **Dotech DPX200** Pressure Multi-Switch over **Modbus** RS485 using a MAX485 Module for the past few weeks, going through nearly every Modbus post on this site with no luck. As my access to the multi-switch can be limited at times, I've also tried using several simulators like ModScan64, Simply Modbus Master/Slave, Modbus Poll etc. but could get none to work.

I'd like to know if the Modbus device's Slave ID has to be set on the device itself or the NodeMCU? Also to get the "Display of low pressure value" the address given in the manual is 40023. How would I write the NodeMCU code to read that value using either the ModbusRtu, ModbusMaster or any other appropriate library?

---

I've added the DPX200's Manual link with my NodeMCU script and wiring diagram, and would appreciate any help from you.

```
#include <ModbusMaster.h>
#define MAX485_TX_ENABLE  12

int myInts[6];
ModbusMaster node;

void preTransmission(){
  digitalWrite(MAX485_TX_ENABLE, 1);
}

void postTransmission(){
  digitalWrite(MAX485_TX_ENABLE, 0);
}

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600, SERIAL_8N1);
  pinMode(MAX485_TX_ENABLE, OUTPUT);
  digitalWrite(MAX485_TX_ENABLE, 0);
}

void loop(){
  uint16_t k = 0,Status;
  node.begin(1, Serial1); //Slave ID = 1?
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
  Serial.println(i);
  Status = node.readHoldingRegisters(0x0023, 5); //Since address is 40023 to 40027
  if ( (Status == node.ku8MBSuccess) ){
     Serial.print("\nIDK: ");
     //Serial.println(node.getResponseBuffer(0));
     for (k = 0; k <= 5; k++ ){
        Status = node.readHoldingRegisters(k, 1);
        Serial.println(node.getResponseBuffer(0));
        delay(0);
     }
  }
}

```

# Answer
Now you have `node.begin(1, Serial1)`, but you can't use Serial1 for RS485 because Serial1 doesn't have RX pin

According to the picture you wired the adapter to RX/TX pin of Serial, but this pins are wired on board to USB for communication with the computer (upload and Serial Monitor). You can't use Serial for RS485 adapter while you are using it for debug prints.

You can use SoftwareSerial fo example on D1/D2 for RS485.

Or if you have an USB-to-TTL-Serial adapter then you can use Serial1 for debug prints and Serial for RS485
> 0 votes

---
Tags: nodemcu, rs485, modbus
---


title: LED blinking issue

text:
# Question
Title: LED blinking issue
i made a distance measuring circuit with different led for different distance ranges

```
#define trigPin 13
#define echoPin 12
#define BPin 7
#define piezoPin 9
#define RPin 4
#define GPin 8

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(BPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  pinMode(RPin, OUTPUT);
  pinMode(GPin, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance >= 200 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(1000);
  {
    if (distance <= 25 || distance <= 0) {
      digitalWrite(RPin, HIGH);
    }
    else {
      digitalWrite(RPin, LOW);
    }
  }

  {
    if (distance >= 25 && distance <= 50) {
      digitalWrite(GPin, HIGH);
    }
    else {
      digitalWrite(GPin, LOW);
    }

    {
      if (distance >= 50 && distance <= 75) {
        digitalWrite(GPin, HIGH);
      }
      else {
        digitalWrite(BPin, LOW);
      }

      {
        if (distance >= 75 && distance <= 100) {
          digitalWrite(BPin, HIGH);
        }
        else {
          digitalWrite(GPin, LOW);
          {
            {
              if (distance >= 100 && distance <= 200) {
                digitalWrite(piezoPin, HIGH);
              }
              else {
                digitalWrite(piezoPin, LOW);
              }
            }
          }
        }
      }
    }
  }
}

```

everything is working fine except Gpin it is blinking please help me i am also uploading link to download my .ino file link; https://www.datafilehost.com/d/e19b35d5

# Answer
> 0 votes
This is your code without unnecessary brackets:

```
#define trigPin 13
#define echoPin 12
#define BPin 7
#define piezoPin 9
#define RPin 4
#define GPin 8

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(BPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  pinMode(RPin, OUTPUT);
  pinMode(GPin, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance >= 200 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(1000);

  if (distance <= 25 || distance <= 0) {
    digitalWrite(RPin, HIGH);
  }
  else {
    digitalWrite(RPin, LOW);
  }

  if (distance >= 25 && distance <= 50) {
    digitalWrite(GPin, HIGH);
  }
  else {
    digitalWrite(GPin, LOW);
  }

  if (distance >= 50 && distance <= 75) {
    digitalWrite(GPin, HIGH);
  }
  else {
    digitalWrite(BPin, LOW);
  }

  if (distance >= 75 && distance <= 100) {
    digitalWrite(BPin, HIGH);
  }
  else {
    digitalWrite(GPin, LOW);
    if (distance >= 100 && distance <= 200) {
      digitalWrite(piezoPin, HIGH);
    }
    else {
      digitalWrite(piezoPin, LOW);
    }
  }
}

```

Using the ternary operator you can write some if statements easier:

```
#define trigPin 13
#define echoPin 12
#define BPin 7
#define piezoPin 9
#define RPin 4
#define GPin 8

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(BPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  pinMode(RPin, OUTPUT);
  pinMode(GPin, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance >= 200 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(1000);

  digitalWrite(RPin, (distance <= 25 || distance <= 0) ? HIGH : LOW);
  digitalWrite(GPin, (distance >= 25 && distance <= 50) ? HIGH : LOW);

  if (distance >= 50 && distance <= 75) {
    digitalWrite(GPin, HIGH);
  }
  else {
    digitalWrite(BPin, LOW);
  }

  if (distance >= 75 && distance <= 100) {
    digitalWrite(BPin, HIGH);
  }
  else {
    digitalWrite(GPin, LOW);
    digitalWrite(piezoPin, (distance >= 100 && distance <= 200) ? HIGH : LOW);
  }
}

```

Some remarks to think about that helps you solve your sketch (and is the reason why your GPin may blink):

1. The line part `(distance <= 25 || distance <= 0)` can be rewritten to `(distance <= 25)` since if a value is less/equal than 0, it automatically is less/equal than 25.
2. You set based one a condition a pin to HIGH or another pin to LOW, I would expect both pins to change, or the same pin. But I don't know your requirements.
3. The 'edge' values (e.g. 25, 50, 75) fall in multiple conditions, you probably want to exclude the end edge. It is a sort of guideline to include the start and exclude the end, e.g. `if (distance >= 50) && (distance < 75)`.

In your case you probably are best of checking the distance like this:

```
if (distance < 0)
{
   ...
}
else if (distance < 25)
{
   // 0 <= distance < 25)
   ...
}
else if (distance < 50)
{
   // 25 <= distance < 50)
}
...

```

or do it the other way around:

```
digitalWrite(GPin, 'condition in which GPin should be on' ? HIGH : LOW);
digitalWrite(BPin, 'condition in which BPin should be on' ? HIGH : LOW);

```

e.g. when you want the GPin to be on when between 0 and 25:

```
digitalWrite(GPin, ((distance >=0) && (distance < 25) ? HIGH : LOW);

```

---
Tags: programming
---


title: OTA push sketch to NodeMCU

text:
# Question
Title: OTA push sketch to NodeMCU
Similar questions regarding Arduinos mention the existence of tools that would enable the pushing of sketch updates to NodeMCU via WiFi / OTA (Over The Air).

Does this proceed? If so, please indicate the proper tools.

# Answer
> 1 votes
Arduino IDE supports upload to a network port. Network ports are detected with mDns and made available in Tools\>Port menu.

The ArduinoOTA library bundled with the esp8266 Arduino boards package supports upload from IDE with 'network port' over WiFi. See the example of the ArduinoOTA library available in Examples menu in IDE.

# Answer
> 0 votes
Yes, there exist methods to update codes through OTA in Wifi-modules/NodeMCU. You will first need to allot an IP address to your device which will later be used as a port to carry out OTA transmission. Look out to this tutorial-https://circuitdigest.com/microcontroller-projects/esp8266-ota-update-programming-using-arduino-ide

---
Tags: wifi, nodemcu
---


# Question
Title: Please help me combine the two codes for DHT11 and SW-420 Vibration sensor for arduino in one program
The following is the code used for DHT11 Temperature and Humidity sensor:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 0, 1, 2, 3);
byte degree_symbol[8] =
              {
                0b00111,
                0b00101,
                0b00111,
                0b00000,
                0b00000,
                0b00000,
                0b00000,
                0b00000
              };
int gate=11;
volatile unsigned long duration=0;
unsigned char i[5];
unsigned int j[40];
unsigned char value=0;
unsigned answer=0;
int z=0;
int b=1;
void setup()
{

lcd.begin(16, 2);
 lcd.print("Temp = ");
 lcd.setCursor(0,1);
 lcd.print("Humidity = ");
 lcd.createChar(1, degree_symbol);
 lcd.setCursor(9,0);
 lcd.write(1);
 lcd.print("C");
 lcd.setCursor(13,1);
 lcd.print("%");
}

void loop()
{

 delay(1000);
 while(1)
 {
  delay(1000);
  pinMode(gate,OUTPUT);
  digitalWrite(gate,LOW);
  delay(20);
  digitalWrite(gate,HIGH);
  pinMode(gate,INPUT_PULLUP);//by default it will become high due to internal pull up
 // delayMicroseconds(40);

  duration=pulseIn(gate, LOW);
  if(duration <= 84 && duration >= 72)
  {
      while(1)
      {
        duration=pulseIn(gate, HIGH);

        if(duration <= 26 && duration >= 20){
        value=0;}

        else if(duration <= 74 && duration >= 65){
        value=1;}

        else if(z==40){
        break;}

        i[z/8]|=value<<(7- (z%8));
        j[z]=value;
        z++;
      }
    }
answer=i[0]+i[1]+i[2]+i[3];

if(answer==i[4] && answer!=0)
{
lcd.setCursor(7,0);
lcd.print(i[2]);
lcd.setCursor(11,1);
lcd.print(i[0]);
}

z=0;
i[0]=i[1]=i[2]=i[3]=i[4]=0;
 }
}

```

The following is the code for SW-420 Sensor:

```
int LED_Pin = 13;
int vibr_Pin =3;

void setup(){
  pinMode(LED_Pin, OUTPUT);
  pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurment
  Serial.begin(9600); //init serial 9600
 // Serial.println("----------------------Vibration demo------------------------");
}
void loop(){
  long measurement =TP_init();
  delay(50);
 // Serial.print("measurment = ");
  Serial.println(measurement);
  if (measurement > 1000){
    digitalWrite(LED_Pin, HIGH);
  }
  else{
    digitalWrite(LED_Pin, LOW);
  }
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

```

Assuming the DHT11 Pin configuration remains unchanged and you can change the pin configurations for SW-420 vibration sensor, please give me a combined code for the two sensors to display results in one program. Thanks a lot.

# Answer
There are multiple threads on how to combine two different sketches. One of the main things you have to do is refactor your code to get rid of calls to `delay()`. Do a Google search on `Arduino blink without delay` and read one of the tutorials you find. The idea is to make a call to the `millis()` function for each thing you want to do on a time intervl, save the current millis count, and then wait until the new value of millis() is greater than the saved value by your desired time interval. By doing that, your code does a very fast series of checks:

"is it time to do `<thing 1>` again?"

"Is it time to to `<thing 2>` again?"

"What about `<thing 3>`"

And repeats.

Then it doesn't freeze the rest of your sketch waiting for time to pass. (That is what `delay()` does. Everything stops until the delay time has passed, which is bad.)
> 2 votes

---
Tags: arduino-uno, programming, sketch, temperature-sensor
---


# Question
Title: Is there an Arduino motor shield library?
I have an old motor shield but can see the revision 3 is still being sold: https://store.arduino.cc/arduino-motor-shield-rev3

When I follow the link for "Getting Started section" the page lists a lot of shields but not the motor shield. I must be missing something really obviously but I can't find a library for the motor board.

I'm trying to drive 2 DC motors.

# Answer
> 0 votes
From Chrisl's comment: https://github.com/gallingern/arduino-motor-shield-r3

You don't really need a library though as the code is simple enough:

```
void setup() {

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

}

void loop(){

  //forward @ full speed
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A
}

```

From here.

---
Tags: arduino-motor-shield
---


# Question
Title: ESP8266 official library post request returns 400
Every time I try the post request I get a 400 error but the JSON and URL are identical to those that I used on an online API tester and it worked every time there. I am running this program in the official Arduino IDE and most of this code was taken from the ESP8266 official library here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h

```
if (http.begin(client, host)) {  // HTTP

  http.addHeader("Content-Type", "application/json");
  // Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  // int httpCode = http.GET();
  String request = "{ \"temperature\": 27.0, \"humidity\": 43 }";
  Serial.print("[HTTP] POST...\n");
  int httpCode = http.POST(request);

```

# Answer
> 1 votes
400 is a HTTP error "Bad request" sent by the HTTP server. Possible reasons for this error are malformed HTTP request line, malformed HTTP request headers, missing empty line after the last HTTP header and a request to 'secure' port without encryption.

In your case the HttpClient library constructs the HTTP request so there should be no error. Only thing you supply for the request is the URL in your case it is the variable `host`. As we cleared in comments, your URL started with https. The HttpClient library parsed the url, detected the https protocol and used the secure port 443. But the underlying networking Client object was not SSL so it didn't encrypt the request.

---
Tags: esp8266, http
---


# Question
Title: Help understanding how avrdude works with ArduinoISP and why its not working for me
I am trying to use avrdude with a Mega2560 running ArduinoISP

Note: I have the 10uF cap on the Mega2560 RESET line as described by Ardunio.

Also, I am using avrdude/6.3 on Windows 10. The Mega2560(ArduinoISP) is connected to the PC using an a USB cable - connection is COM8.

I have a couple of tasks I want to do

1. Update the firmware on my USBASP
2. Load Arduino boot on ATTINY85 dev board.

I started with Arduino IDE but moved to avrdude to better understand the problem

For #1: Wired it per https://www.arduino.cc/en/Tutorial/ArduinoISP

```
AVR-ISP pin     MEGA-ISP pin
6/10 (name)

1/9 (MISO)      50
2/2 (VCC)       VCC
3/7 (SCK)       52
4/1 (MOSI)      51
5/5 (RESET)     53
6/10 (GND)      GND

```

I tried using the command:

```
avrdude -c arduino -p m8 -P COM8

```

I get the error

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xed
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

avrdude done.  Thank you.

```

--UPDATE-- The error above was caused by not setting the BAUD rate. Now I get:

```
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.

```

What I really want to know is more of how this process works so I can better understand it and be able to debug the issues.

1. Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?
2. What does "stk500" mean? Is that the programming protocol, the ISP protocol, or something all together different?
3. Is this all documented somewhere?

# Answer
The target board was not reset.

The "Arduino as ISP" sketch uses pin 10 to reset the target, not the SS pin. So even on Mega, wire reset of target to pin 10, not to pin 53.

> Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?

the first error "not in sync" is a problem with communication with the programmer. it was caused by wrong baud rate. the "invalid signature" is a response from the programmer about target. if the signature could be read avrdude would print the target MCU type. all zeros signature is when the target doesn't answer. so check the wiring.

> What does "stk500" mean? Is that the programming protocol, the ISP protocol, or something all together different?

yes it is a ISP programming protocol. the "Arduino as ISP" implements only this protocol

> Is this all documented somewhere?

this is AVR MCU world, not Arduino. you can google avrdude reference, stk500 reference etc
> 3 votes

---
Tags: avr, avrdude, isp, atmega2560, arduinoisp
---


# Question
Title: Writing Data through Pin at certain frequency
I have an Arduino UNO which is connected to an KLZ25 board, the Arduino sends an 1MHz Clock at Pin 9 and now I should write the PDM-Data with 1 Mhz at pin 8. But i don't know how to write with such a speed, because if I write in the Loop:

```
loop{
digitalWrite(1);
digitalWrite(0);
}

```

I get only a frequency of 36Khz, I know it depends on the count of commands in the loop, but I don't know how to write with a certain frequency in my case 1Mhz.

I get the PDM-Data (pulse density modulation) in form of 1 and 0 from a python script on a Host-PC and now I want to stream the Data with 1MHz to an other developer board which makes further calculation with the PDM-Data. I store the PDM-Data in queues because I have not enough memory to store the whole Data.

Does anybody know how to write PDM-Data with a 1MHz frequency to an output pin ?

# Answer
> 2 votes
If I understand correctly, you want to output a synchronous serial bit stream at 1 MHz. Something like this:

```
        ___     ___     ___
clk  __/   \___/   \___/   \___⋅⋅⋅
     ______ _______ _______ ___
dat  __D0__X___D1__X___D2__X___⋅⋅⋅

```

where the data bits come from the PC.

If you want this to be a continuous bit stream, it will not be easy to generate on an Arduino Uno.

## Receiving the data

Since the data comes from the PC, it comes presumably through the serial link. You have to account for the fact that this link adds a start bit and a stop bit to every byte. Thus, you have 10 bits on the wire for every 8 bits of actual data. Since you have to sustain 1 Mb/s average of actual data, this means that you must configure the serial port for at least 1.25 Mb/s. However, the only baud rate higher that 1 Mb/s supported by the Arduino Uno is 2 Mb/s.

Does your PC support this baud rate? Is the communication reliable at this speed?

If the speed is too high, I would suggest you try to have the PC send the data as PCM at a lower speed, and have the Arduino handle the PCM → PDM conversion.

## Transmitting the data

This data format is very similar to an SPI transmission. Then, the SPI hardware port seems like the easiest way to generate it. However, the SPI transmitter on the Uno is *not* double-buffered. This means that you have to wait for the current byte transmission to be finished before providing the next byte to the SPI hardware. This in turn means that you will inevitably have small delays between consecutive bytes, and one out of every 8 clock cycles will be stretched beyond the expected 1 µs. If this unsteadiness is acceptable for your application, then do use the SPI transmitter. If not, you will have to find another solution.

The serial port on the Uno has a special mode of operation where it behaves like a master SPI port. Unlike the actual SPI port, this port is double-buffered, which makes it possible to send a continuous bit stream with a steady clock. The problem is, you cannot use this mode for transmission and at the same time use the serial port receiver in its regular asynchronous mode. Thus you will not be able to receive the data from the PC when using this mode. If you can manage to route the PC → Arduino communication through SPI, this mode of operation of the serial port may be a good choice.

If none of the options above works for you I suggest, as last resort, to generate the bitstream entirely by software. The timings are tight, as each level of the clock has to be held for only 8 CPU cycles. But it is likely doable in hand-written assembly, provided that interrupts are disabled. Here is roughly how I may try to do that:

```
    in output, _SFR_IO_ADDR(PORT_OUT)   ; save a copy of the port reg.

loop:
    lds data, _SFR_MEM_ADDR(UDR0)       ; load data from USART

    ; output bit 0
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 0                         ; save data[0]
    bld output, 0                       ; load it into output[0]
    ; no delay needed here
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6                             ; assumed to be a macro
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; output bit 1
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 1                         ; save data[1]
    bld output, 0                       ; load it into output[0]
    delay 4
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; etc...

    rjmp loop

```

The code above assumes the UART is synchronized with the output stream, which will likely not be the case in reality. Your real application may then be more complex, and you will have to make that extra complexity fit within the delay slots above.

Note that if you handle the PCM → PDM conversion on the Arduino the resulting code may end up being simpler, as you will be able to read the UART at every loop iteration without worrying about synchronization. I have written a program that does something very similar a while ago, and I just pushed it to GitHub for you to take a look: avr-dac: Turn an AVR into a 1-bit D/A converter. Note that this program is meant to be usable on AVRs without a hardware UART. It expects the PCM data to be fed in the fashion of a shift register. Using the UART would make the program simpler.

---
Tags: arduino-uno, frequency, sound
---