# Question
Title: Standard deviation and variance of an array of numbers
Looking for a simple way to get the variance of an array of numbers, that will compile with the Arduino compiler. Something like this c#:

```
static float variance(double []a, int n)
{
    // Compute mean (average of elements)
    double sum = 0;

    for (int i = 0; i < n; i++) sum += a[i];
    double mean = (double)sum / (double)n;
    // Compute sum squared differences with mean.
    double sqDiff = 0;
    for (int i = 0; i < n; i++)
        sqDiff += (a[i] - mean) * (a[i] - mean);
    return (float)sqDiff / n;
}

// Driver Code
public static void Main ()
{
    double []arr = {10, 11, 12, 13};
    int n = arr.Length;
    Console.WriteLine( "Variance: " + variance(arr, n));
}

```

---

To keep it simple, and thanks for all your help.... it is a platform with actuators in each corner to raise and lower the platform.... Each actuator sends a feed back via modbus to the main micro processor at its request Which is stored to a array, which is processed and then sent via modbus Back to control (simple on/off) each actuator to keep platform in somewhat of a level position +/- a set number.... I already use the min/max (max – min = ) in the my code to limit a set, simple differential between the Actuators.... I am thinking that using the variance differential would work better for the application.... Thinking it would also detect a jammed or faulty actuator faster than the max/min difference with Less platform twisting.... (Response to Edgar), You could look at it as XYZ,… X= position.. Y= actuator.. Z=sample rate

This is my code snip it for the max/min

example 1 — adj\_str = actuators position = (10,11,10,9) run level flag 1

example 2 — adj\_str = actuators position = (10,14,10,9) run level flag 0

```
void min_max()
{
    int max = adj_str[0];
    int min = adj_str[0];
    for (int i = 0; i <= 3; i++)
    {
        const int value = adj_str[i];
        if (value > max) max = value ;
        if (value < min) min = value ;
    }
    //-
    adj_str_dif = max - min;
    //-
    if (adj_str_dif < 1) level_flag = 1;
    //-
    if ((level_flag == 1)&&(adj_str_dif > 4))  // 4 = the differential
    { level_flag = 0;}
    //-
    if (level_flag == 0)           // Level Till Max or Min (re-level)
    {
        // -- Lower --
        if (adj_str_dif > 0 && (digitalRead(but_pin[1]) == LOW))
            base = (max);
        // -- Raise --
        if (adj_str_dif > 0 && (digitalRead(but_pin[2]) == LOW))
            base = (min);
    }
    //-
    if (level_flag == 1)       // Run Till full retract or full extend
    {
        // -- Lower --
        if (adj_str_dif < 1 && (digitalRead(but_pin[1]) == LOW))
            base = 1023;
        // -- Raise --
        if (adj_str_dif < 1 && (digitalRead(but_pin[2]) == LOW))
            base = 0;
    }
}

```

# Answer
> 1 votes
C++ and C# (or Java) basic language constructs are very similar. Here is the Arduino version of your C# code with minimal required modifications. There is no change in the function implementation.

```

float variance(double a[], int n)
{
    // Compute mean (average of elements)
    double sum = 0;

    for (int i = 0; i < n; i++) sum += a[i];
    double mean = (double)sum / (double)n;
    // Compute sum squared differences with mean.
    double sqDiff = 0;
    for (int i = 0; i < n; i++)
        sqDiff += (a[i] - mean) * (a[i] - mean);
    return (float)sqDiff / n;
}

void setup() {
    Serial.begin(115200);
    double arr[] = {10, 11, 12, 13};
    int n = sizeof(arr) / sizeof(double);
    Serial.print( "Variance: ");
    Serial.println(variance(arr, n));
}

void loop() {

}

```

---
Tags: arduino-mega, sketch
---


# Question
Title: DC motor fan speed control with Temperature Sensor
I used this circuit schematic for the project however, when DC Motor starts to work, temperature value is increasing abnormally high. How can I solve this problem? It shows abnormal high values like 70, 85 ,101 etc.

```
#define TEMPERATURE A0
#define fan 3
void setup(){
Serial.begin(9600);
pinMode(fan, OUTPUT);
}

void loop(){
float temp = analogRead(TEMPERATURE);    //Read the analog pin
temp = temp * 0.48828125;   // convert output (mv) to readable celcius

Serial.print(temp);
//print the temperature status
Serial.print('\n');
delay(1000);

 if (temp<=24){
  analogWrite(fan, 51);

  delay(1000);

}
else if (temp<=26 && temp>24){
  analogWrite(fan,122);

  delay(1000);

}
 else if (temp<=30 && temp>26){
  analogWrite(fan,223);

  delay(1000);

}
else if (temp>30){
  analogWrite(fan,255);

  delay(2000);

}
}

```

# Answer
I am assuming that whatever temperature you are measuring is not rising when the motor is on.

I see that you are sharing the power/ground between your temperature sensor IC and the motor. Motors are extremely noisy from an electrical viewpoint and it's almost certainly causing your temperature sensor to malfunction.

It would be best to separate the temp sensor power/ground connections from the motor power/ground connections completely. Power the motor from an external supply instead of sourcing it from the Arduino.

Another thing that might help is to add some bypass capacitors as close as possible to the motor and to the temperature IC across the Vcc and GND lines. This will help to smooth out the power in spite of the noise that the motor itself generates. Generally you want at least one of two types, an electrolytic capacitor and a ceramic capacitor. These are both inexpensive if you don't already have some on hand. I'll suggest a 10 uF electrolytic and a 0.1 uF ceramic capacitor near both the motor and the temp sensor.
> 1 votes

# Answer
Besides all the good advice from jwh20, you should start with a general strategy to find out where the problem lies. You should hang a DVM directly between the sensor output and ground and see if the voltage also shows the rising problem. If not, the trouble is in your code.

A drifting value is often due a wiring issue, like a bad sensor ground. It wouldn't hurt to go over all the wiring very carefully.
> 0 votes

---
Tags: arduino-uno, temperature-sensor, transistor
---


# Question
Title: How do I know when a filter coffee machine is finished by using any sensor?
I have a filter coffee machine that looks like this one and I would like to send a message to the machine users by using any development board (like Arduino or NodeMcu) when the machine is finished.

I haven't found a way to detect when the machine is finished. (I also don't want to do any physical change on the machine, like adding any cable or opening in the machine. I can use any sensor or so on.)

How can I do that? Any advice?

# Answer
Just two ideas, both non-invasive:

The machine moves water from the reservoir at the back to the coffeepot at the front of the machine, so its weight distribution will change while making coffee.

If you put a thin pressure pad (like this one, or something similar) under the whole machine at the back you should see the pressure at that point become smaller while coffee is being made.

If the effect isn't pronounced enough, you could make the whole machine tilt forward while making coffee by putting a narrow and thin strip of plastic under its centre from left to right so it can swivel forward and back just a little depending on the location of the bulk of the water.

If the pressure on the pressure pad at the back stops dropping, the coffee is ready. You can also detect when the coffee can is empty again this way, or maybe even how many cups of coffee are still available in the coffee can.

Or maybe you could detect with a contact microphone when the machine goes silent, assuming it makes sufficient noise when making coffee. Mine does.
> 1 votes

# Answer
If the machine has a Brewing- or a Done Brewing LED, a light sensor can detect this without no changes or connections to the machine. This would also have the advantage of working for a short or full pot.
> 0 votes

---
Tags: arduino-uno, sensors, arduino-nano, nodemcu
---


title: Error sending data from ESP8266 to Uno

text:
# Question
Title: Error sending data from ESP8266 to Uno
I am sending data from an ESP8266 to an Uno (I need to use the Uno because it has more inputs than the ESP and I need those for my project.) The ESP8266 is connected to the Uno's Serial pins 0/1 RX/TX (communicating on BAUD rate of 9600), and then I have a SoftwareSerial out from the Uno (on a BAUD rate of 57600) for debugging. Something weird is happening though. The transfer works a couple times and then I get this in the log:

```
--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Exception (0):
epc1=0x40239ba1 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

>>>stack>>>

ctx: sys
sp: 3fffebd0 end: 3fffffb0 offset: 0190
3fffed60:  40239b2e 3feffe00 3fffd9d0 00000050
3fffed70:  000005e0 00000000 40103501 3ffed4d0
3fffed80:  0000003c 00000000 00000022 401049e6
3fffed90:  401049c8 3fffc100 3ffef2a0 00000000
3fffeda0:  00000000 4022279f 00000020 40100198
3fffedb0:  400005e1 150cc636 00000005 4010144c
3fffedc0:  4022279f 00000030 00000010 3ffefdcc
3fffedd0:  40221007 3fff051a 00000014 00000000
3fffede0:  00000000 00000061 00000061 00000001
3fffedf0:  3ffecdb8 00000006 00000000 3fff04fc
3fffee00:  3fff051a 3ffef2a0 00000061 00000000
3fffee10:  3ffe9be8 7fffffff 50800000 00000001
3fffee20:  00000001 00004a08 00000142 401006d7

```

Any ideas what could be causing this? Here is the code that the Uno uses for receiving from the ESP and printing to the SoftwareSerial (Serial is the RX/TX and mySerial is the SoftwareSerial). It uses a couple helper functions I haven't included here but let me know if you need them:

```
void receiveFromESP() {
  if (Serial.available() > 0   ) {
    endofTransmission == 0;
    alreadyZeroed = 0 ;
    receivedChar = Serial.read();
    mySerial.print(receivedChar);
    if (receivedChar == '[' ) {
      lastNum = 0 ;
      commaNumber = 0 ;
      lastWasNum = 0 ;
    }
    if (receivedChar == '*' ) {
      lastNum = 0 ;
      commaNumber = 0 ;
      lastWasNum = 0 ;
      createArray[0] = 4;
      createArray[1] = 4;
      createArray[2] = 4;
      createArray[3] = 4;
    }
    if (receivedChar == 'A'
        || receivedChar == 'B'
        || receivedChar == 'C'
        || receivedChar == 'D'
        || receivedChar == 'E'
        || receivedChar == 'F'
        || receivedChar == 'G'
        || receivedChar == 'H'
        || receivedChar == 'I'
        || receivedChar == 'J'
        || receivedChar == ','
       ) {
      if (lastWasNum == 1) {
        createArray[commaNumber] = lastNum;
        commaNumber++;
      }
      lastWasNum = 0 ;
      createArray[commaNumber] = charToNumber(receivedChar);
      commaNumber++;
      lastNum = 0 ;
    }
    if (receivedChar == ']') {
      lastWasNum = 0 ;
      endofTransmission = 1 ;
      for (int i = 0; i < 50; i++) {
        mySerial.print(createArray[i]);
        mySerial.print(':');
      }
    }
    if (
      receivedChar == '0'
      ||  receivedChar == '1'
      ||  receivedChar == '2'
      ||  receivedChar == '3'
      ||  receivedChar == '4'
      ||  receivedChar == '5'
      ||  receivedChar == '6'
      ||  receivedChar == '7'
      ||  receivedChar == '8'
      ||  receivedChar == '9'
    ) {
      lastWasNum = 1;
      receivedCharInt = (int)receivedChar - 48;
      lastNum = lastNum * 10 + receivedCharInt;
    }
    t = millis();
  }
};

```

