# Question
Title: ESP-01 Deep Sleep not waking up properly
I have a temperature/humidity project using an ESP-01 and DHT11. I want to be able to put t into deep sleep to preserve battery life. I have soldered a wire from GPIO16 to RST.

```
#include <SimpleTimer.h>  //https://github.com/jfturcot/SimpleTimer
#include <ESP8266WiFi.h>
#include <PubSubClient.h>  //https://github.com/knolleary/pubsubclient
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>  //https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA
#include "DHT.h"

//USER CONFIGURED SECTION START//
#define DHTPIN 2     // what digital pin we're connected to

const char* ssid = "mySSID";
const char* password = "password";
const char* mqtt_server = "mqttserverip";
const int mqtt_port = 1883;
const char *mqtt_user = "usser";
const char *mqtt_pass = "pass";
const char *mqtt_client_name = "DryerMCU"; // Client connections can't have the same connection name
//USER CONFIGURED SECTION END//

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);
SimpleTimer timer;

bool boot = true;
int status = WL_IDLE_STATUS;

//Functions
void setup_wifi()
{
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void getTemperature()
{
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");

  char temperature[50];
  char humidity[50];

   // Update temperature and humidity
  String temp_str = String(f);
  temp_str.toCharArray(temperature, temp_str.length() + 1);
  client.publish("dryer/temperature", temperature);

  String hum_str = String(h);
  hum_str.toCharArray(humidity, hum_str.length() + 1);
  client.publish("dryer/humidity", humidity);

}

void setup() {
  Serial.begin(38400);
  delay(2000);
  Serial.println("Booting");

  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  getTemperature();

  Serial.println("Going to sleep");
  ESP.deepSleep(10000000,RF_DEFAULT);
}

void loop() {

}

```

When I start it up it takes one measurement, goes to sleep and then wakes up, but nothing happens once it wakes up. Serial output:

```
Booting

Connecting to SSID
  ......
WiFi connected
IP address:
mqttip
Humidity: 51.00 %   Temperature: 20.00 *C 68.00 *F  Heat index: 19.39 *C 66.90 *F
Going to sleep

ets Jan  8 2013,rst cause:5, boot mode:(3,7)

ets_main.c

```

# Answer
*In the question the OP said:*

> I have soldered a wire from GPIO16 to RST.

*But, I'm going to post an answer for the people who find this question and need the ESP-01 modification instructions in order to wake an ESP-01 module up from deep-sleep:*

The ESP8266 mounted on an ESP-01 board will not wake up from deep-sleep because the ESP8266 wake up signal is not connected to the reset pin of the ESP8266 on an ESP-01 board. You need to add this connection which can be difficult for most people. You can see the modification in this picture:  ...which comes from this instructables posting.

If this is too difficult, consider using a different ESP8266 board which brings these ESP8266 pins to board edge connectors.
> 1 votes

# Answer
I guess you have a race condition between automatic connection to WiFi by the Espressif SDK and your WiFi.begin(). You have two options how to solve it.

**1. option:** Don't use WiFi.begin in this sketch. Use an utility sketch to set the SSID and password and the SDK remembers it persistent on flash. Then it is able to connect fast to WiFi specially on reset, because it has the WiFi channel number in RTC memory which is not cleared at reset (only on power down).

**2. option:** turn of remembering of the SSID and password and the automatic connection at start. Then the esp8266 will connect to the WiFi only with your `WiFi.begin` call. The commands are `WiFi.persistent(false)` and `WiFi.setAutoConnect(false)`.

You can turn of the SoftAP too. At default it starts automatically. The command is `WiFi.softAPdisconnect()`
> 0 votes

---
Tags: esp8266
---


# Question
Title: Unable to compile SimpleTimer code - Exit status 1
I downloaded the SimpleTimer library from the Arduino's library manager and navigated to Arduino Playground website for some sample code for testing - SimpleTimer - Arduino Playground. After copying the following code into the Arduino IDE:

```
#include <SimpleTimer.h>

// the timer object
SimpleTimer timer;

// a function to be executed periodically
void repeatMe() {
    Serial.print("Uptime (s): ");
    Serial.println(millis() / 1000);
}

void setup() {
    Serial.begin(9600);
    timer.setInterval(1000, repeatMe);
}

void loop() {
    timer.run();
}

```

I receive the following error:

```
exit status 1
no matching function for call to 'SimpleTimer::setInterval(int, void (&)())'

```

Please help me out here as I am doing everything according to the instructions given in the arduino playground page of SimpleTimer.

# Answer
> 1 votes
There are quite a few Arduino libraries called “SimpleTimer”. According to arduinolibraries.info, the one you get through the library manager is Alexander Kiryanenko's SimpleTimer. The one described in Arduino Playground is Marcello Romani's version. You should try the examples that come with the specific library you install.

---
Tags: timers
---


# Question
Title: Distance Measurement - between 6 points, individually moving in (almost) any direction within 1m
I'm trying to find a solution for a given task in a problem I want to solve. Assume I have 6 individual Points in a 3D environment of about 1m³. Each point will be able to change position (almost) freely. Is there a way I can get the information of which distance each point is to any of the remaining 5 points? Background Idea for understanding: Say its 2 wooden triangles (one of those points on each angle) and I need to calculate how far and in which direction one is moving from or towards the other. By comparing all those distances, direction and step-width may be easily calculated. Are there like "coded" distance-sensors so they don't mix their signals? Any thoughts highly appreciated.

# Answer
You may try to implement some kind of ultrasonic transponders. The emitter sends a code addressing a specific receiver. Upon recognizing its address, the receiver replies after a short, fixed delay. The emitter measures the time it took the response to reach it, and from there computes the distance.

You may need some kind of omnidirectional transducers (e.g. this models) if you want the measurement to work in any direction. And also a protocol to avoid several emitters talking at the same time.

This seems to me like a very complex project though.
> 1 votes

# Answer
The vertices of two (wooden) triangles already constrains the problem - in a positive way - since the inter-point distances of each triangle's vertices is constant. If they were 6 individual, free-floating points, the job would be that much more complex -- 30 unknown distances (each point to each other point), instead of only 18 (each vertex to each of 3 vertices on the other triangle). That's the math part.

The technology part - what kind of sensors - will need more specifics to answer. For instance, ultrasonic sensors may have an interference problem with wooden triangles drifting about. Light and radar may have visibility issues - i.e., can't see certain of the points, depending on the physical shape and implementation of the drifting objects.
> 0 votes

---
Tags: sensors
---


# Question
Title: Need my code to do multiple commands when inputs are pressed
Hello all I am back again with another issue concerning a code for my job. The code I have been working on is meant to connect to a IP server where some options are listed and I can control the servo motor through there. The options listed are FORWARD, BACKWARD, STEP, and STOP. Each command makes the servo motor move a certain way but the problem I need help with is I need the edited the code to work with three input switches which when pressed in real time they allow the motor to make turns without the need of pressing any button on the server and so far the code is not working. They work with some LED lights which when the input switches are pressed also light up each input is paired with an output (LED) respectively and I tried to create a marker that when the input is pressed also says on the server that "LED1 is on" for example. Each input corresponds to an INPUT switch and each output corresponds to an LED light. The Pin variable corresponds to the motor. Here is the code in question:

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

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

WiFiServer server(80);

int Pin = 16; // GPIO13
int var = 0;
int D1 = 5;
int D2 = 4;
int D4 = 2;
int D5 = 14;
int D6 = 12;
int D7 = 13;
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;