As requested, here is the full ESP code:

```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

#include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic

#define SERIAL_BUFFER_SIZE 256

void setup() {

  Serial.begin(9600);
  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("*WIFISETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }
  WiFiManager wifiManager;
  wifiManager.setConfigPortalTimeout(120);
  //first parameter is name of access point, second is the password
  wifiManager.autoConnect("AP-NAME", "AP-PASSWORD");
}

void loop() {
    WiFiClient client;
    HTTPClient http;
    if (http.begin(client, "[URL]")) {  // HTTP
      // start connection and send HTTP header
      http.addHeader("Content-Type", "text/plain");
      http.addHeader("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=");
      int httpCode = http.GET();

      if (httpCode == 200 ) {  // HTTP header has been sent and Server response header has been handled
        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          Serial.println(payload);
        }
      } else{
        if (httpCode > 0 ){
          //website problem
          Serial.printf("[2,1,1,1]");
        }
        if (httpCode == -1 ){
          //wifi problem
          Serial.printf("[4,1,1,1]");
          ESP.reset();
        }
      }
      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  delay(10000);
}

```

# Answer
> -1 votes
Why not use a PCF8574 I2C expansion board, they work great on 3V3. If you need more inputs or outputs use the PCF8575. There are a lot of I2C expansion boards you can select from. They will also be faster and less convoluted then your existing solution.

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


title: Sync issue with signals

text:
# Question
Title: Sync issue with signals
```

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "digitalWriteFast.h"

#define BUTTONPIN 2
#define FDCSPIN 6
#define CIPIN 5
#define SPEAKERPIN 4

float RPM=1000.0;
int PWus=1.5*1000.0;
int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
int CiCnt;
int totalCnt;
int CIState=B01100000;
bool Buttonstate=0;
LiquidCrystal_I2C lcd(0x27, 20, 4);

void setup()
{
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  lcd.clear();
  lcd.print("READY TO TEST"); // Waiting for button press
  pinMode(BUTTONPIN, INPUT);// Setting button as Input
  pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
  pinMode(CIPIN, OUTPUT); // Cylinder Identification
  digitalWriteFast(FDCSPIN, LOW);
  digitalWriteFast(CIPIN, LOW);
}

void loop()
{
 Buttonstate=digitalReadFast(BUTTONPIN);
 if(Buttonstate==1)
 {
  delay(5);
  if(Buttonstate==1)
  {
    runInjectorTest();
  }
 }
}
void runInjectorTest()
{
  lcd.print("Test Run");
  playtesttone();

    for(totalCnt=0;totalCnt<8000;totalCnt++)
    {

      PORTD=CIState;
      delayMicroseconds(FDCSoffset);
      PORTD=PORTD^B01000000;
      delayMicroseconds(PWus);
      if(totalCnt%4==0)
      {
        CIState=CIState^B00100000;
      }
    }
  totalCnt=0;
  playfinishtone();
}
void playtesttone()
{
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
}
void playfinishtone()
{

  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);

}

```

I am using this code to generate 2 signals, called CI and FDCS. CI stays on until the 5th FDCS pulse. I checked the output which is connected to a driver using the scope and I got this. The rising edge and falling edge of the longer signal (CI, dark green) are supposed to sync with the rising edge of the FDCS signal (Lime green),but they are inline with the falling edge. Note that the output is inverted (when compared to the code) hence the signal generated by the Arduino pins is according to the code.

# Answer
> 2 votes
I did not tried it out. But something like this might help to synchronize the inverted signals to the rising edge of the high frequent signal.

I removed the FDCSoffset delay, because it is negative according to the variables at the top.

```
// initialize CIState with 00
int CIState=B00000000;

// lines not shown .....

for( totalCnt=0; totalCnt<8000; totalCnt++ )
{
  CIState=CIState^B01000000;
  if(totalCnt%4==0)
  {
    CIState=CIState^B00100000;
  }
  // both signals are set at the same time
  PORTD=CIState;
  delayMicroseconds(PWus);
}

```

---
Tags: arduino-uno
---


# Question
Title: i am not able to figure out the problem due to which i can't upload my sketch to nano
this is the error code (it is new from the previous time i posted)

i am using the hourly build for this and not the Beta

```
avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_recv(): programmer is not responding

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

```

this is the info of the loader and board i am using

# Answer
> 1 votes
Another idea - try using Windows Filemanager to navigate down through the folder path shown in the error message and see if the avrdude.conf file exists in the specified place. this probably will not solve your problem but it might help to understand what is happening. Good luck - Bob

# Answer
> 0 votes
I am just taking a guess as I operate on Linux. I would suggest go to tools menu and see if the correct board is selected. I would venture to guess it is not set for nano. Mine gives me two choices new and old. Try one and if it does not work try the other. Be sure your Baud is set correctly.

---
Tags: arduino-nano
---


# Question
Title: Analog input voltage rises when motor is working
I'm making automatic water plant system. I'm using:

Arduino Uno

3.3-6V water pump -https://www.amazon.com/Vipe-Micro-Submersible-Motor-Water/dp/B01N0X3CW4

Capacitive soil moisture sensor - https://www.amazon.com/Gikfun-Capacitive-Corrosion-Resistant-Detection/dp/B07H3P1NRM

I've noticed that when motor turns on sensor readings are much higher. First I thought that the problem is in sensor, but when I measured sensor output in both cases (when motor is on and when motor is off) there was no difference, voltage was the same. Then I measured voltage in analog pin A0 that I used, and I saw there is increase in voltage when pump is on (+0.4V), so my guess is that this voltage is added to sensor output voltage which is giving me higher values in my serial monitor.

For powering my pump I'm using same circuit as in this example: https://www.devacron.com/arduino-tip120-control-dc-motor/

Just except potentiometer there is my sensor, powered via 3.3V Arduino pin (its GND is connected to Arduino GND). I also tried connecting all grounds together in one point, didn't help. I powered Arduino with usb and with 9V supply, in both cases same problem. Tried powering pump and Arduino with same and with different power supplies, no luck either.

I should also add that there is no change in AREF and 5V pin when pump is working. 4.97V in both cases.

Does anyone have any idea what can be the problem and how to solve it?

Here is how I wired everything: https://i.stack.imgur.com/8IDQR.jpg

I also tried with 0.1uF ceramic and 10nF electrolytic capacitors. as suggested, wiring it like this: https://i.stack.imgur.com/fNQnX.jpg Didn't make much difference, problem is still there.

# Answer
Try adding some bypass capacitors at the two points I've added arrows to:

I suggest two in each spot, one a 0.1uF (or similar) ceramic dipped or disc and the other a 1 or 10uF electrolytic. Keep the polarity in mind for the electrolytic.

Oh, and another thing. Be sure your motor is not pulling your power supply voltage down. It's possible your phone charger supply is inadequate to supply the power needs of the motor. Use a voltmeter across the input to the Arduino and check the voltage when the motor runs. If it's dropping much below 5V you need a better power supply. Well, I see now that you are only powering the motor from that 5V supply. So that's probably not it.
> 1 votes

---
Tags: arduino-uno, motor, input, analog
---


# Question
Title: What is the best way to init wifi communication between two devices (get IP address)?
what is the best way to init wifi communication between two devices without knowing IP of second device, let's say Raspberry Pi and ESP8266?

I want to build simple home automation system for my purpose. There will be Raspberry Pi, as heart of system and ESP8266 as controlled devices. What is best way to get them communicate? I think, the hardest think is how to get their IP address. Then it will be easy to communicate via sockets.

In next text, by RPi I mean Raspberry Pi and program in RPi will be in python (but using call of terminal commands when needed).

My idea is this: On ESP8266 will be running program, which will create WiFi Acces Point at start (on first run in network). Name (SSID) of that AP will be specific (let's say starting with ESP-AUTOMATION prefix), so Raspberry Pi will know, when new ESP device will be turned on (Raspberry Pi will repeatedly search for accesible networks). When new ESP appear, RPi will save own IP to variable and connect to newly searched network (let's say ESP-AUTOMATION-abcd). Then will RPi send to AP (ESP) it's (RPi's) IP address and local network SSID and password. Then it will disconnect, and connect back to local network (and gain it's "old" IP, which it previously saved to variable). Then ESP connect to local network with static IP and after succesfull connect, it will send to RPi it's IP address via socket (because IP addr of RPi it will already known, because RPi have send it when it served as AP). Then RPi will save that IP address. And because IP addresses (of RPi and also ESP) will be configured as static, it shouldn't change over time.

Is this good idea? Or is something of that unreal (I am at beginning of that all)?

PS: I really want completely autonomous system, so for me is not solution something like connect ESP to PC and print it's IP to serial and then it write to RPi...

Thanks for every advice/opinion.

# Answer
One is a server and the other is a client. The server do not need to know IP of the client, but the client need to know IP address of the server. See more in communication between two Arduino
> 1 votes

---
Tags: esp8266, wifi, raspberrypi, networking, esp
---


# Question
Title: Question: how to join two different codes
I’m dabbling in Arduino and having trouble running two sketches on my Arduino UNO simultaneously. The first is about a program that reads temperature and relative humidity and the second is a program that reads barometric pressure. Both programs work independently, but when I try to combine the two, No help

```
this is the code for temperature and relative humidity:

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

//VARIABLES
//Asignación de los pines digitales
int SENSOR = 2; //Este es el pin #2
int RS = 4;
int E = 5;
int D4 = 6;
int D5 = 7;
int D6 = 8;
int D7 = 9;
//Variables de lectura de tempratura y humedad
int temp;
int hume;
//Creación de variables para el sensor y el display
DHT dht(SENSOR,DHT11);                    //Formato general: DHT <var_name>(PIN, MODELO DEL SENSOR)
LiquidCrystal lcd(RS, E, D4, D5, D6, D7); // Formato general: LiquidCrystal <var_name>(RS, RW, ENABLE, D0, D1, D2, D3, D4, D5, D6, D7)
//Variable para salida del abanico
int motor = 12;

void setup(){

  //Iniciar el sensor de temp
  dht.begin();
  //Iniciar el LCD
  lcd.begin(16,2); //(tipo 16 columnas, 2 líneas)
  //Setea el Pin 12 como salida
  pinMode(motor,OUTPUT);

}

void loop(){ //Este es el buclé principal del programa

  //Lee valores físicos
  hume = dht.readHumidity();
  temp = dht.readTemperature();

  //Limpia el LCD
  lcd.clear(); //esta instrucción coloca el cursor en la pos 0,0 (columna, fila)
  lcd.setCursor(0,0); //(no necesaria porque la linea de arriba ya lo hace)
  //Escribe los valores leídos en el LCD
  lcd.print("TEMPERATURA: ");
  lcd.print(temp);
  lcd.print("C");
  lcd.setCursor(0,1); //esta instrucción coloca el cursor en la pos 0,1 (columna, fila)
  lcd.print("HUMEDAD: ");
  lcd.print(hume);
  lcd.print("%");

  //Activa el motor si la temperatura pasa el valor deseado
  if(temp>=30){ // Compara si la temp ya es 30 grados
    digitalWrite(motor,HIGH); //Si lo es manda un 1 lógico a teavés del pin digital #12
  }
  else{
    digitalWrite(motor,LOW);// sino, manda un 0, lo que apagaría el motor
  }

  delay(2000);//valor en milisengundos para que repita el ciclo

}

```

and this is the barometric pressure code:

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

// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here

Adafruit_BMP085 bmp;

void setup() {
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
}

void loop() {
    Serial.print("Temperature = ");
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    // Calculate altitude assuming 'standard' barometric
    // pressure of 1013.25 millibar = 101325 Pascal
    Serial.print("Altitude = ");
    Serial.print(bmp.readAltitude());
    Serial.println(" meters");

    Serial.print("Pressure at sealevel (calculated) = ");
    Serial.print(bmp.readSealevelPressure());
    Serial.println(" Pa");

  // you can get a more precise measurement of altitude
  // if you know the current sea level pressure which will
  // vary with weather and such. If it is 1015 millibars
  // that is equal to 101500 Pascals.
    Serial.print("Real altitude = ");
    Serial.print(bmp.readAltitude(101500));
    Serial.println(" meters");

    Serial.println();
    delay(500);
}

```

# Answer
You need to write one program using elements from each block of code. There is no way the Arduino will run both programs concurrently, it will only run one or the other. You can copy and paste them together but unless done correctly it will not work. This is why it is important to understand the code you are using.
> -1 votes

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


# Question
Title: How to move a servo quickly and without delay function
Im trying to move a servo from one place to another while using the typical `for` loop you find in the servo's library example:

```
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
  servo1.write(pos1);
  delay(15);
}

for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
  servo1.write(pos1);
  delay(15);
}

```

The thing is that while this does work, I want to be able to move the servo a little quicker, but I can't use the `delay()` function because of some connectivity issues with another library (BLYNK).

How could I move the servo from lightOFF to lightON the quickest way possible without using the `delay()` function?

# Answer
> 6 votes
The quickest way possible from `LightON` to `LightOFF` is simply `servo1.write(lightOFF);` without loops or delays, in one go; no need to do it degree by degree. For example:

```
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1++) {
  servo1.write(pos1);
  delay(15);
}

servo1.write(lightOFF);

```

If you want it to move a few degrees every loop and do other things in the loop while it moves, you can time it with `millis()` instead of `delay()`. The code below should move the servo 5 degrees every 0.5s:

```
int moveTime = 500; // Move every 0.5s
unsigned long int startMillis = 0;
int position = lightOFF;
int step = 5; // Move 5 degrees

void loop() {
  if (millis() - startMillis >= moveTime) {
    servo1.write(position);
    if (position <= lightON) {
      position = position + step;
    }
    startMillis = millis();
  }
  // Do other things
}

```

Untested and incomplete, but you get the idea.

# Answer
> 2 votes
The best way is to use map() function.

```
void loop() {
  unsigned long progress = millis() - startMillis;

  int angle = map(progress, 0, MOVING_PEDIOD, lightOFF , lightON);
  servo1.write(angle);
}

```

The above code use the millis() function, therefore you do not need to worry about blocking other code.

Full instruction is available on How to control speed of servo motor

---
Tags: servo, code-review, code-optimization
---


# Question
Title: Some code only works when USB serial port connected
I'm using Arduino Uno as my microcontroller, but I got a strange behavior. I need to run several function at the same time. One to get GPS and temperature value then send every value to user's phone number when a request received by SIM800L GSM module, and another to display those value on I2C LCD. Everything works fine when my USB port connected to my computer. But when I tried to unplug the USB and using external power source from Li-Po battery I can't get a response from SIM800L module whenever I send a request message.

When I tried to create a separate program (just received a request message and then sent a response by SIM800L) it works fine even though using external power supply (Li-Po battery) without USB port plugged in. Another strange behavior is when I was using both of Li-Po battery and USB port connected then unplugged the USB port it works fine again. But when I unplugged my battery and then plugged it again without USB port connected, SIM800L couldn't send a response. What is wrong ?

This is my full code:

```

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>
#include "DHT.h"

//sms
char ReceivedSms;
short DHT_OK=-1, GPS_OK=-1;
String DataSms;
int _timeout;
String _buffer;
String number = "+62811XXXXXX";

//dht
#define DHTPIN 5
#define DHTTYPE DHT11

LiquidCrystal_I2C lcd(0x27,20,4);
SoftwareSerial sim800l(2,3);
DHT dht(DHTPIN, DHTTYPE);

// The TinyGPS++ object
TinyGPSPlus gps;

void setup()
{
  Serial.begin(9600);
  sim800l.begin(9600);
  dht.begin();
  lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
  _buffer.reserve(50);
  ReceiveMode();
}

void loop()
{
   displayInfo();

}