Servo servoMotor;

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(D1, INPUT);
  pinMode(D2, OUTPUT);
  pinMode(D4, INPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, INPUT);
  pinMode(D7, OUTPUT);
  pinMode(Pin,INPUT);
  //pinMode(LED_BUILTIN, OUTPUT);
  //digitalWrite(LED_BUILTIN, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  //servoMotor.attach(Pin);

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  temp1 = digitalRead(D1);
  temp2 = digitalRead(D4);
  temp3 = digitalRead(D6);
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request
  if(temp1 == HIGH) {
    digitalWrite(D2,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(90);
  }
  else{
    digitalWrite(D2,LOW);
  }

  if(temp2 == HIGH) {
    digitalWrite(D5,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(-90);
}
  else {
    digitalWrite(D5,LOW);
}

  if(temp3 == HIGH) {
    digitalWrite(D7,HIGH);
}
  else{
    digitalWrite(D7,LOW);
}

  int value = LOW;
  while (value = LOW); {
  if (request.indexOf("/LED=ON") != -1)  {
    //digitalWrite(LED_BUILTIN, HIGH);
    value = HIGH;
    servoMotor.attach(Pin);
    servoMotor.write(0);
    delay(1000);

  }
  if (request.indexOf("/LED=OFF") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(180);
    delay(1000);

  }
  if (request.indexOf("/LED=STP") != -1){
      var = 1;
      while(var < 10){
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(90);
    delay(200);
    servoMotor.write(-90);
    delay(200);
    var=var+1;
    }
  }
  if (request.indexOf("/LED=STOP") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.detach();
    delay(1000);
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.print("Robot is now: ");

  if(value == HIGH) {
    client.print("Moving Forward");
  } else if(value == LOW) {
    client.print("Moving Backward");
  } else if(request.indexOf("/LED=STP") != -1) {
    client.print("Moving in Step");
  }else {
    client.print("Stopped");
  }

  if(temp1 == HIGH) {
    client.print("Led_1 is on");
  }else if (temp1 == LOW);{
    client.print("Led_1 is off");
  }

  if(temp2 == HIGH) {
    client.print("Led_2 is on");
  }else if (temp2 == LOW);{
    client.print("Led_2 is off");
  }

  if(temp3 == HIGH) {
    client.print("Led_3 is on");
  }else if (temp3 == LOW);{
    client.print("Led_3 is off");
  }

  client.println("<br><br>");
  client.println("<a href=\"/LED=ON\"\"><button>Move Forward </button></a>");
  client.println("<a href=\"/LED=STP\"\"><button>Step </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Move Backward </button></a><br />");
  client.println("<a href=\"/LED=STOP\"\"><button>STOP </button></a><br />");
  client.println("<a href=\"/Temp1=HIGH\"\"><Input>LED_1 ON </Input></a><br />");
  client.println("<a href=\"/Temp2=HIGH\"\"><Input>LED_2 ON </Input></a><br />");
  client.println("<a href=\"/Temp3=HIGH\"\"><Input>LED_3 ON </Input></a><br />");
  client.println("</html>");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
  }
}

```

P.S. I just edited the code to do the turns when the input is pressed for the third input it is supposed to make a random turn (either left or right the machine needs to decide on its own) and I am not sure how to write that in the code.

# Answer
Your code will only do anything if a client has connected to it because of this line

```
if (!client) {
    return;
  }

```

Your physical button will never do anything on their own unless a client has connected and has sent some data.

For the random direction you use a line like the following to randomly pick a direction

```
int direction = random(0,2) ? 1 : 0 ;

```

your direction variable will be with either 1 or 0 randomly
> 1 votes

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


# Question
Title: How to declare a pointer for arduino neopixels library so I can set it up in the setup function with dynamic variables?
I am using NeoPixel strips, and I want to be able to declare a pointer to them, but not initialize them until the `setup` function (because they will initialize with certain variables only made available in `setup`).

For simpler data types, I am just doing:

```
int totalNumColors = 4; //number of colors user can cycle through`
uint32_t* colorArray = new uint32_t[totalNumColors];
void setup() {
  for (int i=0;i<totalNumColors;i++){
    colorArray[i] = totalColorArray[i];
  }
}

```

How do I do this for NeoPixel strip intializers? I tried:

```
Adafruit_NeoPixel* pixels = new Adafruit_Neopixel;`

```

but I get the error:

```
expected type-specifier before 'adafruit neopixel'

```

# Answer
> 1 votes
You can assign the pointer to NULL, and in the `setup` function give it a value. Note you have to add () for the arguments, even if there are none like in this case. Also you have to include the library (but probably you did but not added in your question).

```
#include "Adafruit_NeoPixel.h"

Adafruit_NeoPixel* pixels = NULL;

void setup()
{
  pixels = new Adafruit_NeoPixel();
}

```

---
Tags: arduino-ide, c++, library, class, neopixel
---


title: Pseudo-code of a program

text:
# Question
Title: Pseudo-code of a program
I have written a code but I am facing a problem in pseudo-code that I am not able to change this code, so can anyone help me in translating the Arduino IDE program code to pseudo-code?

```
#define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include<DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "py0oKurvtk_Rv2GGkKtghpKqlxLQug8F";
char ssid[] = "Hostal1";
char pass[] = "shakajutt7867";
DHT dht(D4, DHT11);
SimpleTimer timer;
int Relay = D5;
int PIR = D3;
void sendSensor()
{
  float humi = dht.readHumidity();
  float temp = dht.readTemperature();
  int value = digitalRead(PIR);
  if (value == 1)
  {
  digitalWrite(Relay, HIGH);
  Serial.print("Detected");
  Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Detected");
  lcd.setCursor(0,1);
  lcd.print("T: ");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  else if (value== 0)
  {
    digitalWrite(Relay, LOW);
    Serial.print("Not Detected");
    Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Not Det");
  lcd.setCursor(0,1);
  lcd.print("T:");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  Blynk.virtualWrite(V7, value);
  Blynk.virtualWrite(V5, humi);
  Blynk.virtualWrite(V6, temp);
  delay(1500);
}
void setup()
{
  pinMode(Relay, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(Relay,LOW);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  lcd.begin(16,2);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  lcd.setCursor(0,0);
  timer.setInterval(1000L, sendSensor);
}
void loop()
{

  Blynk.run();
  timer.run();
}

```

# Answer
"Pseudo-code" isn't a programming language. It is just a term that we use when we write code that looks like code but can't be compiled, because it's half-English, half-code. You write pseudo code when you want to communicate to another human how code is supposed to work without getting bogged down in the details.
> 1 votes

---
Tags: programming
---


# Question
Title: Refreshing a web-page hangs after few times
I'm using a Nucleo F429ZI board and I wrote a sketch that enables a simple web-server:

```
#include <LwIP.h>
#include <STM32Ethernet.h>

const int WEB_PORT = 80;
EthernetServer server(WEB_PORT);
char buffer[1024];

void setup()
{
    Serial.begin(115200);
    // define variables
    Ethernet.begin(localIP, netmask, dns, gateway);
    server.begin();
}

void loop()
{
    processServer();
}

void processServer()
{
  String readString;
  EthernetClient client = server.available();
  if (client)
  {
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        readString += c;

        if (c == '\n')
        {
          if (readString.startsWith("GET"))
          {
            readString.remove(0, 4);
            int pos = readString.indexOf(' ');
            String path = readString.substring(0, pos);

            if (path == "/status") pageStatus(client);
            break;
          }
        }
      }
    }
    delay(1);
    client.stop();
  }
}

void pageStatus(EthernetClient client)
{
    sectionHeader(client, 2);
    client.println("<html>");
    client.println("<style>table{font-family: verdana, sans-serif;border-collapse: collapse;width: 30%;}");
    client.println("td, th{border: 1px solid #dddddd;text-align: left;padding: 8px;}tr:nth-child(even)");
    client.println("{background-color: #dddddd;}</style>");
    client.println("<table>");
    client.println("<tr><th>Servo</th><th>Position</th><th>Running</th><th>Initialized</th></tr>");

    for (int i = 0; i < getParamUInt8(P_SERVO_SIZE); i++)
    {
        sprintf(buffer, "<tr><td>%u</td><td>%d</td><td>%s</td><td>%s</td></tr>", i + 1, (int16_t) _servo[i].current, _servo[i].ended ? "NO" : "YES", _servo[i].initialized ? "YES" : "NO" );
        client.println(buffer);
    }
    client.println("</table>");

    client.println("<br><hr><br>");

    client.println("<table>");
    client.println("<tr><th>Led</th><th>PWM</th><th>Running</th></tr>");

    for (int i = 0; i < getParamUInt8(P_LED_SIZE); i++)
    {
        sprintf(buffer, "<tr><td>%u</td><td>%d</td><td>%s</td></tr>", i + 1, (int16_t) _led[i].pwm, _led[i].ended ? "NO" : "YES");
        client.println(buffer);
    }
    client.println("</table>");

    client.println("<br><hr><br>");

    client.println("<table>");
    client.println("<tr><th>Stepper</th><th>Position</th><th>Running</th></tr>");

    for (int i = 0; i < getParamUInt8(P_STEPPER_SIZE); i++)
    {
        sprintf(buffer, "<tr><td>%u</td><td>%d</td><td>%s</td></tr>", i + 1, (int16_t) _stepper[i].stepper.getCurrentPositionInMillimeters(), _stepper[i].stepper.motionComplete() ? "NO" : "YES");
        client.println(buffer);
    }
    client.println("</table>");
    client.println("</html>");
}

void sectionHeader(EthernetClient client, int refresh)
{
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    if (refresh) client.println("Refresh: 2");
    client.println();
    client.println("<!DOCTYPE HTML>");
}

```

As you can see in the `sectionHeader()` I want to refresh the page every 2 seconds. It works, but after 3 or 4 refreshes it hangs and I have to reset the whole board.

Of course with an embedded system I would use Ajax... here I thought reloading the page should be enough.

What might cause such a hang?

# Answer
The code you have that says `readString += c` has to allocate a whole new string whenever it runs out of space for more characters. All those allocations are filling up memory.

Instead of the String class, use a single C character array, e.g.

char s\[128\];

that is big enough for whatever you put in it.

If it helps, I wrote a simple arduino web server for my own project, and if you look at the code here that may give you ideas for how to implement this.
> 1 votes

---
Tags: ethernet, web-server
---


title: IDE finds multiple libraries

text:
# Question
Title: IDE finds multiple libraries
I don't understand Arudino IDE. Ever. This is a part of the compilation output:

```
Alternatives for ArduinoJson.h: [ArduinoJson@6.14.0]
ResolveLibrary(ArduinoJson.h)
  -> candidates: [ArduinoJson@6.14.0]
/home/mark/.arduino15/packages/STM32/tools/xpack-arm-none-eabi-gcc/9.2.1-1.1/bin/arm-none-eabi-g++ -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb @/tmp/arduino_build_952252/sketch/build_opt.h -c -Os -w -std=gnu++14 -ffunction-sections -fdata-sections -nostdlib -fno-threadsafe-statics --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -fno-use-cxa-atexit -I/home/mark/OSC -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/avr -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32 -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/LL -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/hid -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/cdc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Src -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/STM32F4xx -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Src -w -x c++ -E -CC -DSTM32F4xx -DARDUINO=10810 -DARDUINO_NUCLEO_F429ZI -DARDUINO_ARCH_STM32 "-DBOARD_NAME=\"NUCLEO_F429ZI\"" -DSTM32F429xx -DHAL_UART_MODULE_ENABLED -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/Core/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/ -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/DSP/Include -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/variants/NUCLEO_F429ZI -I/home/mark/Arduino/libraries/STM32duino_LwIP/src -I/home/mark/Arduino/libraries/STM32duino_STM32Ethernet/src -I/home/mark/Arduino/libraries/ArduinoJson/src /tmp/arduino_build_952252/sketch/OSC.ino.cpp -o /dev/null
Alternatives for FlexyStepper.h: [FlexyStepper@1.0.0]
ResolveLibrary(FlexyStepper.h)
  -> candidates: [FlexyStepper@1.0.0]
/home/mark/.arduino15/packages/STM32/tools/xpack-arm-none-eabi-gcc/9.2.1-1.1/bin/arm-none-eabi-g++ -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb @/tmp/arduino_build_952252/sketch/build_opt.h -c -Os -w -std=gnu++14 -ffunction-sections -fdata-sections -nostdlib -fno-threadsafe-statics --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -fno-use-cxa-atexit -I/home/mark/OSC -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/avr -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32 -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/LL -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/hid -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/cdc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Src -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/STM32F4xx -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Src -w -x c++ -E -CC -DSTM32F4xx -DARDUINO=10810 -DARDUINO_NUCLEO_F429ZI -DARDUINO_ARCH_STM32 "-DBOARD_NAME=\"NUCLEO_F429ZI\"" -DSTM32F429xx -DHAL_UART_MODULE_ENABLED -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/Core/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/ -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/DSP/Include -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/variants/NUCLEO_F429ZI -I/home/mark/Arduino/libraries/STM32duino_LwIP/src -I/home/mark/Arduino/libraries/STM32duino_STM32Ethernet/src -I/home/mark/Arduino/libraries/ArduinoJson/src -I/home/mark/Arduino/libraries/FlexyStepper/src /tmp/arduino_build_952252/sketch/OSC.ino.cpp -o /dev/null
Alternatives for Tasker.h: [Tasker@2.0]
ResolveLibrary(Tasker.h)
  -> candidates: [Tasker@2.0]

Più di una libreria trovata per "ArduinoJson.h"
Usata: /home/mark/Arduino/libraries/ArduinoJson
Più di una libreria trovata per "FlexyStepper.h"
Usata: /home/mark/Arduino/libraries/FlexyStepper
Più di una libreria trovata per "Tasker.h"
Usata: /home/mark/Arduino/libraries/Tasker

```

*Più di una libreria trovata* in English means *more than one library found*. And *Usata* means *Used*.

It's telling me it finds multiple libraries and selects one among them. Cool. But why it doesn't tell me *where* are the others?

Ok, I do:

```
$ sudo find / -name Tasker.h
/home/mark/Arduino/libraries/Tasker/Tasker.h

```

the same happens with the others. So, **where are the multiples libraries it finds**?

# Answer
> -1 votes
When you install your Arduino, 3 locations are used for your libraries:

* Installation folder
* Personal folder
* Boards folder

### Installation folder

This is the location where you installed Arduino. Normally they are:
On Windows: `%ProgramFilesDir%\Arduino\libraries`
On Linux: `/home/{USERNAME}/arduino-{VER}/libraries`
There, you can find 5-10 base libraries.

### Personal folder

Since, on each update, the installation folder is deleted, the sketches and custom libraries are stored in your personal data folder:
On Windows: `%userprofile%\documents\Arduino\libraries`
On Linux: `/home/{USERNAME}/Arduino/libraries/`
There, you can find all libraries that you downloaded from the IDE.

### Boards folder

Some libraries comes with your board and are board optimized. Arduino IDE will always check this folder, before it search for other libraries.
On Windows: `%LOCALAPPDATA%\Arduino15\packages\{BOARD}\hardware\{MODEL}\{VERSION}\libraries`
On Linux: `/home/{USERNAME}/.arduino15/packages/{BOARD}/hardware/{MODEL}/{VERSION}/libraries`

---

As I can see, you have a custom board selected. So the Arduino IDE search on the boards folder. If it can find a library it will take this one. If not, it will search on your personal folder and finally in the installation folder. I am not sure, but it could also get the newer one, if there is a version on it. Can't say how the right library is selected by the IDE.

If more than 1 are found, a warning message will appear. But it is just a message, you can just check if the right library was taken.

---
Tags: arduino-ide, library, ide
---


title: LSB/MSB and shiftOut

text:
# Question
Title: LSB/MSB and shiftOut
Here is the shiftOut function code from wiring\_shift.c

```
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
     uint8_t i;

     for (i = 0; i < 8; i++)  {
           if (bitOrder == LSBFIRST)
                 digitalWrite(dataPin, !!(val & (1 << i)));
           else
                 digitalWrite(dataPin, !!(val & (1 << (7 - i))));

           digitalWrite(clockPin, HIGH);
           digitalWrite(clockPin, LOW);
     }
}

```

Does this mean that least significant bit is on the left and most significant bit is on the right? Or LSBFIRST means that will be the last outputted bit so it will be "first" in outputted sequence?

One more thing

here is a sample code:

```
shiftOut(dataPin, clockPin, LSBFIRST, B00101001);
shiftOut(dataPin, clockPin, LSBFIRST, B11010011);

```

Why does this

```
union
{
     word uniform;
     byte separate[2];
} state;

state.uniform = 54057; // aka 11010011 00101001
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[1]);
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[0]);

```

have different output but if i swap last two lines it works correctly?

# Answer
> 0 votes
Integer values of the Arduino have the MSB left and the LSB right. The `shiftOut()` function let's you choose, how the order should be timewise. If you provide `LSBFIRST`, the function will start the transmit with the LSB (on the right) and then go left to the MSB. Otherwise it will start with the MSB and then go right to the LSB. So this effects only the time order of the bits, in that they get transmitted.

# Answer
> 0 votes
There is no "left" or "right" in a binary number, only in the human representation of that number.

It is traditional for us to place the most significant bit on the left, purely because that his how we represent other numbers - like 1234 (1 is the most significant digit, the thousands).

Given the pseudo-number `12345678` if you shift out LSBFIRST the 8 gets output first, then the 7, then the 6, etc. In MSBFIRST the 1 gets output first, then the 2, then the 3, etc.

---
Tags: arduino-ide, shift-register, bit
---


# Question
Title: Why does my circuit work only when I do not use the Serial port?
I am a newcomer to working with Arduinos (and circuits in general) so when I was tasked with making a simple push-button circuit to control an LED's state, and to send a message back using `Serial.println()` to show the button had been pressed, I noticed that the LED is dimly lit when I press the button to give it power. However, when I do not use the Serial port at all in my code, then it works perfectly as expected.

My code:

```
const int ledPort = 8;
const int detPort = 7;
void setup() {
  pinMode(ledPort, OUTPUT);
  pinMode(detPort, INPUT);
  digitalWrite(ledPort, HIGH);
  Serial.begin(9600);
}

void loop() {

  if (digitalRead(detPort) == HIGH) {
    digitalWrite(ledPort, LOW);
    Serial.println("9");
    delay(500);
  }
  else {
    digitalWrite(ledPort, HIGH);

```

My circuit:

https://i.stack.imgur.com/mYUYf.jpg

My Board: MEGA2560

# Answer
Your circuit is wired improperly.
It will be easiest for you to simply follow this official tutorial that will show you how to use a push button to turn on an LED. Even though you have a mega, it will work fine for you.

You will see a wiring picture there that is simplified:

Plus, the correct code is there:

```
/* Basic Digital Read
 * ------------------
 *
 * turns on and off a light emitting diode(LED) connected to digital
 * pin 13, when pressing a pushbutton attached to pin 7. It illustrates the
 * concept of Active-Low, which consists in connecting buttons using a
 * 1K to 10K pull-up resistor.
 *
 * Created 1 December 2005
 * copyleft 2005 DojoDave <http://www.0j0.org>
 * http://arduino.berlios.de
 *
 */

int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){
  val = digitalRead(inPin);  // read input value
  if (val == HIGH) {         // check if the input is HIGH (button released)
    digitalWrite(ledPin, LOW);  // turn LED OFF
  } else {
    digitalWrite(ledPin, HIGH);  // turn LED ON
  }
}

```

**Schematic Is Quite Important** also, as you attempt to look at the picture and build the circuit you discover how difficult it is to see how things are connected. That leads you to understand how important a simple schematic can be.
I've attempted to turn the pic from the arduino site into a schematic and my interpretation may be wrong or the actual circuit that the Arduino site has built may be wrong. If anyone has comments I will take them into account.

Trying to build from a picture of a circuit is terribly difficult and trying to debug your circuit from a picture is also. That's why when you submit a question you should submit a drawn schematic of how you have wired it up.

simulate this circuit – Schematic created using CircuitLab
> 0 votes

# Answer
Your circuit doesn't make sense to me, either :) I can't see where the LED is getting its ground from, in particular.

Try starting with the circuit shown here and report back!

Good luck!
> 0 votes

---
Tags: arduino-mega
---


title: how to combine two code of arduino uno

text:
# Question
Title: how to combine two code of arduino uno
```
int mamank=13;
void setup() {
  pinMode (mamank,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  if(sensorValue>550)digitalWrite(mamank,HIGH);
  else if(sensorValue<500)digitalWrite(mamank,LOW);
  delay(100);
}

```

-----------------------------------------------AND this code----------------------

```
int red=2;
int green=3;
int blue=4;

void setup () {
  pinMode (red,OUTPUT);
  pinMode (green,OUTPUT);
  pinMode (blue,OUTPUT);
  Serial.begin (9600);}

void loop() {
  // read the input on analog pin 0:
  int value = analogRead(A1);

  if (value > 500) {
    Serial.println("Very heavy Rain");
    digitalWrite (red,HIGH);
    digitalWrite(green,LOW);
    digitalWrite(blue,LOW);}
  else if ((value > 300) && (value <= 500)) {
    Serial.println("AVERAGE Rain");
    digitalWrite (green,HIGH);
    digitalWrite (red,LOW);
    }
  else{
    Serial.println("Dry Weather");
    digitalWrite (blue,HIGH);
    digitalWrite (red,LOW);
    digitalWrite (green,LOW);
  delay(100);
  }
  }

```

# Answer
Put the stuff before setup() together, fix any duplicates:

```
int mamank=13; <<< pin assignment? If yes, this can be byte
int red=2; <<< pin assignment? If yes, this can be byte
int green=3; <<< pin assignment? If yes, this can be byte
int blue=4; <<< pin assignment? If yes, this can be byte

```

Put the stuff in setup() together, fix any duplicates

```
void setup() {
pinMode (mamank,OUTPUT);
Serial.begin(9600);
pinMode (red,OUTPUT);
pinMode (green,OUTPUT);
pinMode (blue,OUTPUT);
Serial.begin(9600);  <<< duplicate, so delete this line
}

```

Put the stuff in loop() together, then check the desired functionality:

```
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
if (sensorValue>550) {
digitalWrite(mamank,HIGH);
}
else if (sensorValue<500) {
digitalWrite(mamank,LOW);
}
delay(100);
// read the input on analog pin 0:
int value = analogRead(A1);
if (value > 500) {
Serial.println("Very heavy Rain");
digitalWrite (red,HIGH);
digitalWrite(green,LOW);
digitalWrite(blue,LOW);
}
else if ((value > 300) && (value <= 500)) {
digitalWrite (green,HIGH);
digitalWrite (red,LOW);
}
else {
Serial.println("Dry Weather");
digitalWrite (blue,HIGH);
digitalWrite (red,LOW);
digitalWrite (green,LOW);
delay(100);
}

}

```
> 0 votes

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


title: How to use external libraries in CLion

text:
# Question
Title: How to use external libraries in CLion
I would like to use the external libraries that are downloaded by Arduino IDE into the default sketchbook location (*~/Arduino/libraries/*).

If you open Library Manager in Arduino IDE and if you install an external library (e.g **DHT sensor library 1.3.7** and its dependency **Adafruit Unified Sensor 1.0.3**) then it will be downloaded to the sketchbook location and you can use them freely in case of writing code in Arduino IDE.

However I really like auto code completion, managing source code in GIT repository, formatting source lines, etc. which functionalities are not provided by Arduino IDE, so I changed to CLion.

I have installed **CLion** and **Arduino Support 1.4.4 Plugin** and created a new Arduino Sketch Project.

## Project Structure:

```
.
+--cmake
   +--Platform
      +--Arduino.cmake
   +--ArduinoToolchain.cmake
+--libs
   +--Adafruit_Sensor
      +--Adafruit_Sensor.h
      +--library.properties
      +--README.md
   +--DHT
      +--DHT.cpp
      +--DHT.h
      +--DHT_U.cpp
      +--DHT_U.h
      +--keywords.txt
      +--library.properties
      +--README.md
+--CMakeLists.txt
+--first_test_project.ino
+--User_Setup.h

```

## first\_test\_project.ino:

```
#include <Arduino.h>
#include "User_Setup.h"
#include <libs/Adafruit_Sensor/Adafruit_Sensor.h>
#include <libs/DHT/DHT.h>

DHT *dht;

void setup() {
    dht = new DHT(7, DHT22);
}

void loop() {

}

```

So I have copied over the downloaded libraries from *~/Arduino/libraries* folder to the project folder under *libs* folder.

When I try to upload the code to Arduino Board I am getting the following in the log:

```
undefined reference to `DHT::DHT(unsigned char, unsigned char, unsigned char)'

```

Could somebody please explain what is wrong here.

Thank you very much!

# Answer
> 1 votes
In my opinion, the easiest way for the beginner is to use Platformio, it sets up CLion project automatically.

See docs for more info.

# Answer
> 0 votes
Did you add your libraries to the cmake files?

I don't have any experience with CLion but `undefined reference` normally means that the linker couldn't find the function/class your are using.

So make sure the libraries are compiled and the linker knows where to find the object files.

---
Tags: arduino-uno
---


# Question
Title: Setting Time Function With DS3232 Library
I am trying to set the time on my DS3231, then read that time on my arduino nano. This is for a digital clock project. I am using DS3232 library by JChristensen.

He has an example that can set the DS3231 time through the serial monitor, and it works great, but I don't understand how to implement it into my sketch.

I can confirm that once the external RTC is set using said example, I can then upload my code, and the clock holds time when unplugged. It's setting the time within my sketch that I can't figure out. I've been at it for about 8 hours today and read through the github resources.

Here's my code. Towards the top you can see my attempt to set the system time, then set it to the RTC.

```
 #include "SevSeg.h";
    #include <DS3232RTC.h>; //Jack Christensen
    https://github.com/JChristensen/DS3232RTC
    #include <Streaming.h>; //Mikal Hart https://github.com/janelia-
     arduino/Streaming
    //Also requires time library https://github.com/PaulStoffregen/Time

    SevSeg sevseg;

    void setup() {
    // put your setup code here, to run once:

    //Serial.begin(9600);

    setSyncProvider(RTC.get);// the function to get the time from the RTC
    setTime(8,0,0,20,1,2020);
    time_t t = now();
    RTC.set(now());

     byte numDigits = 4;
     byte digitPins[] = {2, 3, 4, 5};
     byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12};
     bool resistorsOnSegments = false; // 'false' means resistors are on digit
     pins
     byte hardwareConfig = COMMON_CATHODE; // See README.md for options
     bool updateWithDelays = false; // Default 'false' is Recommended
     bool leadingZeros = false; // Use 'true' if you'd like to keep the leading
     zeros
     bool disableDecPoint = true; // Use 'true' if your decimal point doesn't
     exist or isn't connected. Then, you only need to specify 7 segmentPins[]

     sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,
      resistorsOnSegments,
       updateWithDelays, leadingZeros, disableDecPoint);

    }

     void loop() {

    sevseg.setChars("hola");
    sevseg.refreshDisplay();

     if(millis()>6000) {

    int adj = 0;
    int timenumber;
    int hr = hourFormat12();
    int Min = minute();

    timenumber = (hr*100) + Min; //converts time into a number for the seven
    segment display

   sevseg.setNumber(timenumber);
   sevseg.refreshDisplay();
    }

    }

```

And JChristensen's Example Code:

```
// Arduino DS3232RTC Library
// https://github.com/JChristensen/DS3232RTC
// Copyright (C) 2018 by Jack Christensen and licensed under
// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Example sketch to display the date and time from a DS3231
// or DS3232 RTC every second. Display the temperature once per
// minute. (The DS3231 does a temperature conversion once every
// 64 seconds. This is also the default for the DS3232.)
//
// Set the date and time by entering the following on the Arduino
// serial monitor:
//  year,month,day,hour,minute,second,
//
// Where
//  year can be two or four digits,
//  month is 1-12,
//  day is 1-31,
//  hour is 0-23, and
//  minute and second are 0-59.
//
// Entering the final comma delimiter (after "second") will avoid a
// one-second timeout and will allow the RTC to be set more accurately.
//
// No validity checking is done, invalid values or incomplete syntax
// in the input will result in an incorrect RTC setting.
//
// Jack Christensen 08Aug2013

#include <DS3232RTC.h>      // https://github.com/JChristensen/DS3232RTC
#include <Streaming.h>      // http://arduiniana.org/libraries/streaming/

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

    // setSyncProvider() causes the Time library to synchronize with the
    // external RTC by calling RTC.get() every five minutes by default.
    setSyncProvider(RTC.get);
    Serial << F("RTC Sync");
    if (timeStatus() != timeSet) Serial << F(" FAIL!");
    Serial << endl;
}

void loop()
{
    static time_t tLast;
    time_t t;
    tmElements_t tm;

    // check for input to set the RTC, minimum length is 12, i.e. yy,m,d,h,m,s
    if (Serial.available() >= 12) {
        // note that the tmElements_t Year member is an offset from 1970,
        // but the RTC wants the last two digits of the calendar year.
        // use the convenience macros from the Time Library to do the conversions.
        int y = Serial.parseInt();
        if (y >= 100 && y < 1000)
            Serial << F("Error: Year must be two digits or four digits!") << endl;
        else {
            if (y >= 1000)
                tm.Year = CalendarYrToTm(y);
            else    // (y < 100)
                tm.Year = y2kYearToTm(y);
            tm.Month = Serial.parseInt();
            tm.Day = Serial.parseInt();
            tm.Hour = Serial.parseInt();
            tm.Minute = Serial.parseInt();
            tm.Second = Serial.parseInt();
            t = makeTime(tm);
            RTC.set(t);        // use the time_t value to ensure correct weekday is set
            setTime(t);
            Serial << F("RTC set to: ");
            printDateTime(t);
            Serial << endl;
            // dump any extraneous input
            while (Serial.available() > 0) Serial.read();
        }
    }

    t = now();
    if (t != tLast) {
        tLast = t;
        printDateTime(t);
        if (second(t) == 0) {
            float c = RTC.temperature() / 4.;
            float f = c * 9. / 5. + 32.;
            Serial << F("  ") << c << F(" C  ") << f << F(" F");
        }
        Serial << endl;
    }
}

// print date and time to Serial
void printDateTime(time_t t)
{
    printDate(t);
    Serial << ' ';
    printTime(t);
}

// print time to Serial
void printTime(time_t t)
{
    printI00(hour(t), ':');
    printI00(minute(t), ':');
    printI00(second(t), ' ');
}

// print date to Serial
void printDate(time_t t)
{
    printI00(day(t), 0);
    Serial << monthShortStr(month(t)) << _DEC(year(t));
}

// Print an integer in "00" format (with leading zero),
// followed by a delimiter character to Serial.
// Input value assumed to be between 0 and 99.
void printI00(int val, char delim)
{
    if (val < 10) Serial << '0';
    Serial << _DEC(val);
    if (delim > 0) Serial << delim;
    return;
}

```

# Answer
> 0 votes
I figured it out. You must first set the built in arduino RTC using the time library, then set the DS3232 from there. It did not work for my code before because it has to be called *outside* of the setup function.

For instance, I made a function that adjusts the hour:

```
void adjHr() { //hour adjustment function

if(millis() >= time_now + period){
        time_now += period;
        time_now = millis();
        setTime(hour()+1,minute(),second(),day(),month(),year());
        RTC.set(now());
    }

```

My setup function also includes:

```
setSyncProvider(RTC.get);

```

Allows the code to get time from the DS3232.

---
Tags: rtc
---


# Question
Title: Set the wall clock time or change GMT offset without ntp server?
I have been able to get the current time from an NTP server and set what appears to be an internal clock using the `configTime()` function from the ESP32 core. I can then get the current time with the function `getLocalTime()`.

I would like to be able to set the time returned by `getLocalTime()` from user input rather than from an NTP server. I would also like to be able to update the GMT Offset without needing to reconnect to the server.

How do I interact with the clock value used by `getLocalTime()`? Is there documentation for this clock somewhere?

---

per request the `SimpleTime` example from the ESP32 install:

```
#include <WiFi.h>
#include "time.h"

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

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

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

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
}

```

# Answer
The functions configTime and getLocalTime are from ESP32 core file esp32-hal-time.c. This wraps the ESP32 SDK functions. You can use the SDK functions to set the time and zone. They work with the RTC peripheral of the ESP32.

You can use setTimeZone to set the time zone.

The time.h is standard C time library. The ESP32 SDK makes it to work with the built in RTC (reference). To set the time it gets complicated. You would have to use undocumented SDK time functions.
> 3 votes

---
Tags: esp32, time
---


# Question
Title: Why are the PWM variables in this RC code snippet handled this way? What are the magic numbers?
```
tcommand=(pwm_value-480.0)/8.22;
flapmag=(pwm_value-880)/41.0+10;

```

In this piece of code used in arduino radio control aircraft, I don't understand why PWM value is subtracted and divided like this. This is not my code, it came from here. Any explanation would be of great help. I have read about PWM but all have different explanations.

```
//Arduino servo flap system
//copyright Steve Morris 10-25-16
#include <Servo.h>
volatile int pwm_value = 0;
volatile int prev_time = 0;
static int servo_comm1 = 0;
static int servo_comm2 = 0;
volatile int flapangle1 = 0;
volatile int flapangle2 = 0;
volatile int millisold = 0;
int millinow = 0;
float dt = 0;
float flapmag = 0;
static float flapdeg = 0;
float tcommand = 0;
float floattime = 0;
float temp = 0;
float glide_deg = -10.0;
static int pwm_value_temp = 0;
float omegadot = 0.0;
float thetadot = 0.0;
static float omega = 0.0;
static float theta = 0.0;
static float k0 = 1.0;
static float k2 = 10.0;
static float servo_zero1 = -4;
static float servo_zero2 = 0;

Servo myservo1, myservo2; // create servo object to control a servo

void setup() {
  //Serial.begin(115200);
  // when pin D2 goes high, call the rising function
  attachInterrupt(0, rising, RISING);
  myservo1.attach(5); // attaches the servo on pin 5 to the servo object
  myservo2.attach(6); // attaches the servo on pin 6 to the servo object
}
void loop() {

  millinow = millis();
  floattime = millinow / 1000.0;
  dt = (millinow - millisold) / 1000.0;
  millisold = millinow;

  tcommand = (pwm_value - 480.0) / 8.22;
  omegadot = k0 * tcommand - k2 * omega;
  thetadot = omega;
  flapdeg = sin(theta);
  theta = theta + omega * dt;
  omega = omega + omegadot * dt;

  flapmag = (pwm_value - 880) / 41.0 + 10;
  flapdeg = flapmag * sin(theta); //variable amplitude+freq

  flapangle1 = (int)((30.0 - flapdeg + servo_zero1) * 2.0 + 25.0);
  flapangle2 = (int)((30.0 + flapdeg + servo_zero2) * 2.0 + 25 .0);

  if (pwm_value > 930) {
    servo_comm1 = flapangle1;
    servo_comm2 = flapangle2;
  }

  //Glide Lock
  if (pwm_value < 910) {

    servo_comm1 = (int)((30.0 - glide_deg + servo_zero1) * 2.0 + 25.0);
    servo_comm2 = (int)((30.0 + glide_deg + servo_zero2) * 2.0 + 25.0);

  }

  myservo1.write(servo_comm1); // tell servo to go to position in variable 'pos'
  myservo2.write(servo_comm2); // tell servo to go to position in variable 'pos'

  //Serial.println(servo_comm1);
  //Serial.println(floattime);
  //Serial.println(dt);
  //Serial.println(flapangle);
  //Serial.println(flapdeg);
  //Serial.println(temp);
  //Serial.println(tcommand);
  //Serial.println(pwm_value);

}

void rising() {
  attachInterrupt(0, falling, FALLING);
  prev_time = micros();
}

void falling() {
  attachInterrupt(0, rising, RISING);
  pwm_value = micros() - prev_time;
}

```

# Answer
There is not enough context to be certain, but given the variable names I can assume that this is code from a sketch that receives information from an RC controller and is intended to control parts of some form of flying craft.

So with that in mind, let's take this line:

```
flapmag=(pwm_value-880)/41.0+10;

```

I assume that this is to calculate the amount the flaps should be extended or retracted.

RC controllers, or rather the receivers that pick up the signals, usually output a PWM signal (square wave with a variable duty cycle) where the duty cycle is directly related to the position of the joystick.

A joystick is usually zero in the center and goes plus or minus for up and down (or right and left). But you can't have a negative PWM value, since that makes no sense (how can you have a signal that is off for *less* that 0% of the time?!). So the output is "offset" by a certain amount (that's not quite true - actually the joystick is 0 for fully down, and 100% for fully up, with "0" being somewhere in the middle, so the offset is applied by the joystick, not the receiver, but that really doesn't matter for us right now).

So we have a signal that is at any time somewhere between 0% and 100%, with "zero" being somewhere in the middle. What actual value the "100%" is, or exactly where "zero" is, can vary depending on many many factors, so we'll just use "100" for the maximum, and "50" for the middle "zero" offset.

The first thing you want to do, then, is remove that "zero" offset. And that is as simple as subtracting it. With our example numbers above, if you subtract the "zero" offset of "50" from the incoming signal it now goes between -50 and +50 instead of 0 and 100. That now relates much better to how a joystick appears - 0-50 in an upwards direction (+) and 0-50 in a downwards direction (-).

And that is exactly what is happening with `pwm_value-880` in your code. The middle "zero" value of 880 is being subtracted from the incoming joystick position to give you an "up" or "down" value that is positive or negative respectively.

Next comes the division. This scales the incoming value to the right size for the device you are driving. In our example we have a ±50 signal. But what if our flaps require a ±10 signal to give the correct movement range. So simply dividing the value by 5 will change ±50 into ±10. That's exactly what the `/41.0` is doing - scaling the result to fit the range of the target device.

Then there's one final `+10` in there. This simply adds a small offset to the result. You can think of this as a "trim" value. It sets the actual "zero" point of the target device - in this case when the joystick is centered it means the flaps are set to a +10 position.

As to how the `pwm_value` itself is created, that is usually done through capturing the rising and falling edges of the incoming waveform from the receiver and timing how long the signal is in the HIGH or LOW state. That may be performed by some unspecified library.
> 5 votes

---
Tags: programming, pwm, code-review, remote-control
---


title: DS1307 Real-Time Clock

text:
# Question
Title: DS1307 Real-Time Clock
I am trying to make an Arduino project based on the Sparkfun DS1307 RTC (real-time clock).

There are a few issues with how Arduino libraries don't support checking if the Arduino board has been powered down and check for that.

Then using that as a conditional as to when the program should fall back to the compiled time if the RTC isn't set to a time yet because of something else.

When I power down the clock, it will automatic fall back to the compiled time every single time, regardless of what is currently on the RTC. Clearly this is not something you would want.

Edited - This is my current code. Keep in mind there are a few more changes I could do like take Byte zero declare out of the loop so it is still rough.

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

#define DS1307_ADDRESS 0x68

void setup() {
  Wire.begin();
  Serial.begin(9600);
  rtc.begin();
  if(false){
    //Should check RTC somehow to determine if should fallback to compiled time here.
    Serial.println("The DS1307 clock has lost power and reset to compiler's time");
    rtc.autoTime();
  }
}

void loop() {
  if(digitalRead(7)==LOW)
    printDate();
  delay(1000);
}

byte bcdToDec(byte val){
  return ((val/16*10) + (val%16));
}

void printDate(){
  rtc.update();
  Wire.beginTransmission(DS1307_ADDRESS);
  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  //Print the date like 3/1/1/11 23:59:59
  Serial.print(month);
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

```

# Answer
> 1 votes
DS1307 gives a square wave output which can be set to specific frequencies which is available in the datasheet. Initially the square wave output is disabled. You can enable it when you set the time. When you power up again, check for the square wave and if it is absent you can set the time again. This can be easily done by creating a timeout code and resetting the timeout timer in an interrupt. If square wave is present an interrupt will be generated accordingly and the timeout time period will be set to initial value. If the timeout time expires you set the clock. This can even track clock failures in real time. Also you can use the same interrupt to extract data from the RTC as square wave output can be configured to 1Hz and hence you can poll the RTC at every 1Hz and take the data from the RTC.

# Answer
> 0 votes
> There are a few issues with how arduino's libraries doesn't support checking if the arduino board has been powered down and check for that.

How is it supposed to do that? The board's powered down.

> When I powered down the clock. It will automatic fallback to compiled time every single time regardless of what is currently on RTC. Clearly this is not something you would want.

So don't have a compiled in time.

# Answer
> 0 votes
Easy. Here is one way to do it.

1. Read the clock off the rtc.
2. Wait a known period of time, based on the mcu frequency,
3. Read the clock off the rtc again.
4. Compare the two time reading and it should have advanced. If not, fall back to compiled time.

There are other ways to do it as well, like bor, or square wave output, interrupt on vbat line, ......

# Answer
> 0 votes
You could periodically store the date and time in the battery-backed SRAM in the DS1307. Every few seconds, once a minute, something like that. Upon sketch start, perhaps in setup(), read the current RTC time, compare to the stored time, if the current time is later than the stored time, you can do the math and see how long the Arduino has been down. Or use the Arduino's EEPROM to hold the last stored time if you are concerned about the RTC losing it's battery and resetting to it's default date and time, which would be earlier than the EEPROM time.

---
Tags: arduino-uno
---


# Question
Title: How to create an inverted PWM on the Due via software
Hello I am i need of a piece of code that lets me invert a PWM signal of two PWM pins on the due. Example D1 will be 101010 and D2 will be 010101. Is it possible?

Im pretty limited in my options because, doing it externally is not an option because there will be a time where a change in mode is needed and both pins will be sending signal independently. Manually pulling the pins High and Low is also not an option for me because this will make the code blocking other codes.

# Answer
> 1 votes
Not using the Arduino API, no. But you can by direct manipulation of the SAM3X8E registers.

You should study section 38 of the datasheet, where it mentions in the list of facilities:

> * Independent Complementary Outputs with 12-bit Dead-Time Generator (Also Called Dead-Band or Non-Overlapping Time) for Each Channel

---
Tags: pwm, arduino-due
---


title: Help with debugging code

text:
# Question
Title: Help with debugging code
This is NOT my code; was posted on Project Hub. I tried to use the code (humidity controller) but it returns an error on line 270:

```
else if (DHT.humidity >= setpoint + 3 and syson == true) { //if humidity is 3% above setpoint

```

Error: expected primary-expression before '.' token

The OP is not responding to comments and I'm no expert. Would appreciate if someone could help debug the code; Thanks!

```
       //HUMIDITY CONTROLLER 1.1
//written for NANO

//controls and displays relative humidity
//sesnor used is DHT11
//uses active-low relay module to control live lines for 2 standard electrical outlets
//uses i2c lcd to display humidity and humidity setting
//turns display off during inactivity
//setting is adjustable from 10%-90% using 2 buttons
//backlight of LCD is controlled by pin 4, connected to top LED jumper pin on i2c backpack
//serial communications to monitor to ensure all code is working.

//added: "system off" function - allows both outlets to be turned off

// █ G █ L █ O █ B █ A █ L █ S █
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <dht.h>

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

dht DHT;

#define DHT11_PIN A2

//buttons and variables to adjust calibration
int calupbtn = A0;
int calup;
int caldownbtn = A1;
int caldown;

//i2c PINS A4, A5

//pin for turning on humidifier relay
int humidifier = 3;
//pin for turning on the fan relay
int fan = 2;
//pin for turning on LCD backlights
int lcdlight = 4;

//calibration variable
int setpoint = 50;  //feedback setpoint.
bool calstate = false;  //enables calibration adjustments only when LCD is ON.

//backlight timing variables
int displtime = 12000;  //amount of time the display is to be on before turning off
unsigned long displtimeon;  //last recorded time display timer was reset
int calunlock = 0;   //loop counter for unlocking calibration

//sensor timing variables
unsigned long lastcheck;  //last time DHT was read
long interval = 30000;      //time between DHT readings

//system variables
bool syson = true;    //reference for system on/off.
byte systog = 2;       //even number toggles on, odds toggle off
int syslock = 0;     //loop counter for unlocking system toggle

// █ S █ E █ T █ U █ P █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █
void setup(){

  Serial.begin(9600);  //serial communication used to ensure code is working correctly.

  lcd.init();  //initialize LCD
  lcd.backlight(); //enable LCD backlight, but doesn't turn it on

  lastcheck = 0;
  digitalWrite(lcdlight, HIGH);
  Serial.println("STARTING");
  lcd.print("   STARTING");

  //pin assignments
  pinMode(calupbtn, INPUT);
  pinMode(caldownbtn, INPUT);
  pinMode(humidifier, OUTPUT);
  pinMode(fan, OUTPUT);
  pinMode(lcdlight, OUTPUT);
  delay(1000);

  //test fan
  lcd.setCursor(0,1);
  lcd.print("<FAN>     HMDFR  ");
  digitalWrite(fan, LOW);
  digitalWrite(humidifier, HIGH);
  delay(6000);
  //test humidifier
  lcd.setCursor(0,1);
  lcd.print(" FAN     <HMDFR> ");
  digitalWrite(fan, HIGH);
  digitalWrite(humidifier, LOW);
  delay(6000);
  //stop startup test
  digitalWrite(humidifier, HIGH);
  digitalWrite(fan, HIGH);
  lcd.clear();

  displtimeon = millis();

  int chk = DHT.read11(DHT11_PIN);
  lastcheck = millis();

  lcd.setCursor(0,0);
  lcd.print("Humidity: ");
  lcd.setCursor(13,0);
  lcd.print(DHT.humidity);
  lcd.setCursor(15,0);
  lcd.print("%  ");
  lcd.setCursor(0,1);
  lcd.print("setting: ");
  lcd.setCursor(13,1);
  lcd.print(setpoint);
  lcd.setCursor(15,1);
  lcd.print("%  ");
  delay(100);
}

// █ L █ O █ O █ P █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █
void loop(){

  //check calibration buttons
  calup = digitalRead(calupbtn);
  caldown = digitalRead(caldownbtn);

  if(calup == HIGH and caldown == HIGH){  //--------SYSTEM TOGGLE
    syslock ++;
    Serial.println(syslock);
    if(syslock == 20){  //if both buttons held down for this many loops
      systog++;
      if(systog % 2 == 1){  //--------SYSTEM OFF
        syson = false;
        digitalWrite(fan, HIGH);
        digitalWrite(humidifier, HIGH);
        digitalWrite(lcdlight, HIGH);
        Serial.println("SYSTEM TURNED OFF");
        lcd.clear();
        lcd.print("   SYSTEM OFF");
        lcd.setCursor(0,1);
        lcd.print("  hold both btns");
        delay(2000);
        lcd.setCursor(0,1);
        lcd.print("  to turn on    ");
        displtimeon = millis();
      }
      if(systog % 2 == 0){  //--------SYSTEM ON
        syson = true;
        Serial.println("SYSTEM TURNED ON");
        digitalWrite(lcdlight, HIGH);
        lcd.clear();
        lcd.print("   SYSTEM ON");
        delay(2000);
        lcd.clear();
        displtimeon = millis();
      }
      syslock = 0;
    }
  }
  else(syslock = 0);

  //read humidity at appropriate intervals
  if(millis() > lastcheck + interval and syson == true){  //read the DHT humidity
    int chk = DHT.read11(DHT11_PIN);
    lastcheck = millis();
    Serial.print("DHT read = ");
    Serial.print(DHT.humidity);
    Serial.print("%");
    Serial.println(" ");
    }

  //turn on the led lights when calibration buttons are pressed
  if(calup == HIGH xor caldown == HIGH){
    digitalWrite(lcdlight, HIGH);
    calstate = true;
    displtimeon = millis();  //set display timer
    Serial.println("cal btn ACTIVE");
    if(syson == false){
      digitalWrite(lcdlight, HIGH);
      lcd.clear();
      lcd.print("   SYSTEM OFF");
      lcd.setCursor(0,1);
      lcd.print("  hold both btns");
      delay(3000);
      lcd.setCursor(0,1);
      lcd.print("  to turn on    ");
      displtimeon = millis();
    }
  }

  if(calstate == true and syson == true){  //--------DISPLAY ROUTINE
    Serial.println("printing display");
    //display variables on LCD
    lcd.setCursor(0,0);
    lcd.print("Humidity: ");
    lcd.setCursor(13,0);
    lcd.print(DHT.humidity);
    lcd.setCursor(15,0);
    lcd.print("%  ");
    lcd.setCursor(0,1);
    lcd.print("setting: ");
    lcd.setCursor(13,1);
    lcd.print(setpoint);
    lcd.setCursor(15,1);
    lcd.print("%  ");
    delay(100);

    calunlock ++;
    //keeps calibration locked until display cycles 5 times after initially turned on
    //prevents adjustments on initial button press.
  }

//--------CALIBRATION ADJUSTMENTS
  if(calup == HIGH and caldown == LOW and calstate == true and syson == true){
    if(setpoint < 90 and calunlock > 5){
      setpoint = setpoint + 5;  //increase setpoint
      Serial.println("adj setpoint up");
    }
    Serial.println(setpoint);
    delay(100);
    displtimeon = millis();     //reset backlight timeout
  }

  if(caldown == HIGH and calup == LOW and calstate == true and syson == true){
    if(setpoint > 10 and calunlock > 5){
      setpoint = setpoint - 5;  //decrease setpoint
      Serial.println("adj setpoint dn");
      }
    Serial.println(setpoint);
    delay(100);
    displtimeon = millis();     //reset backlight timeout
  }

  if(millis() > displtimeon + displtime){  //-----------------BACKLIGHT TIMEOUT
    digitalWrite(lcdlight, LOW); //turn off the screen
    calstate = false;
    Serial.println("displ + backlights off");
    lcd.clear();
    calunlock = 0;  //lock calibration
  }

  if(millis() < lastcheck){
    lastcheck = millis();  //reset timers in a millisecond rollover
  }

                                      //--------SETPOINT ERROR PROCEDURE
  if(setpoint > 91 or setpoint < 9){  //in case setpoint is ever out of bounds
    Serial.println("O/B ERROR");
    digitalWrite(lcdlight, HIGH);
    lcd.clear();
    lcd.print("O/B ERROR");  //display error message on lcd
    lcd.setCursor(0,1);
    lcd.print("RESETTING");
    delay(1000);
    for(int count = 9; count >= 0; count = count - 1){
      lcd.setCursor(15,1);
      lcd.print(count);     //count down from 10
      delay(1000);
    }
    setpoint = 50;        //reset setpoint at 50.
    displtimeon = millis();
  }

  //turn on humidifier relay if below setpoint  --------RELAY CONTROL
  //RELAY MODULE IS ACTIVE LOW
  if(DHT.humidity <= setpoint - 3 and syson == true){  //if humidity is 3% lower than setpoint
    Serial.println("humidifier ON, fan OFF");
    digitalWrite(humidifier, LOW);  //turn on humidifier
    digitalWrite(fan, HIGH);
  }
  else if(DHT.humidity >= setpoint + 3 and syson == true){  //if humidity is 3% above setpoint
    Serial.println("humidifier OFF, fan ON");
    digitalWrite(humidifier, HIGH);  //turn on fan
    digitalWrite(fan, LOW);
  }
  else{
    Serial.println("all off");  //if humidity is within 3% of setpoint
    digitalWrite(humidifier, HIGH);  //turn both off
    digitalWrite(fan, HIGH);
  }
  //delay(700);  //un-comment for serial debugging

  Serial.print("setpoint = ");
  Serial.println(setpoint);

  //delay(700);  //un-comment for serial debugging
}

/*  WIRING DIAGRAMS
 https://66.media.tumblr.com/98426b566744beacdd42bc0221092b76/tumblr_pvr0u8kvZy1yrmjh9o1_1280.png
 */

```

# Answer
You have installed the Adafruit DHT library via the Arduino library manager

The source code does not work with that library. It is written to use the DHT library written by Rob Tillaart, named DHTLib. That library is not included in the Library Manager of the Arduino IDE. Instead, you have to download the library as a ZIP file and install it via Sketch / Include Library / Add .ZIP library.

I don't know why you have changed the source code in the meanwhile. Using DHTLib with the source code of revision 1 of your question works fine. In the meanwhile you have tried to adapt the code to match the Adafruit library, which eventually might be ok as well after some hard work. I suggest rolling back to the code of revision 1 and installing the correct library.
> 2 votes

---
Tags: debugging
---


title: GSM+GPS modules

text:
# Question
Title: GSM+GPS modules
Say, I need to track a vehicle using Arduino and a (GPS+GSM) module. Though GPS can be used to get Location of the Vehicle(and then sent using GSM), why would we even do it using GPS if we already have a GSM module. Can't GSM do both these tasks(getting location and sending it) . What's the use of using an extra module there?

I am new to network stuff, help me!

# Answer
> 1 votes
The GSM module can estimate it's location based on cell tower triangulation but if you want a more accurate location then you need to use a GPS.

---
Tags: gsm, gps
---


title: 16*2 LCD on nodeMCU

text:
# Question
Title: 16*2 LCD on nodeMCU
I am getting this error while uploading a simple LCD program on NodeMCU can anyone guide me??........

```
esptool.py v2.8
Serial port COM9
Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):
  File "C:\Users\HP-DeViL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3/tools/upload.py", line 65, in <module>
    esptool.main(cmdline)
  File "C:/Users/HP-DeViL/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.6.3/tools/esptool\esptool.py", line 2890, in main
    esp.connect(args.before)
  File "C:/Users/HP-DeViL/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.6.3/tools/esptool\esptool.py", line 483, in connect
    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

```

# Answer
> -1 votes
I have seen this behavior on esp chips as well. This happens when you've uploaded a program that utilizes the processor very heavily or a blank program. I've gotten it to upload by unplugging and re-plugging, trying to time it correct so that it's just booting up while the programming begins. Just keep trying this and eventually it should get through.

---
Tags: lcd
---


# Question
Title: Can't get actual output when, both input logic is high
I want When,

* light=0, ir=0 then output will pin 8 high & pin 12 low.
* light=0, ir=1 then output will pin 8 high & pin 12 high.
* light=1, ir=0 then output will pin 8 low & pin 12 low.
* light=1, ir=1 then output will pin 8 low & pin 12 low (This statement does not work).

Please find the code & suggest me, if any modification is needed.

```
void setup() {

    pinMode(8,OUTPUT); //logic output.
    pinMode(12,OUTPUT); //logic output.
    pinMode(2, INPUT); //value input.
    pinMode(4, INPUT); //value input.

    Serial.begin(9600);
}

void loop() {

    int light = digitalRead(2); //value input.
    int ir = digitalRead(4); //value input.

    if (light == LOW && ir == LOW)
    {

      digitalWrite(8, HIGH);
      digitalWrite(12, LOW);
      delay(2000);

    }

    if (light == LOW && ir == HIGH)
    {

      digitalWrite(8, HIGH);
      digitalWrite(12, HIGH);
      delay(2000);

    }

    if (light == HIGH && ir == LOW)
    {

      digitalWrite(8, LOW);
      digitalWrite(12, LOW);
      delay(2000);

    }

    if (light == HIGH && ir == HIGH) //This condition does not work.
    {

      digitalWrite(8, LOW);
      digitalWrite(12, LOW);
      delay(2000);

    }

    digitalWrite(8, LOW);
    digitalWrite(12, LOW);
    delay(2000);

}

```

# Answer
> 1 votes
You can simplify your requirements somewhat by splitting your inputs up.

> light=0, ir=0 then output will pin 8 high & pin 12 low.
>
> light=0, ir=1 then output will pin 8 high & pin 12 high.

If `light` is 0 then pin 8 is high. AND `ir` is echoed to pin 12.

> light=1, ir=0 then output will pin 8 low & pin 12 low.
>
> light=1, ir=1 then output will pin 8 low & pin 12 low

If `light` is 1 then both pins 8 and 12 are low, and you don't care what `ir` does, since it doesn't have any effect on the outputs.

So your structure could look more like:

```
if (light == 0) {
    digitalWrite(8, HIGH); // 8 will always be high with light == 0
    digitalWrite(12, ir); // echo the ir value to pin 12
} else {
    digitalWrite(8, LOW); // if light is 1 then everything
    digitalWrite(12, LOW);// is low regardless of ir.
}

```

# Answer
> 0 votes
Note this is not an answer to the question (I don't see any problem initially), but to clean the code it might help to debug it (using print statements as Sim Son suggests).

Instead of all the `if` statements, check when pin 8 and pin 12 needs to be HIGH:

```
 pin 8:  (light == LOW && ir == LOW)
 pin 12: (light == LOW && ir == LOW)  or (light == LOW && ir == HIGH)

```

For pin 12, the condition can be rewritten as

```
 pin 12: (light == LOW) || (ir == LOW or ir == HIGH)

```

which is equal to

```
 pin 12: light == LOW

```

So now you can change the code from the `loop` function to:

```
void loop()
{
   digitalWrite(8 , (light == LOW && ir == LOW) ? HIGH : LOW);
   digitalWrite(12, (light == LOW             ) ? HIGH : LOW);
   delay(2000);

   digitalWrite(8, LOW);
   digitalWrite(12, LOW);
   delay(2000);

```

}

the x ? : z statements means: if x is true, do y, else z.

The last three statements are fixed (copied from your code).

Now we can even further reduce it, by removing the duplicated code

```
void loop()
{
   processLeds((light == LOW && ir == LOW), (light == LOW));
   processLeds(False                      , False         );
}

void processLeds(int conditionLed8, int conditionLed12)
{
    digitalWrite( 8, conditionLed8  ? HIGH : LOW);
    digitalWrite(12, conditionLed12 ? HIGH : LOW);
    delay(2000);
}

```

You pass the condition when led 8 and 12 have to be high or log to a function, which sets the LEDs.

Now you can also use much less print statements for finding your problem.

---
Tags: input
---


# Question
Title: Declaring and using array of structures in Arduino
Printing structure variables, I get default values. What is wrong with my code?

```
struct SCENARIO
{
  int Lamp_Pin = -1;
  int PB_Pin = -1;
} ;

SCENARIO  _red;
SCENARIO  _yellow;
SCENARIO  _white;
SCENARIO  _stop;
SCENARIO btns[4] = { _red,  _yellow, _white, _stop};

void setup()
{
  _stop.Lamp_Pin = 8;
  _stop.PB_Pin = 4;

 ///// initializing other 3 objects i.e. red & white & yellow
 ////
for (int i = 0; i < 4; i++)
  {
    Serial.print(i);Serial.print(":");
    Serial.print(btns[i].Lamp_Pin);Serial.print(":");
    Serial.println( btns[i].PB_Pin );
    //pinMode(  btns[i].Lamp_Pin, OUTPUT);
    //pinMode(  btns[i].PB_Pin, INPUT);
  }
}

```

The image below shows what I get. It seems I have not initialized the variables!

# Answer
> 1 votes
The problem is that a struct is handled as a value type, not as a reference type.

This means that a copy of `_stop` is made and put in `btns` (`btns[3]` actually).

So what you need to do is putting pointers into the `btns` array:

```
SCENARIO* btns[4] = { &_red, &_yellow, &_white, &_stop};

```

The symbol * denotes a pointer, and & means the address of a variable (so it points to the variable and is not a copy).

Now when you change `_stop`, also `btns[3]` which points to `_stop` will show the correct initialized value.

For printing you should use:

```
Serial.println( (*btns[i]).LampPin);Serial.print(":");
Serial.println( (*btns[i]).PB_Pin );

```

Because \*btns\[i\] is a pointer, but because this is a very often used feature, a special notation can be used:

```
Serial.print(btns[i]->Lamp_Pin);Serial.print(":");
Serial.println( btns[i]->PB_Pin);

```

# Answer
> 1 votes
In this line:

```
SCENARIO btns[4] = { _red,  _yellow, _white, _stop};

```

you are making 4 copies of the structures and placing them in an array.

Instead you should either create the array directly with the values:

```
SCENARIO btns[4] = {
    {-1, -1},
    {-1, -1},
    {-1, -1},
    {8, 4}
};

```

And only use the array, or use pointers in the array:

```
SCENARIO *btns[4] = { &_red,  &_yellow, &_white, &_stop };

```

and then access the entries as pointers:

```
Serial.print(btns[i]->Lamp_Pin);
Serial.print(":");
Serial.println( btns[i]->PB_Pin );

```

---
Tags: programming, array
---


title: Interfacing Arduino with Python Serial

text:
# Question
Title: Interfacing Arduino with Python Serial
I am implementing an FIR filter using Arduino. I am using an input signal as an audio signal. The audio signal has a duration of 3 seconds with total samples, 66150. What I am doing is reading this file in python and storing the data in an array. Using Serial, I want to send this sampled data to Arduino serial and process it, then send it back to serial and receive in Python.

**Python Code**

```
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile # get the api
import serial, time

samplerate, data = wavfile.read("sample.wav")
samples = len(data)
plt.plot(data[:20000])
arduino = serial.Serial('COM4', 9600, timeout=.1)
time.sleep(1) #give the connection a second to settle

for i in range(0,samples):

    arduino.write(data[i])
    time.sleep(1)
    print(arduino.readline())

```

**Arduino Code**

```
  void setup() {

  Serial.begin(9600);
  }
  int i = 0;
  int newdata[10];
  void loop() {
     if(Serial.available() > 0) {
          int data = Serial.read();
          newdata[i] = data;
          Serial.print(newdata[i]);
          i = i+1;
        }
   }

```

The problem I am facing is that I am stuck at very first step. As a check, I sent 10 samples values at start from Python to arduino using a loop and tried to recover them back to read on Python console. These values were not correct. When I entered a string inside the arduino.write(), it was receiving but when I input a variable inside the arduino.write(), it doesn't print that value after transferring back to python. I just tried many things like changing to string but I didn't get the desired result. The output for this code is attached. Tomorrow is my submission and I am stuck in this thing. Help will be highly appreciated.

# Answer
I have found a way to tackle this. Here is my arduino code:

```
char buf[100];
const double coefficients[28] = {
-0.006416610121367, -0.01179616274682, -0.01212859343535,-0.001491136183145,
 0.0175211951058,  0.03193599126761,   0.0259553014052,-0.004580133449276,
-0.04206485416456, -0.05260424218688,-0.007566809377484,  0.09242896920118,
 0.2100842841173,   0.2894365184419,   0.2894365184419,   0.2100842841173,
 0.09242896920118,-0.007566809377484, -0.05260424218688, -0.04206485416456,
-0.004580133449276,   0.0259553014052,  0.03193599126761,   0.0175211951058,
-0.001491136183145, -0.01212859343535, -0.01179616274682,-0.006416610121367
};

int order_of_filter = 27;
int sample_array[28] = {};
double output_sample = 0;
void setup()
{
  Serial.begin(9600);
  Serial.setTimeout(50000);
}
void loop()
{
  int  sample_in;
  int num_read = Serial.readBytesUntil('\n', buf, 100);
  buf[num_read] = '\0';
  sscanf(buf, "%d", &sample_in);
  for (int i = order_of_filter; i > 0; i--)
  {
    sample_array[i] = sample_array[i-1];
  }

  sample_array[0] = sample_in;

  for(int i = 0; i<=order_of_filter; i++)
  {
    output_sample = output_sample + sample_array[i]*coefficients[i];
  }
  Serial.println(output_sample);
  output_sample = 0;
}

```

And here is my Python Code:

```
    import matplotlib.pyplot as plt
  from scipy.fftpack import fft
  from scipy.io import wavfile # get the api
  import serial, time
  import numpy as np
  import sounddevice as sd

  arduino = serial.Serial('COM4', 9600, timeout=1) #COM port depends on the USB port
 time.sleep(3) #time to get connection ready
 # %%

 fs, data = wavfile.read('hfsound.wav')
 samples = len(data)
 #Plot the signal
 plt.plot(data[:samples])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 #Plotting fft
 fft_input = fft(data)
 half_length = int(len(fft_input)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_input[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 # %%

 #Declare an Array of zeros
 outputArray = np.zeros(64000)
 #Sending data to aurdino
 for i in range(samples):
     number = data[i]
     string = str(number).encode(encoding='utf-8') + b'\n'
     arduino.write(string)
     byt = arduino.read_until();
     print(byt.strip())
     outputArray[i] = byt.strip()

 arduino.close()
 # %%

 #Plotting Output waveform
 #Plot the time-domain output signal
 plt.plot(outputArray[:len(outputArray)])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Output Signal")
 plt.grid()
 plt.show()

 #Plotting fft of output
 fft_out = fft(outputArray)
 half_length = int(len(fft_out)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_out[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Output Signal")
 plt.grid()
 plt.show()
 # %%

 #Playback code
 sd.play(outputArray, fs)
 # %%

```
> 1 votes

# Answer
```
    arduino.write(data[i].tobytes())
    time.sleep(.1)
    print(int.from_bytes(arduino.readline(),byteorder='little') )

```

Is this what you whant?
> 0 votes

---
Tags: serial, arduino-due
---


title: qsort is not really sorting

text:
# Question
Title: qsort is not really sorting
I'm working with Arduino and getting some strange errors. qsorting is not sorting correctly.

```
//using this libraries
#include <ESP8266WiFi.h>
#include <inttypes.h>

//the red struct is

typedef struct {
    int32_t rssi;
    int id;
} red;

//Here is my compare function
int compare (const void * a, const void * b)
{
  yield();
  red *redA = (red *)a;
  red *redB = (red *)b;
  //Serial.printf("redA->rssi: %d, redB->rssi: %d\n",redA->rssi,redB->rssi);
  //Serial.flush();

  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);
  //return ( redB->rssi - redA->rssi );
}

void showNetworks(){
  int n = WiFi.scanNetworks(false,false);
  red listOfRedes[n];

  for (int i = 0; i < n; i++) // ...initialize it
  {
    yield();
    listOfRedes[i].rssi = WiFi.RSSI(i);
    listOfRedes[i].id = i;
    Serial.printf("%d: RSSI%d\n", i, listOfRedes[i].rssi);
    Serial.flush();
  }
  Serial.printf("salio\n");
  Serial.flush();
  qsort (listOfRedes, n, sizeof(red), compare);
  Serial.printf("ordeno\n");
  for (int i = 0; i < n; i++) // ...initialize it
  {
    yield();
    Serial.printf("%d: RSSI:%" PRId32 "\n", listOfRedes[i].id, listOfRedes[i].rssi);
  }
}

```

and this is the output i get

```
0: RSSI-69
1: RSSI-65
2: RSSI-72
3: RSSI-50
4: RSSI-60
5: RSSI-87
6: RSSI-87
7: RSSI-79
8: RSSI-80
9: RSSI-88
10: RSSI-74
11: RSSI-77
12: RSSI-78
13: RSSI-83
14: RSSI-79
15: RSSI-60
16: RSSI-85
17: RSSI-86
18: RSSI-66
19: RSSI-88
20: RSSI-80
21: RSSI-74
22: RSSI-81
23: RSSI-87
salio
ordeno
4: RSSI:-60
1: RSSI:-65
0: RSSI:-69
3: RSSI:-50
18: RSSI:-66
15: RSSI:-60
2: RSSI:-72
10: RSSI:-74
11: RSSI:-77
21: RSSI:-74
19: RSSI:-88
20: RSSI:-80
22: RSSI:-81
23: RSSI:-87
12: RSSI:-78
5: RSSI:-87
6: RSSI:-87
7: RSSI:-79
8: RSSI:-80
9: RSSI:-88
13: RSSI:-83
14: RSSI:-79
16: RSSI:-85
17: RSSI:-86

```

As you can see the sorting is not OK and I don't get why. Thank you in advance and sorry for my poor English.

# Answer
In your program there is this line of code:

```
  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);

```

Which appears to return a 1 if A is greater then B other wise it will return a 0. This code can not tell the difference between A \< B and A == B. Consider altering this line of code to allow returning 1 for A \> B, 0 for A == B and -1 for A \< B:

```
  return redA->rssi > redB->rssi ? 1 : (redA->rssi < redB->rssi ? -1 : 0);

```
> 1 votes

---
Tags: esp8266
---


# Question
Title: Behaviour of tone() not as expected within while loop
I have a smoke detector with a piezo buzzer. I want to operate the arduino in low power mode so that it will last on a 9V battery. I've attached an interrupt, and when the digital output of the MQ-2 sensor goes high, it switches to a monitor function.

In the while loop, I check to see if the analog sensor has reached the threshold value, and I output to serial to see if I am in the conditional. If I use:

```
digitalWrite(buzzer, HIGH);

```

then the piezo sounds, however if I use

```
tone(buzzer, 1000,200);
delay(200);

```

it does not. I'm confused as to why this would be the case.

Full code as follows:

```
#include "LowPower.h"

int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 50;
int smokeD0 = 2;

void setup() {
  pinMode(redLed, OUTPUT);
  digitalWrite(redLed, LOW);
  pinMode(greenLed, OUTPUT);
  digitalWrite(greenLed, HIGH);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  pinMode(smokeD0, INPUT);

}
void switchToMonitor() {
  Serial.begin(9600);
  int digitalSensor = digitalRead(smokeD0);
  if (digitalRead(smokeD0) == HIGH)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
  }
  else {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
  }
  //This will be updated later to use the analog input
  //Using digital to make debugging easier
  while (digitalSensor == HIGH) {
    int analogSensor = analogRead(smokeA0);
    Serial.print("Pin A0: ");
    Serial.println(analogSensor);
    Serial.print("Pin D0: ");
    Serial.println(digitalSensor);
    // Checks if it has reached the threshold value
    if (analogSensor > sensorThres) {
      digitalWrite(buzzer, HIGH);
      //tone(buzzer, 1000,200);
      Serial.println("here");
      delay(1000);
    }
    else {
//      digitalWrite(redLed, LOW);
//      digitalWrite(greenLed, HIGH);
      noTone(buzzer);
      Serial.println("also here?");
    }
    //delay(100);
    digitalSensor = digitalRead(smokeD0);
  }
  noTone(buzzer);
}

void loop() {
  //delay(100);
  //LowPower.standby();
  attachInterrupt(0, switchToMonitor, CHANGE);
  LowPower.powerDown(SLEEP_FOREVER, ADC_ON, BOD_ON);
  detachInterrupt(0);
}

```

# Answer
> 1 votes
You can't use delay() or timer based tone() function in interrupt handler. Set a flag in interrupt and run the code in loop() conditionally based on the flag state. Do not forget to have the flag variable volatile.

---
Tags: interrupt, piezo
---


title: TX pin sends wrong data in Arduino Uno

text:
# Question
Title: TX pin sends wrong data in Arduino Uno
I want to send some data to an IP Modem from Arduino Uno. That IP Modem has TTL levels TX and RX inputs.

I used this connection between Arduino to the IP Modem:

I am powering Arduino with 12 V plugged in the barrel.

This is the photo of the connections:

I connected the PC to the USB connector of Arduino and I uploaded the following sketch to send "AABB" to the Modem:

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

void loop(void) {
 Serial.print("AABB");

 delay(5000); // Envía la temperatura cada 5 segundos
}

```

When monitoring what is received by the modem, it is

0x5F 0x5F 0xAF 0x2F

If I send just "A", the character received each 5 seconds is 0x5F.

Of course, both ends are configured as 115,200bps, 8N1.

In order to discard Modem problem, I connected RX, TX and GND in Arduino to a DB9 female connector and then to a RS232 - USB converter and started monitoring with my PC.

My surprise was that the data received is exactly the same as the received by the modem when it was connected. As seen in the following picture:

As you see in the picture, "\_" twice was shown (ASCII 0x5F), {\xaf} and finally "/" (ASCII 0x2F).

Above test confirms Arduino is sending wrong data.

Something to note. When I monitor using USB cable connected to Arduino and using Monitor Serie in the Arduino IDE, I see correctly "AABB". The problem is when using TX and RX pins (the same happened if I used other pin along with SoftwareSerial library)

What may be going on?

# Answer
> 1 votes
Since you have already tried SoftwareSerial, also try inverting the serial protocol via SoftwareSerial. Sometimes a device uses inverted serial protocol and you don't know it.

So initialize inverted add 1 to the end of the contructor like so :

```
SoftwareSerial mySerial(RXPIN, TXPIN,1); // RX, TX, inverted

```

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


# Question
Title: Arduino Obstacle Avoiding Shield controlor motor L293D
I am a beginner with Arduino. I wanted to make an Arduino obstacle avoiding. So I ordered last week an L293D Shield Motor Driver and I don't know if what I receive is a good item. The first picture is how it looks on the site and the second picture is what I got.

I saw that if you search for this motor you get results for both motors, but they are not the same. And I saw in this tutorial, this person using a motor like mine https://www.youtube.com/watch?v=ydDvoknlJ9M and then he switched to the motor in the first picture.

Questions: Are these motors the same? Should I request a return? If they are the same, how can I add the pins (as shown in the third picture?

Again, I am a beginner and I would appreciate if someone can help me.

# Answer
To complete @chrisl answer: Yes you need these pins to make the same robot as in the video. You can order them online and solder them (if you know how to solder and if you have the soldering material). Be careful with soldering ;)

For your information, the pins you circled in red are used to communicate with the Arduino pins A0 to A5, and provide +5V and GND. In the video, they are connected to the ultrasound sensor.

And please clarify what is your `motor`??? Do you mean the `Shield motor driver`? It is not the same. A `shield` is an eletronic board that you plug to your Arduino to do a specific task (control a motor, connect to wifi...). A `motor driver` is the electronic to control the motor. On your pictures, they are mainly the 3 components with 16 legs each.
> 1 votes

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


# Question
Title: Addressable LEDs vs Multiplexing for a Matrix
I would like to building a 8x64 RGB Matrix and connect it to my Arduino. As this form factor does not really exist I would need to build one myself but now I am wondering if I should use addressable LEDs like WS2813 or APA107 and use FastLED or rather use 'dumb' LEDs and just multi-/charlieplex them using a MAX7221 or comparable chip.

What are some pros and cons I should consider with each one? I read that to many WS2813 can make problems but APA107 seem to fix that. But on the other hand most bigger matrices just use multiplexing........

# Answer
The smart RGB LEDs will be brighter. Each device has its own control chip that controls the 256 PWM level for each of the 3 LEDs. So for an 8x64 array, you send in 3 bytes/device, 8x64x3 = 1535 btyes, pause a few microseconds, and the array updates itself.

Going the multiplexing route, you would do something like have 64x3 = 192 anode drivers (or up to 192, if not all are LEDs are lit up) to enable the LEDs across the display, and then 8 common cathode drivers to turn on each row one at a time for 1/30 to 1/24 of a second for minimal flicker. So 192 LEDs, 20mA each, the common cathode needs to be able to sink 3.84A

On the otherhand, 8x64 LEDs, each needing up to 60mA at full on, = 30.72A.
> 1 votes

---
Tags: rgb-led, multiplexer
---


title: Arduino MKR 10100 control DC Motor

text:
# Question
Title: Arduino MKR 10100 control DC Motor
Thank you for reading my post. I have been stuck on this for several weeks now! I am trying to turn ON/OFF a DC motor from Arduino IOT Cloud. I have set up the cloud and added the switch. Everything works well with an LED: it lights on and off as needed, but the motor does not turn on or off. Below is the circuit I have set up.

My circuit specs are as follows:

1. I'm not using a UNO as the image illustrates, rather I'm using an Arduino MKR WiFi 1010, but the connections of the pins are exactly the same: LED at PIN 3 and Motor at 7.
2. The diode I am using is 1N4001.
3. The transistor I'm using is TIP120.
4. The motor I'm using is 5V DC Motor.
5. 270 Ohm resistor on the transistor circuit and 220 Ohm on the LED circuit.

The Arduino code I made is as follows:

```
#include "thingProperties.h"

#define LED_PIN 3
#define MOTOR_PIN 7

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(MOTOR_PIN, OUTPUT);

  setDebugMessageLevel(2); // For debugging of cloud integration
  Serial.begin(9600);
  delay(1500);

  initProperties(); // initialize cloud properties
  ArduinoCloud.begin(ArduinoIoTPreferredConnection); // Connect to cloud
}

void loop() {
  ArduinoCloud.update(); // Update cloud background services
}

void onMotorChange() {
  if (motor) {
    // Motor & LED ON
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(MOTOR_PIN, HIGH);
  } else {
    // Motor & LED OFF
    digitalWrite(LED_PIN, LOW);
    digitalWrite(MOTOR_PIN, LOW);
  }
}

```

All my setup seems to be be correct, but it just is not working. I have researched a lot but to no avail. I have tested with a different motor just to be sure, but it also does not work. I'm not sure where I have made a mistake.

Please help me. Thank you very much.

# Answer
Okay i managed to solve it, the issue was actually my circuit wiring. Below is an image with the correct setup for the transistor or MOSFET.

I have changed the TIP120 to RFP30N06LE as VE7JRO suggested:

> The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

but that with the circuit in question does not work. I have not tested the circuit attached with this answer using a TIP120 but i suspect it would work as well. Finally i added a 9V battery as jsotola suggested:

> never use an arduino as a power supply ... there is a good chance that the arduino will become an expensive fuse

but i have not tested using the 5V Arduino pin again i suspect it would work as well.

## Bonus:

If anyone was wondering how i made these images i used TinkerCAD

Thank you all

Hope this Helps!
> 0 votes

# Answer
The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

For a more in-depth answer, please see this answer: https://electronics.stackexchange.com/a/388468/165322
> 1 votes

---
Tags: motor, transistor, iot, mkr1000, mkr1010
---


title: How to calibrate MPU 6050 thermometer?

text:
# Question
Title: How to calibrate MPU 6050 thermometer?
I'm using MPU 6050 and there's a thermometer onboard. However, I looked through the chip set data sheets but could not find the instruction for temperature sensing.

Could you tell me how to calibrate the data string from the two address started from 0x41?

# Answer
> 2 votes
The temperature sensor is likely included to keep the gyroscope and accelerometer better calibrated over the specified temperature range. The temperature may not be the ambient temperature should the chip warm up.

The temperature sensor specifications are in section 6.3 on page 14 of the specification sheet indirectly pointed to in the question.

```
TEMPERATURE SENSOR
Range -40 to +85°C
Sensitivity Untrimmed 340 LSB/ºC
Temperature Offset 35ºC -521 LSB
Linearity Best fit straight line (-40°C to +85°C) ±1°C

```

So, when the chip is at 35C the chip temperature register is supposed to read about -521. To convert that into C you need to make a calculation:

> chip\_temperature = ((value\_read + 521) + (35 * 340)) / 340

Simplified:

> chip\_temperature = (value\_read + 12421) / 340

---
Tags: mpu6050, calibration
---