void displayInfo()
{
  String RSMS;

  while(sim800l.available() > 0) {
      ReceivedSms = sim800l.read();
      RSMS.concat(ReceivedSms);
      GPS_OK = RSMS.indexOf("All");
   }

  if (gps.location.isValid())
  {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Latitude  : ");
    lcd.println(gps.location.lat(), 6);
    lcd.setCursor(0,1);
    lcd.print("Longitude : ");
    lcd.println(gps.location.lng(), 6);
    delay(5000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Suhu       : ");
    lcd.println(dht.readTemperature());
    lcd.setCursor(0,1);
    lcd.print("Kelembaban : ");
    lcd.println(dht.readHumidity());
    delay(2000);

    if(GPS_OK!=-1)
        {
        String link = "http://www.google.com/maps/place/" + String(gps.location.lat(),6) + "," + String(gps.location.lng(),6);
        DataSms = "ALL\nSuhu = "+String(dht.readTemperature(),1)+" C"+" \nKelembaban ="+String(dht.readHumidity(),1)+" %"+" \nMaps = "+link;
        SendMessage();
        ReceiveMode();
        GPS_OK = -1;
        }
  }
  else
  {

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("GPS not found");
    delay(2000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Suhu      :");
    lcd.println(dht.readTemperature());
    lcd.setCursor(0,1);
    lcd.print("Kelembaban:");
    lcd.println(dht.readHumidity());
    delay(2000);

    if(GPS_OK!=-1)
       {
        DataSms = "ALL\nSuhu = "+String(dht.readTemperature(),1)+" C"+" \nKelembaban ="+String(dht.readHumidity(),1)+" %"+" \nMaps = Lokasi Tidak Ditemukan";
        SendMessage();
        ReceiveMode();
        GPS_OK = -1;
       }
  }

}

String _readSerial() {
  _timeout = 0;
  while  (!sim800l.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (sim800l.available()) {
    return sim800l.readString();
  }
}

void ReceiveMode() {
  sim800l.println("AT");
  delay(100);
  sim800l.println("AT+CMGF=1");
  delay(100);
  sim800l.println("AT+CNMI=2,2,0,0,0");
  delay(100);
}

void SendMessage()
{
  //Serial.println ("Sending Message");
  sim800l.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  //Serial.println ("Set SMS Number");
  sim800l.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Hello from 800L...";
  sim800l.println(DataSms);
  delay(100);
  sim800l.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}

```

Just for your information I'm using Li-Po battery 7.4V 2200mAh

# Answer
> 1 votes
I have solved my problem by click on Arduino reset button pin after all of my components got a power supply. Somehow I can't explain why does it work after doing that simple thing

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


title: Bitwise write to analog PIN

text:
# Question
Title: Bitwise write to analog PIN
I am just starting to learn bitwise operands and here is my question. To do this:

```
pinMode (13, OUTPUT);
digitalWrite (13, HIGH);

```

bitwise I can do like this:

```
DDRB |= B00100000;   //set PIN13 as OUTPUT
PORTB |= B00100000;  //set PIN13 HIGH

```

but how I can do this:

```
analogWrite(9, 200);

```

I know how to convert DEC numbers to BIN, but how to send this number to PWM PIN? I cannot find any good example in web.. Thank you!

# Answer
Note, you haven't specified, which Arduino you are using. I'm assuming a Atmega328p based Arduino (Uno, Nano, Mini) here, though the principle works with every AVR microcontroller, that has this hardware).

With `analogWrite()` are are not sending data bitwise out of a pin. It configures the hardware Timer for setting that pin at a specific frequency and with a specific duty cycle. So `analogWrite()` actives a totally different piece of hardware inside the microcontroller.

To do this without the Arduino function `analogWrite()`, you first need to decide, which way to go:

* You can generate an interrupt through the hardware Timer and then set the wanted pin by software inside the ISR (which gives you free choice of the pin, but also introduces some jitter in the signal)
* or you can let the hardware Timer itself toggle the pin, which does not involve any software for running (that means you can only use one of the 2 pins, that are associated with the corresponding Timer, but you will get a much more stable signal)

There are lots of tutorials on the web on how to do that. A search for "arduino timer register pwm" gave me some promising results, for example this one, where they explain, how to get PWM with the Timer1 registers and a free to choose frequency. (That is a 3 part series, one part for each Timer. Part 1 for Timer 0 is here, though you might want to keep Timer 0 as it is, so that functions like `delay()` and `millis()` still work as normal). There are also many such questions on this site, for example this one.

Another very important source for anything hardware related is the datasheet of the corresponding microcontroller. For the Uno, Nano or Mini that is the Atmega328p, which datasheet can be found on the microchip site here (or when googling for the microcontroller name)
> 2 votes

---
Tags: analogwrite
---


title: Bit Bang signal generation

text:
# Question
Title: Bit Bang signal generation
```

  #include <Wire.h>
  #include <LiquidCrystal_I2C.h>
  #include "digitalWriteFast.h"

  #define BUTTONPIN 2
  #define FDCSPIN 6
  #define CIPIN 5
  #define SPEAKERPIN 4

  float RPM=1000.0;
  int PWus=1.5*1000.0;
  int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
  int totalCnt;
  int CIState=B00000000;
  bool Buttonstate=0;
  LiquidCrystal_I2C lcd(0x27, 20, 4);

  void setup()
  {
    Serial.begin(9600);
    lcd.begin();
    lcd.backlight();
    lcd.clear();
    lcd.print("READY TO TEST"); // Waiting for button press
    pinMode(BUTTONPIN, INPUT);// Setting button as Input
    pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
    pinMode(CIPIN, OUTPUT); // Cylinder Identification
    digitalWriteFast(FDCSPIN, LOW);
    digitalWriteFast(CIPIN, LOW);
  }

  void loop()
  {
   Buttonstate=digitalReadFast(BUTTONPIN);
   if(Buttonstate==1)
   {
    delay(5);
    if(Buttonstate==1)
    {
      runInjectorTest();
    }
   }
  }
  void runInjectorTest()
  {
    lcd.print("Test Run");
    playtesttone();

      for(totalCnt=0;totalCnt<8000;totalCnt++)
      {

        PORTD=CIState;
        delayMicroseconds(PWus);
        PORTD=PORTD^B01000000;
        delayMicroseconds(FDCSoffset);
        if(totalCnt%4==0)
        {
          CIState=CIState^B00100000;
        }
      }
    totalCnt=0;
    playfinishtone();
  }
  void playtesttone()
  {
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
  }
  void playfinishtone()
  {

    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);

  }

```

I am trying to generate 2 signals using the code above and this output is

From the image, the lime green signal is called FDCS and the other is called CI. Note that the scope shows the inverted form of the signal. I want the falling edge of CI to match with the Falling edge of the 5th FDCS signal (right now rising edge is matching with the falling edge of the CI signal). But the Rising edge of the CI signal should match with the Rising edge of the first FDCS signal (which it's already doing). How do I change my code to do this?

# Answer
If I understand correctly, you signal has a period of 8 FDCS pulses: 4 with CI high and 4 with CI low. Since the rising and falling edges of CI do not happen at the same place relative to the FDCS pulses, you should handle these separately.

I suggest something like the following. Note that, as I do not know what signal(s) your setup inverted, I just try to reproduce what you show on the scope, with non inversion:

```
uint8_t portState = 0;
for (int totalCnt = 0; totalCnt < 16000; totalCnt++)
{
    // On pulse 0, CI rises with FDCS.
    portState |= _BV(FDCSPIN);
    if (totalCnt % 8 == 0)
        portState |= _BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(FDCSoffset);  // pulse width

    // On pulse 4, CI falls with FDCS.
    portState &= ~_BV(FDCSPIN);
    if (totalCnt % 8 == 4)
        portState &= ~_BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(PWus);  // inter-pulse delay
}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to clear output buffer of Arduino Uno?
I have coded arduino for DHT11 which used to print humidity in first and temperature in second line. But some times when I open SerialPort I get absurd data.

# Answer
You can't.

The data you are seeing has already been sent by the previous execution of the sketch before the main MCU was reset. That data resides in a small buffer within the USB interface chip (or even within the USB CDC/ACM / USB UART driver itself, depending on your OS) to which you have no access.

You just have to ignore that data. The simplest way is to put a marker at the start of your program to indicate that whatever is receiving the data should start its receiving from this point on. Something like:

```
Serial.println();
Serial.println("START");

```
> 3 votes

# Answer
I've circumvented this issue by sending a byte to the Arduino whenever I'm ready to receive data using this quick-and-dirty method:

```
if(Serial.available() > 0) {  // At least one byte is available
  Serial.println(millis());
  Serial.read();  // Read the (one) character to empty the buffer
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Unexplained behavior of char array after using `deserializeJson`
I'm using `RF24` library to send messages between 2 MCU's : 1) ESP8266 (no Wifi, same code can be compiled to any Arduino board) 2) pro-Micro.

Message is sent in JSON format, while using `ArduinoJSON` library to `serialize` and `deserialize` messages.

Altough entire code works as expected, I get an error in "RFread" function, which `_readmsg` array loses its content after using `deserializeJson`.

Attached below relevant **part** of "RFread" function. Explanations in code below. Please notice "Mark \[X\]" in code and Serial output:

```
char _readmsg[32];                                <---- Storing input in this array
    char t2[32];                                  <---- variable to clone value
    radio.read(&_readmsg, sizeof(_readmsg));      <---- getting RF input and store it in `_readmsg`
    strcpy(t2, _readmsg);                         <---- cloning, part of error seeking

    Serial.print("first: ");                      <---- printing initial value stored. OK. marked [A] in Serial output
    Serial.println(_readmsg);
    Serial.print("duplicate: ");                  <---- printing clone. OK. marked [B] in Serial output
    Serial.println(t2);

    if (key != nullptr)                           <--- check if "msg" key was sent in message
    {
      StaticJsonDocument<80> DOC;
      deserializeJson(DOC, _readmsg);             <---- **error beyond this point**
      Serial.print("second: ");
      Serial.println(_readmsg);                   <---- printing wrong value. marked [C] in Serial output

      if (DOC.containsKey(key))
      {
        const char *outmsg = DOC[key];
        if (out != nullptr)
        {
          strcpy(out, outmsg);
          return true;
        }
      }
      else
      {
        Serial.print("third: ");
        Serial.println(_readmsg);              <---- still error. marked [D] in Serial output
        Serial.print("duplicate2: ");
        Serial.println(t2);                    <---- clone variable is OK. marked [E] in Serial output
        strcpy(out, t2); // if key not present, return entire message
        return 0;
      }

```

and in Serial port:

```
message sent OK   <---- irrelevant for debug

15:18:14.934 -> first: {"id":"Port","msg":"fff"}       <----[A]

15:18:14.934 -> duplicate: {"id":"Port","msg":"fff"}   <----[B]

15:18:14.934 -> second: id                             <----[C]

15:18:14.934 -> third: id                              <----[D]

15:18:14.934 -> duplicate2: {"id":"Port","msg":"fff"}  <----[E]

15:18:14.934 -> Error. no such key. got reply: {"id":"Port","msg":"fff"}

```

Is there a reason for that ? is it a bug ?

# Answer
When you pass a `char*` input to deserializeJson(), it alters the input to avoid making useless copies.
This is the "zero-copy" mode of ArduinoJson.

In this mode, the JSON parser modifies the input in-place. The following modifications are performed:

1. `'\0'` are inserted at the end of each string
2. Escaped special characters (like `\n`) are unescaped

Example:

```
char[] json = "{\"hello\":\"world\"}";
deserializeJson(doc, json);

```

After executing the line above, the input variable probably contains something like: `"hello\0world\0"`.

You can find more details in the documentation
> 4 votes

# Answer
To sum up Benoit Blanchon answer:

in original code:

```
deserializeJson(DOC, _readmsg);

```

changes to:

```
deserializeJson(DOC, (const char *)_readmsg);

```
> 0 votes

---
Tags: array, json
---


title: Error compiling for board Arduino Nano

text:
# Question
Title: Error compiling for board Arduino Nano
I have multiple Arduino Nano boards. I am able to compile or upload code only once. If I try to compile/upload again I get an error: "Error compiling for board Arduino Nano". However there is a workaround: to be able to upload again I change something in tools menu for example board or processor. I tried all of the nanos and all of the ports.

The error message is below (verbose is enabled).

The problem appeared from nowhere. Thank you in advance!

```
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
Error compiling for board Arduino Nano.

```

# Answer
> 1 votes
I resolved this issue by installing older arduino ide version.

# Answer
> 1 votes
ive been having this same issue for the last 9 or so month it is driving me insane i have uninstalled and reinstalled arduino in every way i possibly can... using revouninstaller and cccleaner and even tried starting a new user account on my computer and installing it and i still have this issue.. i can only click verify or upload one time and the very next time as soon as i click it i get the exact same error message.. and not just for the nano for every board i have on the list,, it is so irritating!!!! the only work around i have found. well the simplest is to change back and forth from nano old bootloader to atmega328.. or switch back and forth from nano and uno in the boards menu..

so when im trying to put multiple codes together and get it to compile every time i click verify i have to change the board info.. or it instantly says

Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr Detecting libraries used... Error compiling for board Arduino Nano.

about to just throw it all in the trash

---
Tags: arduino-ide, compilation-errors
---


# Question
Title: always detects same pin as HIGH even when its not connected
Im practicing with an arduino UNO board (I'm a begginer) and I'm trying to turn some LED's on depending on which analog pin is connected to 5V. Here's my code:

```
int statusLed = 11;
int out1 = 2;
int out2 = 3;
int out3 = 4;
int out4 = 5;
int in1 = A0;
int in2 = A1;
int in3 = A2;
int in4 = A3;
int statusLedBrightness = 3;
int incBrillo = 3;
int fadeDelay = 5;

void blinkFade(int pin){
  analogWrite(pin, statusLedBrightness);
  statusLedBrightness = statusLedBrightness + incBrillo;
  if (statusLedBrightness <= 0 || statusLedBrightness >= 255){
    incBrillo = -incBrillo;
  }
  delay(fadeDelay);
  }

void wait(){
  digitalWrite(out1, LOW);
  digitalWrite(out2, LOW);
  digitalWrite(out3, LOW);
  digitalWrite(out4, LOW);
  blinkFade(statusLed);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(out1,OUTPUT);
  pinMode(out2,OUTPUT);
  pinMode(out3,OUTPUT);
  pinMode(out4,OUTPUT);
  pinMode(in1, INPUT);
  pinMode(in2, INPUT);
  pinMode(in3, INPUT);
  pinMode(in4, INPUT);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (analogRead(in1)>=500){
    Serial.println("1: ");
    Serial.println(analogRead(in1)); //Print "1" and the read of pin A0
    turnOff();
    digitalWrite(out1,HIGH);
  }
  else if (analogRead(in2)>=500){
    Serial.println("2: ");
    Serial.println(analogRead(in2));//Print "2" and the read of pin A1
    turnOff();
    digitalWrite(out2,HIGH);
  }
  else if (analogRead(in3)>=500){
    Serial.println("3: ");
    Serial.println(analogRead(in3));//Print "3" and the read of pin A2
    turnOff();
    digitalWrite(out3,HIGH);
  }
  else if (analogRead(in4)>=500){
    Serial.println("4: ");
    Serial.println(analogRead(in4));//Print "4" and the read of pin A3
    turnOff();
    digitalWrite(out4,HIGH);
  }
  else{
    Serial.println("Stand By");
    wait();
  }

}

```

The problem Im having is when I connect a wire from 5V to any analog pin (A0 to A3) it always runs this segment of code:

```
Serial.println("1: ");
Serial.println(analogRead(in1));
turnOff();
digitalWrite(out1,HIGH);

```

By my understanding it's detecting as if it always was A0 the one that is connected to 5V but i dont understand why is this happening or how to solve it.

This is a screen capture of serial monitor when 5V is connected to pin A2. It should print "3:" and the reading \[\]

# Answer
> 1 votes
You're not showing your schematic but I'm sure that you are simply leaving the Ax pins OPEN when you are not connecting them to your +V line. In that case they are "floating" and as such they can float HIGH or LOW or just about anywhere. What's happening is that when you hook up +V to any of them, that has the side-effect of pulling at least A0 HIGH along with it since you have allowed it to float.

Two things to do here:

1. Don't allow lines to float and expect deterministic behavior. Tie them to +V or to GROUND when you are not using them.
2. Pull the Ax lines to +V or GND via a resistor like 10K Ohms. This will prevent them from floating and will give you predictable results.

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


# Question
Title: Can't upload code to Arduino board on Mac
I'm using a MacBook Pro with 10.13.6, an Official Arduino Uno Board and Arduino 1.8.13 IDE.

I'm having troubles uploading code to the Arduino Board. I have 5 ports available:

* dev/cu.-AvnetaSPPPort
* dev/cu.Bluetooth-Incoming-Port
* dev/cu.SRS-BTX300-DataInteract
* dev/cu.RS-XB41-BluetoothSeria-1
* dev/cu.UEMEGABOOM-LWACP-2

I'm not sure if any oh these ports is the correct one but I've already tried all of them and I keep getting errors like: "`avrdude: ser_open(): can't open device "/dev/cu.-AvneraSPPPort": Resource busy`"

Some weeks ago I was trying Arduino on the same computer and all went good but right now I can't get it to work, however I don't remember wich port was selected.

In the IDE the board I have selected is "Arduino Uno" and as Programmer option I have "AVRISP mkll".

Does anyone know how to solve this?

# Answer
> 2 votes
I finally solved the problem.

Although the Board has no information about being a clone (it only says "Uno" and was provided by the faculty so I think it is official), I was looking on the web for similar problems and found out that installing CH340 Driver was working for a lot of users. So that was what I did and now it works like a charm.

# Answer
> 0 votes
List the ports again, with- and without the Arduino plugged in: open the built-in Terminal app (usually in Applications/Utilities) and type 'ls /dev/tty.\*'. The difference will tell you the Arduino's device name.

"Resource Busy" generally means something else has already connected to that port. Is a terminal-emulator program running and connected to that port? If you're using a terminal-emulator other than the one built in to the IDE, you have tell it to disconnect before you can upload to the Arduino.

---
Tags: arduino-uno, arduino-ide, port-mapping, mac-os, upload
---


# Question
Title: Test level shifter with Arduino and some data
Below is a reference to a logical level bi-directional converter (aka level shifter) I purchased on Ebay. I've soldered the 12 pins (6 for each piece) to the level shifter so that it fits on my bread board.

http://www.ebay.com/itm/121868205078?\_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

This may sound trivial, but I'd like to troubleshoot the level shifter with communication both ways (Rx and Tx) to make sure it's working properly. I've got a constant 4.85v (5V) going to the HV pin, and a constant regulated 3.24V (3.3V) going to the LV pin, along with ground to both GND pins. Right now, I'm using pin0 (Rx) and pin1 (Tx) on the Arduino Mega 2560.

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

void loop() {
  delay(1000);
  Serial.println("Test");
}

```

How can I test this level shifter without any fancy components? How could I write a program to toggle an LED both on LV1 and HV1 pins, by modifying the program above? Please note, that even though the Arduino runs on 5V, I am not using the Arduino as my HV power source.

# EDIT (per comment 3 by @Paul):

Test:

* Burn blank sketch into Arduino
* Connect 5V (Arduino 5V) to HV pin
* Connect GND (Arduino GND) to GND pin on same side as HV pin
* Connect 3.3V to LV pin
* Connect GND (from 3.3V power source) to GND pin on same side as LV pin
* Connect Arduino Tx pin to channel 1 (HV1)
* Connect Arduino Rx pin to channel 2 (HV2)
* Short channel 1 to channel 2 with jumper wire

When all of this is connected, and I open the Serial Monitor on Arduino IDE, anything I type will echo back exactly what I typed. And when I disconnect one of these jumpers, it doesn't echo back. So it seems to work.

# Answer
> 2 votes
You don't need to write any program.

First, note that this is (or at least purports to be) an I2C level shifter. This means that it does *not* actively pull up anything; it only actively pulls down. You are supposed to provide pull-ups somewhere in your circuit.

To test it, pull up HV1 and LV1 with 10K resistors to HV and LV respectively; measure the voltage on both sides to verify you are pulling to ~5V and ~3.3V respectively.

Ground HV1, check that LV1 is low.

Ground LV1, check that HV1 is low.

Ta-dah!

# Answer
> 1 votes
@paul i have done some but when i connect channel1 to channe2 via jumper wire arduino stop working and text stop coming on serial monitor.

---
Tags: arduino-mega, led
---


title: LM35 temperature decreases when heated

text:
# Question
Title: LM35 temperature decreases when heated
I have a question regarding the LM35. The sensor is supposed to have values that are to be directly proportional. But instead of the temperature increasing, the sensor values decrease.

This is my setup below. It seems to be a standard setup in different LM35 tutorial pages.

```
const int sensor= A0; // Assigning analog pin A0 to variable 'sensor'

void setup() {
  pinMode(sensor,INPUT); // Configuring sensor pin as input
  Serial.begin(9600);
}

void loop() {

  float reading=analogRead(sensor); //Reading the value from sensor
  float vout= (reading*5000)/1024;
  float temp= vout/10;

  Serial.print("in DegreeC= ");
  Serial.print(temp);
  Serial.println("");

  delay(500); //Delay of 1 second for ease of viewing

}

```

These are the results. From room temperature, I applied heat through the use of a lighter and it went lower instead of higher.

I read somewhere that it has something to do with the power supplied by the Arduino. However, when I used a 12V supply to power the Arduino, the readings became very erratic and unstable.

## **UPDATE:**

I have finally returned from the city (Took a long time because of Quarantine Restrictions) and I brought 3 LM35 from another shop. All 3 of the new LM35 worked as intended and didn't lower its temp reading when exposed to heat (With the same configuration). I could rule out these possibilities as to the reason why the LM35 didn't work.

**1. Manufacturing Defect** \- all **three** of the LM35 didn't work as intended. They all had their temperature lowered when exposed to heat. There could be a defect in the manufacturing process because it doesn't work as advertised. (Leaning towards this)

**2. Static Electricity** \- I remember receiving the LM35 in a plastic bag as packaged by the shop. It could have been affected by static electricity and damaged the circuit inside (on all three though?). The LM35s I received recently had been packaged in those electrostatic discharge protection packaging so it could have probably contributed to it? I need more insight on this I apologize for not being able to properly word it out.

There could be more but these are the most I could come up with as a conclusion.

# Answer
> 1 votes
You are reading A5 but in your diagram you show it hooked up to A0:

Change your code to this and I believe it will work:

```
const int sensor= A0; // Assigning analog pin A0 to variable 'sensor'

void setup() {
  pinMode(sensor,INPUT); // Configuring sensor pin as input
  Serial.begin(9600);
}

void loop() {

  float reading=analogRead(sensor); //Reading the value from sensor
  float vout= (reading*5000)/1024;
  float temp= vout/10;

  Serial.print("in DegreeC= ");
  Serial.print(temp);
  Serial.println("");

  delay(500); //Delay of 1 second for ease of viewing

}

```

The data you are reading from A5 is indeterminate and just happens to decrease as A0 increases.

================================================================================ UPDATE:

Ok, so you corrected yourself and are reading the correct pin in spite of what your schematic shows. Please explain this:

```
float vout= (reading*5000)/1024;
float temp= vout/10;

```

I think you want:

```
float vout = (reading/1024.0) * 5000.0;
float temp = vout/10.0;

```

You are carelessly mixing floating point and integer math.

---
Tags: arduino-uno, lm35
---


# Question
Title: Can I safely connect my A6 GPRS module to this 5V 2A phone adapter
I have an A6 GPRS module, and my Samsung phone power adapter has output of 5V and 2A. But it also says 9V and 1.6A

My Phone's Adapter

So would it damage my A6 GPRS Module if I plug this to it via the micro usb power port? (especially because it also says 9V)?

My A6 GPRS module

# Answer
The standard output for USB is 5V but there are some such chargers that will output more for enhanced charging output on devices that support it.

In this case the adapter will default to 5V and will only upgrade to 9V if the device requests it. The GPRS module will not request 9V and so the adapter will continue to provide only 5V which is what you want.
> 1 votes

---
Tags: gsm, voltage-level
---


# Question
Title: Problem connecting 2 74HC595 8 bit shift registers in cascading connection
I have now successfully learned how to control a single 8 bit shift register 74HC595 with Arduino UNO but whenever I tried to connect another one with the first shift resistor via cascading connection just like the image shown below (well I didn't use the 10uf capacitor between positive and negative terminal), the first shift register only outputs as desired but the second shift register, connected to a cascading connection, does not seem to work...

Here is the code.

```
    int latchPin = 10;  // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 11;  // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 9;    // Data pin of 74HC595 is connected to Digital pin 4

byte leds = 0;      // Variable to hold the pattern of which LEDs are currently turned on or off

/*
 * setup() - this function runs once when you turn your Arduino on
 * We initialize the serial connection with the computer
 */
void setup()
{
  // Set all the pins of 74HC595 as OUTPUT
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  Serial.begin(9600);
}

/*
 * loop() - this function runs over and over again
 */
void loop()
{
  leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
  updateShiftRegister();
  delay(500);
  for (int i = 0; i <= 16; i++) // Turn all the LEDs ON one by one.
  {
    bitSet(leds, i);        // Set the bit that controls that LED in the variable 'leds'
    updateShiftRegister();
    delay(500);
  }

 /* The loop above should repeated 16 times as there are 2 shift resistors, each of them containing 8 and we need to lit up all 16 LEDs*/

}

/*
 * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
 */
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

```

so is it my code or wiring problem?

I have read many articles on internet to make myself get it understood but unfortunately, none of the articles satisfied me.

many thanks for giving me a bit of your precious time...

# Answer
I am really very sorry to say that after a long inspection , i have found that

shift register clear (pin 10) pin of the second shift register remained inactivated due to loose connection of power, after fixing it, all shift registers are working very fine.

I do really apologize to all those friends who came to help me, for wasting their time, i am really very sorry for that...

all problems are solved now.
> 0 votes

---
Tags: arduino-uno, led, shift-register, multiplexer
---


title: Datasheet of arduino power jack

text:
# Question
Title: Datasheet of arduino power jack
Can we find out about the parts that the arduino uses?

I want to make a shield, and i bought the same power jacks.

And i thought that there would be two pins, one for power, one for GND. However, it has three pins.

The supplier did not have a datasheet, and right now i do not have a continuity beeper either, so could i see its datasheet somewhere, or does anyone know why it has three pins?

# Answer
> 1 votes
This is an image from a typical power jack:

The specific ones you bought may differ. The vendor should be able to supply you with a manufacturer and P/N or an actual data sheet.

Image copied from: https://www.we-online.de/katalog/datasheet/6941xx301002.pdf

---
Tags: power, shields, components
---


# Question
Title: Module that can both detect Voltage (12V) and Control current
I need a module for ARDUINO that can both detect Voltage (12V) **and** Control current between 2 pins (12V), like a relay on another device

I have found relay modules to control pins and another module for 4-channel Voltage detection, but it seems like a lot of components and wiring.

Is there any module that can do both?

# Answer
> 2 votes
You don't need another module to detect voltage on an Arduino. The UNO, which I assume you are using, has 6 analog inputs (A0-A5) that can directly read voltage. The only problem is that you want to measure a voltage up to 12V and the Arduino can only handle 5V. So the solution is to DIVIDE that using two resistors in a voltage-divider configuration so that you only see 5V at the Arduino when there is 12V on the signal.

From here: https://www.electroniclinic.com/what-is-a-voltage-divider-or-potential-divider-formula-and-practical-uses/

you can see how to make one:

As far as controlling a "current" that is usually done with a relay. There are no on-board relays but there are the digital outputs that can drive a small relay or can be connected via some other circuitry like a couple of transistors to drive just about any size relay.

# Answer
> 0 votes
I would suggest opto-isolators for both directions.

simulate this circuit – Schematic created using CircuitLab

For the Ardiuno sending control signal you have to know which way round to connect to the inputs of your controller. Chances are one will be ground - that's "CTL Low".

---
Tags: relay, voltage
---


# Question
Title: How to read/write variables persistenly on Arduino Due (no EEPROM/shield)?
I am relatively new to Arduino and I am currently writing some code to control a relay board. The on/off times are provided by the user at run-time and should be stored persistently (EEPROM or flash) in case of power-down.

On my Uno I worked with the EEPROMex library and that worked well. Now I have a Due which doesnt have any EEPROM and I am struggling how to store variables persistently. Specifically, I dont know how to access whatever I wrote to the flash memory previously. In the example below the content of test\[\] is obviously overwritten on every restart.

```
PROGMEM int test[] = {1, 2, 3, 123, 23};

void test()
{
  Serial.println((long)test);
  for (int i = 0; i < 5; i++)
  {
    Serial.println(test[i]++);
  }
}

```

I noticed that the address does not change during re-starts, so I I tried reading/writing beyond index 4. This out-of-bounds read/write worked, I guess since I am anyway not storing anything else. Interestingly even this memory which is out of the array is overwritten on power-up.

So: How do I store on unser input data (variables) persistenly on an Arduino due without using any shields?

# Answer
I really hope that somebody knows differently, but I'm fairly sure that the answer is that you can't directly save runtime data back to the Arduino Due board. I've looked into this myself and have only found answers saying "wire up an external EEPROM" or similar. Whilst it seems that it should be technically possible to write into unused (or pre-reserved) areas of the program memory, I suspect that the CPU has to be put into a special mode to do this, which is very probably only possible from the bootloader when flashing a new program to it.

I've chosen to go with FRAM chips for data storage. Link to mine. They are difficult to wire up - the only ones I found were in surface mount packages (although some hobby retailers sell them mounted to little boards with header pins), but they are very cheap, very durable (you can write to them a great number of times before they wear out), operate at high speeds and you can read/write single bytes from/to them. Other storage chips often require you to write whole "pages" of data at a time which can mean reading in the existing data, modifying it, then writing it back.

Additional comments: In your original question, you state that the contents of your PROGMEM located array must be restored on restarts. I don't think this is the case. That would suggest that the contents are stored elsewhere and code is in place to overwrite them, however it could be the case that they are copied into working RAM, which would mean that the PROGMEM macro is not actually doing anything on the Due - which may well be the case.

Modify your code to change one of the values of the array (within the bounds of the array!) and then print its value out again after changing it. If the value printed has changed then this means that PROGMEM is not actually doing what it is supposed to do on the Due, which would be a real shame.
> 2 votes

# Answer
This library called DueFlashStorage was created by Sebnil and is in the Arduino Library Database Tool!

It basically takes the EEPROM functionality and applies it to the Flash storage on the DUE. The only drawback is that the flash memory gets erased every time you upload a new (or new version of a) sketch.

For my application that works but for other applications that might not be what you want!

Click here to go to the GitHub for it called DueFlashStorage
> 2 votes

# Answer
Without an external device you won't be able to store data permanently. So it might not be a full shield, but you'll have to add SOMETHING. Depending on how much data you need you might use components that have EEPROM as a side feature. For instance, as explained here, the DS1337 RTC module has 56 spare bytes of EEPROM^H^H^H^H^H^H Non-Volatile RAM available. I know, it sure isn't much, BUT it might be enough for your needs, depending on how much you need to store.

And of course it provides you with DateTime capabilities, wich could come in handy.

Aside from this, there are EEPROM chips mounted on a small board, with DIP switches to set the I2C address, which would be very discrete, and could store a large amount of data. See this one for instance.
> 1 votes

---
Tags: arduino-due, flash, eeprom, eepromex
---


# Question
Title: RF24- Splitting and sending a longer than 32 byte payload
In order to send a long payload I've created the following function:

```
void splitMSG(const char *msg, const int arraySize, const int len)
{
  Serial.print("Array size: ");
  Serial.println(arraySize);
  byte numPackets = (int)(arraySize / len);
  byte P_iterator = 0;
  if (arraySize % len > 0)
  {
    numPackets++;
  }
  Serial.print("num_Packets: ");
  Serial.println(numPackets);

  while (P_iterator < numPackets)
  {
    char t[len + 1];
    char *ptr1 = msg + P_iterator * (len);
    strncpy(t, ptr1, len);
    t[len + 1] = '\0';
    Serial.println(t);
    radio.write(&t, sizeof(t));
    P_iterator++;
  }
}

```

The split message is sent to the serial monitor to verify it is as expected.

\**On the sending device :

```
void loop()
{
  radio.stopListening();

  char send_msg[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";  // <----- input msg
  splitMSG(send_msg, sizeof(send_msg), 10);                  // <----- split to 10 bytes a packet
  delay(1000);
  // Serial.println("±±±±±±±±");
}

```

On the serial monitor I get:

```
08:06:17.569 -> Array size: 37
08:06:17.569 -> num_Packets: 4
08:06:17.569 -> 1234567890
08:06:17.569 -> ABCDEFGHIJ
08:06:17.569 -> KLMNOPQRST
08:06:17.569 -> UVWXYZ

```

\**On the receiving device:

```
void loop()
{
  if (radio.available())
  {
    while (radio.available())
    {
      char buf[32];
      radio.read(&buf, sizeof(buf));
      Serial.print("got msg: ");
      Serial.println(buf);
      radio.flush_rx();
    }
  }

  delay(100);
}

```

On the serial monitor I get:

```
08:08:18.462 -> got msg: 1234567890⸮⸮⸮⸮
08:08:18.561 -> got msg: ABCDEFGHIJKLMNOPQRSTUVWXYZ
08:08:19.555 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
08:08:20.549 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
08:08:21.576 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
08:08:22.570 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
08:08:22.669 -> got msg: UVWXYZ

```

Does the problem with `radio.write` ' buffer , or the way I split the message ?

# Answer
```
t[len + 1] = '\0';

```

Your array is declared as having `len+1` bytes of storage. So the last index is `len`, not `len+1`. You're writing the zero one past the end of the array, thus you're not transmitting it (and sending one byte of "garbage" instead).
> 2 votes

---
Tags: nrf24l01+, array
---


# Question
Title: Can't get deep sleep to work on Wemos D1 ESP8266
I have a Wemos D1 (ver. 2015-08) and I am trying to get it to sleep. I've managed to get it generally up and running/got wifi to work etc, but the deep sleep function is beyond me.

I tried connecting RX\<-D0 pin to RESET, also tried with a 10k resistor. Neither worked. I then tried D2 (listed as gpi016 on the back of the board) to RESET, this also didn't work. Any ideas? It seems like this would be an incredible chip if I could get it to sleep. The example sketch below uploads fine and contacts the serial monitor, up until the point it sleeps.

```
 /* Deep Sleep - Blink
 *
 * Blinks the onboard LED, sleeps for 10 seconds and repeats
 *
 * Connections:
 * D0 -- RST
 *
 * If you cant reprogram as the ESP is sleeping, disconnect D0 - RST and try again
 */

// sleep for this many seconds
const int sleepSeconds = 5;

void setup() {
  Serial.begin(9600);
  Serial.println("\n\nWake up");
  pinMode(BUILTIN_LED, OUTPUT);
  // Connect D0 to RST to wake up
  pinMode(D0, WAKEUP_PULLUP);
  // LED: LOW = on, HIGH = off
  Serial.println("Start blinking");
  for (int i = 0; i < 20; i++) {
    digitalWrite(BUILTIN_LED, LOW);
    delay(100);
    digitalWrite(BUILTIN_LED, HIGH);
    delay(100);
  }
  Serial.println("Stop blinking");
  Serial.printf("Sleep for %d seconds\n\n", sleepSeconds);
  // convert to microseconds
  ESP.deepSleep(sleepSeconds * 1000000);
  Serial.println("sleep finished");
}

void loop() {
}

```

# Answer
> 3 votes
I had to physically connect D0 to RST to wake up the wemos.

# Answer
> 1 votes
In fact it works well using a wire between D2 and RESET pins. But sending the program to the board, you must first disconnect these pin (the arduino IDE will send a hard reset during process, so this D2 reset must not be in place). When the program is uploaded to the ESP and start running, you connect D2 and RESET and it works well, ESP will go to deep sleep mode as expected.

Because it is not a mini, the board has another chip (usb) that will not got to sleep mode, so on my board it will use about 17mA in deep sleep (compare with 80mA in wifi normal operation). Still worth the trick.

---
Tags: esp8266
---


title: arduino parking lot

text:
# Question
Title: arduino parking lot
I want to make a project where there is a parking lot and a ir sensor which senses when a car comes and displays a message on lcd saying to insert a rfid card and then it opens a gate and there are many ir sensors in the slots to detect where there are cars and sends a message saying which slot is free.but the problem is many parts need the 5v pin but there is only one on the arduino board so i wanted to ask if any problem will occur if we connect multiple parts to one 5v pin if there will be a problem what is the work around.

# Answer
You can connect multiple devices or modules to the same 5v pin, as long as it does not exceed the maximum current that the on-board 5v regulator can handled. If you are using a genuine Arduino Uno, it has a NCP1117 which has a maximum current of 1A. If you don't have a genuine Arduino Uno, check the part number and find the datasheet to find out the maximum current.
> 0 votes

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


title: Attiny85 Clone Cannot set P1 to input

text:
# Question
Title: Attiny85 Clone Cannot set P1 to input
Everything i read about the chinese Digispark attiny85 clones says you can use p0-5 as digitlal I\O (p5 as after fuse reset)

Simple test code for a button will not let me use P1 as an input tied to a simple button.

The code below works on p0,p2,p5 but will only interrupt the LED that is set to on, on P1.

```
#include "DigiKeyboard.h"

//pins 3 & 4 used for usb connection
bool buttonState1 = 0;

void setup() {
  pinMode(1, INPUT);
  digitalWrite(1, HIGH); //turn on pull-up resistor
}

void loop() {

    if (digitalRead(1)!= buttonState1){
      buttonState1 = digitalRead(1);
      if (buttonState1 == LOW)DigiKeyboard.print("test1");
    }

}

```

# Answer
> 2 votes
I had a quick look into the Schematics of a digisparc board. P1 is hardwired over an LED and a resistor to GND. If you turn on the PULL UP resistor for P1 the LED should light up and the voltage at P1 would be very low (it depends on the voltage divider that is built from the PULL UP resistor and the LED resistor); so the P1 reading should be LOW. If you connected the Button to GND and press it, the voltage at P1 drops to 0. But, that does not affect the LOW state. The program does not react. The LED turns off, because it is not powered anymore.

You could try to connect the button to +5V and do not setup a PULL UP resistor for P1. If you press the button the LED should light up and +5V should be at P1. It should change its state from high to low. (I did not tried that; but I see no reason, why it would not work).

---
Tags: led, input, attiny85, digispark
---


# Question
Title: Most precise way to measure linear distance travelled by a wheel
Suppose a bot with wheels is traveling in a a straight line, and we want to measure this linear distance traversed by it as accurately as possible.

One of the ways is to use an optical encoder to measure the angle of rotation of the wheels and get the linear distance traveled.

Another way could be to use the data from accelerometer and get the linear distance traveled.

Which of these two methods would be better? Is there a third method which is more precise than the previous two?

# Answer
If you measure one of the free running wheels (with no motor connect to it), it depends on the traction of the wheel, but that could be fairly accurate.

If you move horizontally a simple accellerometer (1 axis) would be great. But if you have a vertical component, then you can not distinct between accelleration and weight force (Einstein). If you use a 3 axes accellerometer, you can compute/extract the robots moving speed (subtract the G component = 9.81 m/s²) and thus the distance. You have to use vector arithmetic in this case.

If the ground has enough "structure" you could use an optical sensor (like optical mice have).

If you have a reference object (e.g. a wall, a book) you could use a LIDAR sensor (https://en.wikipedia.org/wiki/Lidar) to measure the absolute distances at time points and compute the relative distance between these time points.
> 1 votes

# Answer
If you use an accelerometer, you have to integrate twice to arrive at distance travelled. These two integrations will also compound errors and noise, so the result won't be very accurate without many corrections.

If a wheel doesn't slip and is undriven, the results of counting wheel rotations should be fairly accurate when the robot is moving in a straight line.

Dragging a cheap computer mouse behind the robot and reading its output could also work, but I haven't tried that one yet.

The most accurate, if you can set up a flat object that reflects well enough at the destination of the robot, is probably LIDAR. Not cheap, but easy enough to do as long as the robot moves in a straight line.

Another option would be to count wheel rotations, and calibrate with LIDAR (or GPS for very long distances) and use the calibrated wheel rotations in the final version, or use two or more methods and do sensor fusion.
> 1 votes

---
Tags: sensors, accelerometer, robotics, rotary-encoder, imu
---


# Question
Title: Problems with inputting into serial monitor
I am currently working on a project where i take a frequency, and i want the code to take that value and use a formula to work out its mmh2O level. I use the Serial Monitor to input the values, but i have a problem. When writing the values e.g. "44.62352548","44.49151522". The value that is sent is wrong and displayed wrong.

I know the code i have written does not support this many signigicant figures from a float. And i have tried a few things to try and solve it but i cannot crack it.

I have tried using dtostrf() command, but i have never used this before and dont understand. Somebody from the arduino Forums had helped me out but it didnt seem to work. I have also tried formatting aswell, and that did not seem to work.

If anyone has any help and advice it would be much appreciated.

```
float level;
float myValue;

String msg1 = "Enter Frequency (type 0 to exit): ";
String msg2 = "Your Frequency is: ";

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

void loop()
{
  Serial.print(msg1);

  while (Serial.available() == 0);
  {

  }
  myValue = Serial.parseFloat();
  if (myValue == 0.0)
  {
    Serial.end();
  }
  else
  {
    freqConversion();
  }
}

 void freqConversion()
{
  level = (myValue-44.712)/-0.0285493333;
  Serial.println(myValue);
  Serial.print(msg2);
  Serial.println(level);
}

```

# Answer
> 2 votes
You have hit a bug in the implementation of `parseFloat()`.

This function reads the number you send as an integer, ignoring the decimal point, and stores it in a `long`. It then multiplies it by a scaling factor (a power of 0.1) in order to get the correct value. The problem is, if you provide too many significant digits, the integer overflows, and you get garbage. For example "44.64978683" is interpreted as

```
(long) 4464978683 * 0.00000001

```

but `(long) 4464978683` overflows and rolls over to 170011387, hence the result you get.

Simple workaround: do not provide so many significant digits. They are irrelevant anyway given the resolution of a `float`.

**Edit**: I did not find any bug report for this issue, so I submitted my own to the Arduino dev team.

**Update**: Per request of a maintainer, I submitted a pull request with a failing unit test revealing this bug. We then worked on a fix, which has now been merged to master. It should be published on the next release of ArduinoCore-API.

Note, however, that the AVR core does not yet use the common API repository. In the meantime, it may be worth submitting a pull request to ArduinoCore-avr that cherry-picks the fix from ArduinoCore-API.

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


# Question
Title: Finding Relatively Accurate Velocity Using an IMU
I am currently working on a project where I am trying to accurately find velocity in a handheld device using an IMU for about 30 seconds. I have been having major issues doing this because of large amounts of drift from poor calculations due to inaccurate sensor readings. I have tried tuning offsets for my sensor and using other sensor fusion libraries to find my linear acceleration.

At this point I don't know if I am doing something wrong, going about the process wrong, or if my sensors are just to inaccurate to accomplish this.

I am hoping if anyone may have recommendations on how to accomplish this from the ground up. I currently have two 9DOF IMUS listed below. The first one I tried to use the predefined linear acceleration function to find velocity in ndof mode, using bosch calibration steps. The second i spent hours tuning the offsets on to get linear acceleration and it came out much worse than the first sensor. For the second I can include code but I used the madgwick from the Adafruit\_AHRS library for the sensor fusion for sake of time.

Any help is appreciated.

1. https://www.adafruit.com/product/4646 (BNo055 first board)
2. https://www.adafruit.com/product/3463 (FXOS8700 + FXAS21002 second board)

# Answer
Integration of acceleration to derive velocity is a difficult task. This is the first step in dead reckoning. Consider some of the following options to improve accuracy:

1. Some IMUs can be adjusted to increase sample speed. If the acceleration is sudden, more samples my improve the accuracy of the calculated velocity.
2. Try aligning just 1 of the axes of the IMU chip in the direction of acceleration. Do this to simplify the problem. Depending on the Arduino you are using, the processor may not have the power to perform the trig functions necessary for anything except acceleration only along 1 of the IMU's axes.
3. Take care of loosing significant digits. If using integers, try multiplying everything up. For example instead of 1 equaling 1 meter multiply the value up such that 1000 equals 1.000 meters. Now integer math can be used to calculate down to the mm.
> 1 votes

# Answer
For more context I did ask BOSCH directly about this issue and explained my setup in more detail.

https://community.bosch-sensortec.com/t5/MEMS-sensors-forum/BNO055-Outputting-Bad-Linear-Accel-Data/m-p/18976#M5212
> 1 votes

---
Tags: arduino-uno, sensors, adafruit, imu, bno055
---


# Question
Title: How safely write to SD or Eeprom on Arduino power off
I want to constantly store data to sd. But how I make sure data is not corrupted on moment of power off? I think I could add small capacitor on 5V and check when voltage drops, so I would stop data write. Or is there better solution for safe data write?

# Answer
I think a "small" capacitor here is not going to do the job as you need to keep power stable until the write is completed. You need to determine:

1. How much power am I using?
2. How quickly can I detect a power outage?
3. How much time do I need to keep power on the Arduino to complete the write operation(s) I want to complete.

Then you will be in a position to calculate how much capacity you need and whether a capacitor or battery is more appropriate.
> 1 votes

# Answer
You're probably going to want to look to various forms of NVRAM (Non-volatile RAM). SRAM with an automatic save to EEPROM function on power loss, e.g. 47L16. Or battery backed RAM; if you have a real-time clock in your project you may have some limited storage in it. E.g., the DS1307 has 56 bytes, although you can probably find a more accurate RTC that has storage in it. Or FRAM, though it's as bit expensive, e.g. cy15b064q-sxet

In any case you'd probably want to write your data out in blocks with CRC so that you can make a determination on whether or not a partial write was done when reading back later.
> 0 votes

---
Tags: sd-card, capacitors
---


title: Is this a feasible circuit?

text:
# Question
Title: Is this a feasible circuit?
The last couple months I’ve been working on this project, I’m nearing its end and I’m getting really excited! However, this is still pretty new to me and so I was hoping my electrical diagram/accumulated knowledge could be verified before I go and start spending money on parts. All criticism is welcome as are any additional resources. Thank you in advance!

Logic:

**Arduino setup:**

Arduino pins (aside from the power section) at the bottom are capable of outputting up to 40mA at most and when using multiple pins, no more than 200 mA should ever be drawn at once

Piezo buzzers are the only electrical component that do not need resistors

This was taken directly from How To Mechatronics, attaching a 330 Ohm resistor to the LED strip lowers its electrical noise

The other resistor attached to the LED strip should be 25 ohms, seeing as I don’t have one though I will be using a 27-ohm resistor instead. Where 5 LED’s on the strip should take up 300mA (each GRB uses 20mA and I’m using 5 in total, therefore 20 x 3 x 5 = 300). Using Ohms law R = V/I, therefore R = 7.5/0.3, therefore R = 25.

\**I would like to add that I also looked at Watt’s law and was a big confused as I got a current of 200 mA instead (as the LED’s each use between 0.1 – 0.3 Watts, therefore I = W/V, therefore I = 1.5/7.5, therefore I = 0.2) I went with the 27 ohms instead of the 37.5 ohms watts law gave me instead because How To Mechatronics really seemed to know what was up I chose to power the board via the 7.5V, 1A adapter mostly because I wanted its voltage-in to be regulated and seeing as it won’t be plugged into a computer, I thought USB was a bit sketch and it made more sense to use the power port as opposed to the Vin pin.

**Motor setup:**

The motor was chosen based off of my need for high torque – the door handle I am trying to push requires 5 pounds (raised to 6 pounds for extra breathing room) and the entire handle is 4.5 inches (lowered to 3 inches for breathing room) in length (the measurements were provided by a friend as I wont be home for a little bit, might seem a bit overkill but its just cause I don’t think they are entirely accurate in the first place). Using these measurements and the equation Torque = length x Force I got the required torque had to be greater than 0.3572kg/cm to open my door. Knowing this I took a look at a bunch of Nema stepper motors and chose one capable of producing that torque (based off of its holding torque) that was the lightest and smallest. I wanted something light as I am still unsure how I will be mounting this to my door…

Originally, I was going to use the L298N but seeing as how using the 5V pin off the Arduino is not recommended for powering it and that they generally don’t dissipate heat that well for their motors I decided not to

Lastly, the 12V 4A power supply was chosen because I needed something stronger than 9V and I wanted to save money. Seeing as I would have the 0.5A - 0.7A current option selected (to my knowledge anything more could cause damage unlike with the Arduino, extra current is not necessarily a bad thing in this case) it’s a bit overkill. I’m thinking it shouldn’t cause any thermal limiting though seeing as it is rated to 4A and its not as if my motor will be going that often anyways :)

Links (all links except for the motor which goes to pololu redirect to amazon): **7.5V 1A Power supply:** https://www.amazon.ca/Belker-Adjustable-Universal-Household-Electronics/dp/B07NKZCWT1/ref=cm\_cr\_arp\_d\_product\_top?ie=UTF8 **12V 4A power supply:** https://www.amazon.ca/COOLM-Adapter-100-240V-Doorbell-5-5X2-5MM/dp/B07H2T31JJ/ref=sr\_1\_6?dchild=1&keywords=10V+4A+POWER+SUPPLY&qid=1606959202&s=hi&sr=1-6 **KEYESTUDIO W5500 Ethernet Arduino (Uno):** https://www.amazon.ca/gp/product/B079G4WDGW/ref=ppx\_yo\_dt\_b\_asin\_title\_o03\_s00?ie=UTF8&th=1 **NEMA 14 stepper motor (2.7V, 1 A/Phase):** https://www.pololu.com/product/1209 **TB6600 stepper motor driver:** https://www.amazon.ca/TB6600-Stepper-Driver-Controller-tb6600/dp/B07B9ZQF5D/ref=asc\_df\_B07B9ZQF5D/?tag=googleshopc0c-20&linkCode=df0&hvadid=292963865944&hvpos=&hvnetw=g&hvrand=11283888445696292979&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9001232&hvtargid=pla-524548131497&psc=1 **LED strip (WS2812B):** https://www.amazon.ca/gp/product/B01CDTED80/ref=ppx\_yo\_dt\_b\_asin\_title\_o06\_s00?ie=UTF8&psc=1

# Answer
Let's take a look at the LEDs. Different kinds of LEDs have different forward voltage requirements. Non-bright LEDs tend to require less voltage than bright LEDs, since bright LEDs need more power to work. Typical VLED values are 1.7V for non-high-brightness red, 1.9V for high-brightness high-efficiency low-current red, 2V for orange and yellow, 2.1V for green, and 3.4 to 3.6V for bright white and most blue types.

In order to make sure that this voltage gets dropped across the LED, you should use a voltage greater than the LED's forward voltage. Use at least 3V supply voltage for lower-voltage LEDs and 4.5V for 3.4V types. Also add a resistor in series with the LED to limit excess current from burning out the LED, usually so that the current flowing through the LED is about 10mA. Make sure that the current doesn't exceed the maximum current specified on the LED's datasheet. You have 5 LEDs in series with (assuming keeps the math simple) a Vf of 2 Volts, therefore you need 5\*2 (they add) or 10 volts to get them to light then a little more (2 volts) so you can control the current with a resistor. At this point you have 5 volts trying to push current through a 10V device circuit, nothing will happen. Using 12 volts and Ohm's law a 200 Ohm resistor will give you about 10 mA, a safe current for most LEDS. If you want them light replace the 27 Ohm with a 200 Ohm and connect to the +12V inplace of the 5V pin. Note LEDs do not work well in parallel unless the current is controlled in each LED or LED string. This is based on your schematic showing 5 LEDs powered by a 5V source.
> -1 votes

---
Tags: arduino-uno, stepper-motor, led-strip, buzzer
---


# Question
Title: ESP32 HTTPS server - how to get POST request string
I'm trying to set up an ESP32 (DOIT ESP32 DEVKIT V1 in the Arduino IDE, with Espressif's WiFi libraries) with the following includes so far:

```
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <HTTPSServer.hpp>
#include <SSLCert.hpp>
#include <HTTPRequest.hpp>
#include <HTTPResponse.hpp>

```

Now, if I have a callback routine that's set up with

```
ResourceNode * nodeEchoPost = new ResourceNode("/cmd", "POST", &handleEcho);

```

how can I parse out the POST request string? On the serial console I get

```
[HTTPS:I] Request: POST /cmd

```

which is a debug output from the HTTPSRequest library itself. But I have no clue how to get that '/cmd' string for my own use! I've tried the example code of

```
byte buffer[256];
size_t s = req->readBytes(buffer, 256);

```

getting a buffer that only returns garbage, probably because all the request is in the POST statement and the body is empty.

Since all I need is the request-info

```
'/cmd?command1=foo&command2=bar&etc'

```

to chop up and use, well.. how do I get that out from the library? I've been googling around, and looking in the library header files, without much luck.

Also, is there any advantage to using the WiFiClientSecure library instead, since everything already goes over HTTPS? That's more of a side question, though if it makes it easier to grab the Request string that way, I'm totally fine with accepting that.

# Answer
> 1 votes
That's a GET and not a POST, so variables are accessible with

```
auto params = req->getParams();
std::string command1;
std::string cmd2;
bool hascommand1 = params->getQueryParameter("command1", command1);
bool hascmd2 = params->getQueryParameter("cmd2", cmd2);

```

See example at https://github.com/fhessel/esp32\_https\_server/blob/master/examples/Parameters/Parameters.ino

The `.c_str()` is required to transition from std::string to what println needs, not a problem related to the getRequestString() function itself

I came across this question while looking for ways to read actual POST variables, which is not documented (and the source code does not show sign of it)

# Answer
> 0 votes
I think I found the answer, by looking through examples in the github repo of Hessel's HTTPS library.

In short, this seems to be it:

```
void handleEcho(HTTPRequest * req, HTTPResponse * res) {

Serial.print("in handleEcho. request is:");
Serial.println(req->getRequestString().c_str());

```

Output from serial console:

```
"in handleEcho. request is:/cmd?command1=foo&cmd2=bar"

```

Now I have a plain-text string that I can use plain string commands on to chop up in parts with strtok or similar. I don't mind the extra hassle of finding keywords in the string, I'm happy to just have *gotten* the damn thing.

Since I have all the data I want in that request, I'll just use req-\>readBytes as mentioned in examples to empty the buffer and discard all 'body' data.

And someone's gotta agree with me that adding the .c\_str() to an already existing function just seems extra complicated. :/

---
Tags: esp32
---