# Question
Title: cannot open source file "WProgram.h" in VSCode
So I started typing out this question, but in the process of taking screenshots and looking up sources for the question I figured out the answer :P

That said, this problem has been a snag for me for a while and I've asked multiple people about it with no solution. Because it seemed kind of daunting for me and I haven't seen many well explained reasons I figured I'd finish out the post here to help anyone that is running into this or will run into it in the future.

---

# The snag

I'm using vscode for my editor and I've had this snag for a while but it's finally driving me nuts enough to ask for help.

When in include certain libraries I get error squiggles under the include.

In this case the squiggle is popping up because of the error:

> cannot open source file "WProgram.h" (dependency of "Adafruit\_MPR121.h")C/C++(1696)

At first I though the snag was because my include path needed my arduino libraries directory so I added that for the project, but I still get the snag.

I did a computer wide search for the `WProgram.h` file but was not able to find it.

The thing is, all of my sketches still compile and upload fine so for the most part I'm just able to ignore it ... *but the squiggle!!!!!!*.

Any ideas of how I can resolve this?

# Answer
> 4 votes
I landed here in the same position as you, and after researching the comments mentioning `-DARDUINO=10813` and some more googling I found: https://github.com/microsoft/vscode-arduino/issues/1148

This led me to adding one more line to `defines` in my `c_cpp_properties.json`

and this also removed the squiggly!

{
    "configurations": [
        {

            ...

            "defines": [
                "USBCON",
                "ARDUINO=10813"
            ],

            ...

        }
    ],

}```

# Answer
> 3 votes
# The answer

Like I said in the question, I found the answer after doing some searching while typing up the question itself and I want to explain it for future squiggle-haters :)

## WProgram.h vs Arduino.h

I did a bunch of searching to try to track down what's going on and I eventually found this helpful (and depending on the veracity of the source, kind of sad) bit of history:

> There is history of the arduino project not everyone was aware of or supposed to know. I only this much: this all started with some graduate student(s) that created the wiring platform and IDE, called wiring board and wiring "programming language". This project is still active with active users like the arduino project. Then the arduino folks decide to create the arduino project based on wiring project so they took the wiring IDE (which took from the original Processing IDE), including all the libraries etc. and created the first Arduino board (slightly different than wiring board, cheaper!) called it arduino. Arduino project has not very positively acknowledged the wiring project as the source of their project and wiring folks didn't take it very well.
>
> Now, that WProgram.h, is a definition file created by and for the wiring project and board. That's why it has a W on it. It has been in Arduino IDE since its beginning and was replaced by Arduino.h only recently when Arduino 1.0 was released. Now all Arduino 1.0+ IDE will use Arduino.h and not WProgram.h so if you have that plus some other old stuff, you will have to make changes to work with Arduino 1.0+ IDE.

## The temp fix

With that in mind I dove into the source file for the `Adafruit_MPR121.h` library and found where it includes the `WProgram.h` header file and commented it out.

It's also worth pointing out that the pre-compiler conditional here supports the renaming of the file in newer versions of Arduino.

I labeled this section of the answer as "The temp fix" because it involves modifying a 3rd party dependency which is normally not a great idea. Yeah it fixes it now, but as soon as I need to update this library that edit is going to get blown away and I'd need to manually do it again. In this case the update is pretty minimal so maybe that's no big deal, but if the fix was more involved, like a heavy edit, that would be a real big pain in the butt and could cause other unforeseen consequences (and I played half-life as a kid so I know that's not good).

# The better fix

Normally I would say the better fix for this would be to clone the source repository, make the fix there, and do a pull request so the dependency itself gets updated at the source (if someone approves and merges the PR).

But this is a bit different, the conditional in there is actually fine as it adds backwards compatibility. It's there so that the library can support both pre-1.0 and post-1.0 arduino IDE versions. If we did a PR to cut out the `WProgram.h` reference we'd add in breaking code for anyone on the older versions.

So, the better solution is to appease my local compiler.

We know that the `Arduino.h` header for all intents and purposes is the same as the `WProgram.h`, so a almost-full-proof solution would be to fake out the `WProgram.h` file on my computer to appease the compiler.

An important part to note here is that to make sure I faked it out correctly I went to the arduino repository, scrolled back through the tags, found the last tag before they switched to 1.0+, and found the WProgram.h file. Once there I grabbed the same pre-compiler check and definition for the WProgram header so I could be sure I did the correct `define` for the WProgram name.

This feels like a bit of overkill because it protects me from other headers being included with the same string defined, but if that happened it would be because I *have* the WProgram file anyway, but I figured if I was going to fake it out I'd do it right.

This could backfire if I include a library that *only* includes `WProgram.h` and *not* the `Arduino.h` in that arduino version check conditional, but this would 100% be the case for a correction and pull request for that library.

# Summary

So now I know that the `Arduino.h` file is the reason I'm able to compile everything correctly even with the red squiggle, I have a faked out `WProgram.h` so that my compiler can find something when looking for the file and, *most importantly*, I no longer need to look at those red squiggles under the includes :)

Next step, figure out the same thing for `Sam.h` :P

# Answer
> 3 votes
I recently figured out, it's way too simple. Just tap F1 and look for this then select the configuration for "Arduino".

(Pardon my Grammer)

---
Tags: header
---


title: arduino acclerometer with servo motor

text:
# Question
Title: arduino acclerometer with servo motor
I'm currently working on project to operate three motors while sending accelerometer value to computer via bluetooth module. I want the motor operation and value transmission to work seperatly. But when motors operate, the transmission stops. I used the ArduinoThread library, but since I don't understand all the usage, it still has some kind of delay. Plus, I want two of the motors work first(just once) and the other works after specific time(also just once). But the first setup of two motors and the latter doesn't work. Please check my code and give me some advice. Thank you!

```
#include <Wire.h>
#include <SoftwareSerial.h>
#include <Servo.h>
#include <Thread.h>

const int MPU_addr=0x68;  // MPU-6050 I2C address
int16_t AcX,AcY,AcZ,GyX,GyY,GyZ;

SoftwareSerial BTSerial(3,2);   // TX,RX

Servo servoMini;
Servo servoUp;
Servo servoDown;
int pinMini = 6;
int pinUp = 9;
int pinDown = 10;
int i = 1;
unsigned long tPrev, tNow = 0;

Thread myThread = Thread();

void readAcc(){
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers   // 14bit??

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  //AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  //AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  //GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  //GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  //GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  BTSerial.println(AcX);   // 16bit
  Serial.println(AcX);

  // delay(25);
}

void setup(){
  // I2C
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)

  // serial, bluetooth
  Serial.begin(9600);
  BTSerial.begin(9600);
  Serial.println("CLEARDATA");
  Serial.println("ONLY AcX");

  // servo
  servoMini.attach(pinMini);
  servoUp.attach(pinUp);
  servoDown.attach(pinDown);
  pinMode(pinMini, OUTPUT);
  pinMode(pinUp, OUTPUT);
  pinMode(pinDown, OUTPUT);
  servoMini.write(145);
  servoUp.write(180);
  servoDown.write(0);

  // Thread(MPU-6050)
  myThread.onRun(readAcc);
  myThread.setInterval(20);
}

void loop(){
  while(i == 1){
    tNow = millis();
    myThread.run();

    servoUp.attach(pinUp);
    servoDown.attach(pinDown);
    servoUp.write(60);
    servoDown.write(120);

  if((tNow - tPrev)>= 1000){
    servoMini.attach(pinMini);
    servoMini.write(180);
    i++;
  }
}

  servoMini.detach();
  myThread.run();
}

```

# Answer
> 1 votes
Here's the final form of my project. I've added motor detach function since it still shivers a bit.

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

const int MPU_addr=0x68;  // MPU-6050 I2C address
int16_t AcX,AcY,AcZ,GyX,GyY,GyZ;

SoftwareSerial BTSerial(3, 2);  // TX, RX

Servo servoMini;
Servo servoUp;
Servo servoDown;

const byte pinMini = 6;
const byte pinUp = 9;
const byte pinDown = 10;

// Timings for each event.
const unsigned long ACC_INTERVAL = 50;
const unsigned long INTERVAL = 1000;
const unsigned long INTERVAL_FIN = 2000;
const unsigned long GRIPPER_INTERVAL = 2000;
const unsigned long GRIPPER_INTERVAL_FIN= 3000;
const unsigned long LED_INTERVAL = 250;

// Keep track of timestamps for each event.
unsigned long prev_led_timestamp;
unsigned long prev_acc_timestamp;
unsigned long servo_timestamp;
unsigned long servo_timestamp_fin;
unsigned long gripper_timestamp;
unsigned long gripper_timestamp_fin;

// Flags to indicate completion of "just once" events.
bool servo = false;
bool servo_fin = false;
bool gripper = false;
bool gripper_fin = false;

// State of blinking LED.
bool led_state = false;

void readAcc(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers   // 14bit??

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  //AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  //AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  //GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  //GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  //GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  BTSerial.println(AcX);   // 16bit
  //Serial.println(AcX);
}

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

  // For blink without delay.
  pinMode(LED_BUILTIN, OUTPUT);

  // I2C
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

  // servo
  servoMini.attach(pinMini);
  servoUp.attach(pinUp);
  servoDown.attach(pinDown);

  // Perform first move.
  servoMini.write(145);
  servoUp.write(180);
  servoDown.write(0);

  // Initialise all timestamps with the same value with a single call to millis().
  prev_led_timestamp =
  prev_acc_timestamp =
  servo_timestamp = servo_timestamp_fin =
  gripper_timestamp = gripper_timestamp_fin = millis();
}

void loop(){
  unsigned long current_timestamp = millis();

  // TASK 1: Read acc.
  if (current_timestamp - prev_acc_timestamp >= ACC_INTERVAL){
    // Read acc.
    readAcc();
    prev_acc_timestamp += ACC_INTERVAL;
  }

  // TASK 2: Just once.
  if (!servo && current_timestamp - servo_timestamp >= INTERVAL)  {
    //Serial.print("Running just once... ");
    servoUp.attach(pinUp);
    servoDown.attach(pinDown);
    servoUp.write(60);
    servoDown.write(120);
    // retract speed control
    servo = true;
    //Serial.println("Done.");
  }
  if (!servo_fin && current_timestamp - servo_timestamp_fin >= INTERVAL_FIN){
    servoUp.detach();
    servoDown.detach();
    servo_fin = true;
  }

  // TASK 3: Also just once.
  if (!gripper && current_timestamp - gripper_timestamp >= GRIPPER_INTERVAL)  {
    // Perform third move.
    //Serial.print("Running also just once... ");
    servoMini.write(180);
    gripper = true;
    //Serial.println("Done.");
  }
  if (!gripper_fin && current_timestamp - gripper_timestamp_fin >= GRIPPER_INTERVAL_FIN){
    servoMini.detach();
    gripper_fin = true;
  }

  // TASK 4: Blink without delay.
  if (current_timestamp - prev_led_timestamp >= LED_INTERVAL){
    // Toggle LED state.
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    prev_led_timestamp += LED_INTERVAL;
  }
}

```

# Answer
> 1 votes
I think you want something like Blink Without Delay, but with more tasks.

Here is my interpretation of your description which extends Blink Without Delay by adding three more tasks to:

* read the accelerometer
* perform "just once"
* perform "also just once"

I've added several `Serial.print()` statements to give a running commentary on what's occurring for debug purposes.

```
#include <Wire.h>
#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial BTSerial(3, 2);  // TX, RX

Servo servoMini;
Servo servoUp;
Servo servoDown;

const byte pinMini = 6;
const byte pinUp = 9;
const byte pinDown = 10;

// Timings for each event.
const unsigned long READ_ACCELEROMETER_INTERVAL = 50;
const unsigned long JUST_ONCE_INTERVAL = 1000;
const unsigned long ALSO_JUST_ONCE_INTERVAL = 2000;
const unsigned long LED_BLINK_INTERVAL = 200;

// Keep track of timestamps for each event.
unsigned long previous_blink_timestamp;
unsigned long previous_accelerometer_timestamp ;
unsigned long just_once_timestamp;
unsigned long also_just_once_timestamp;

// Flags to indicate completion of "just once" events.
bool just_once = false;
bool also_just_once = false;

// State of blinking LED.
bool led_state = false;

void setup()
{
    Serial.begin(115200);
    Serial.println("\n\nAccelerometer with Servo Test\n");

    // For blink without delay.
    pinMode(LED_BUILTIN, OUTPUT);

    // servo
    servoMini.attach(pinMini);
    servoUp.attach(pinUp);
    servoDown.attach(pinDown);

    // Perform first move.
    servoMini.write(145);
    servoUp.write(180);
    servoDown.write(0);

    // Initialise all timestamps with the same value with a single call to millis().
    previous_blink_timestamp =
    previous_accelerometer_timestamp =
    just_once_timestamp =
    also_just_once_timestamp = millis();
}

void loop()
{
    unsigned long current_timestamp = millis();

    //
    // TASK 1: Read accelerometer.
    //
    if (current_timestamp - previous_accelerometer_timestamp >= READ_ACCELEROMETER_INTERVAL)
    {
        // Read accelerometer.
        Serial.print("Reading accelerometer... ");
        readAcc();
        previous_accelerometer_timestamp += READ_ACCELEROMETER_INTERVAL;
        Serial.println("Done.");
    }

    //
    // TASK 2: Just once.
    //
    if (!just_once && current_timestamp - just_once_timestamp >= JUST_ONCE_INTERVAL)
    {
        // Perform second move.
        Serial.print("Running just once... ");
        servoUp.write(60);
        servoDown.write(120);
        just_once = true;
        Serial.println("Done.");
    }

    //
    // TASK 3: Also just once.
    //
    if (!also_just_once && current_timestamp - also_just_once_timestamp >= ALSO_JUST_ONCE_INTERVAL)
    {
        // Perform third move.
        Serial.print("Running also just once... ");
        servoMini.write(180);
        also_just_once = true;
        Serial.println("Done.");
    }

    //
    // TASK 4: Blink without delay.
    //
    if (current_timestamp - previous_blink_timestamp >= LED_BLINK_INTERVAL)
    {
        // Toggle LED state.
        led_state = !led_state;
        digitalWrite(LED_BUILTIN, led_state);
        previous_blink_timestamp += LED_BLINK_INTERVAL;
    }
}

```

---
Tags: arduino-uno, bluetooth, servo, accelerometer, threads
---


# Question
Title: I'm getting watchdog timer resets in NodeMCU. How can I permanently disable or stop that?
I'm using NodeMCU for my project. At first it works fine, but after some days it is resetting frequently because of the watchdog timer. I have used the `Esp.wdtfeed()` method also. But it is not working. Can you please tell me what the problem exactly with or any solution? Here is my code:

```
void setup(void) {
  ESP.wdtDisable();
  ESP.wdtEnable(WDTO_8S);
  Serial.begin(9600);
  int n = WiFi.scanNetworks();
  Serial.println("");
  if (n == 0)
    Serial.println("no networks found");
  else {
    for(int i=0;i<n;i++) {
      if(WiFi.SSID(i)==ssid1) {
        WiFi.begin(ssid1,password1);
        ssid=ssid1;
      } else if(WiFi.SSID(i)==ssid2) {
        WiFi.begin(ssid2,password2);
        ssid=ssid2;
      } else if(WiFi.SSID(i)==ssid3) {
        WiFi.begin(ssid3,password3);
        ssid=ssid3;
      }
    }
  }
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.drawStringMaxWidth(15,15, 128,"Display started");
  display.display();
  // Wait for connection
  display.clear();
  int j=0;
  while(j<10) {
    display.drawStringMaxWidth(15,15, 128,"connected to");
    display.drawStringMaxWidth(15,32, 128,ssid);
    display.display();
    display.clear();
    delay(1000);
    j++;
  }
  display.drawStringMaxWidth(15,32, 128,"");
  display.display();
  Serial.print("Connected to ");
  display.clear();
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (mdns.begin("esp8266WebForm", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.print("Connect to http://esp8266WebForm.local or http://");
  Serial.println(WiFi.localIP());
  server.on("/", getvalues);
  pinMode(buzzPin,OUTPUT);
  pinMode(but,INPUT);
}

void loop(void) {
  ESP.wdtFeed();
  if((WiFi.status()== WL_DISCONNECTED)||(WiFi.status()==WL_CONNECTION_LOST)) {
    display.drawStringMaxWidth(15,15, 128,"disconnected");
    display.display();
    int n = WiFi.scanNetworks();
    Serial.println("");
    if (n == 0)
      Serial.println("no networks found");
    else {
      for(int i=0;i<n;i++) {
        if(WiFi.SSID(i)==ssid1) {
          WiFi.begin(ssid1,password1);
          ssid=ssid1;
        } else if(WiFi.SSID(i)==ssid2) {
          WiFi.begin(ssid2,password2);
          ssid=ssid2;
        } else if(WiFi.SSID(i)==ssid3) {
          WiFi.begin(ssid3,password3);
          ssid=ssid3;
        }
      }
      int j=0;
      display.clear();
      while(j<10) {
        display.drawStringMaxWidth(15,15, 128,"connected to");
        display.drawStringMaxWidth(15,32, 128,ssid);
        display.display();
        display.clear();
        delay(1000);
        j++;
      }
      display.clear();
      display.drawStringMaxWidth(15,32, 128,"");
      display.display();
    }
  }
  getvalues();
  delay(20000);
}

```

# Answer
> 2 votes
here my way to find the bug first 1.comment out the watchdog from the code. 2.debug the code flow and find it get struck. Debugging in the sense put "Serial.print()" in between your code where you feel stuck but here don't disable your watchdog.

# Answer
> 1 votes
After long time I have seen this question and thought of answering as I found the issue at that time itself, But not posted here.

After debugging for long time, I got to know that there is a string i am initializing with the data fetched from a site which has been overflown beyond the memory of NodeMCU. due to which it has thrown watchdog exception, So please do memory management properly as NodeMCU cannot do data processing and all.

---
Tags: wifi, nodemcu, watchdog
---


# Question
Title: how can I accurately recieve potentiometer values over the USB port?
I want to read the analog values of my ardunio uno into a separate c++ program. On the Arduino I have a serial port initialized for 9600 baud:

```
int sensorPin = A0;    // select the input pin for the potentiometer

int sensorValue = 0;  // variable to store the value coming from the sensor

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

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
}

```

The output value should be right around 390, given the current settings. My serial port reading code seems to read the port fine, but only displays some of the characters sometimes.... some of the time, it reads the value fine. other times I get one or 2 of the characters, such as 3, or 39.

```
#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>    // POSIX terminal control definitions
#include <iostream>
using namespace std;

int main(){
    const char* device ="/dev/ttyACM0";
/* Open File Descriptor */
//int USB = open( device, O_RDWR| O_NONBLOCK | O_NDELAY );
int USB = open( device, O_RDWR| O_NOCTTY );

/* Error Handling */
if ( USB < 0 ){
cout << "Error " << errno << " opening " << device << ": " << strerror (errno) << endl;
}

/* *** Configure Port *** */
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
   cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
   cout << "Error " << errno << " from tcsetattr" << endl;
}

if ( tcsetattr ( USB, TCSANOW, &tty ) != 0){
cout << "Error " << errno << " from tcsetattr" << endl;
}

/* Allocate memory for read buffer */
char buf [1024];
memset (&buf, '\0', sizeof buf);

/* *** READ *** */
int n = read( USB, &buf , sizeof buf );
cout << "buffer: " << &buf << endl;
/* Error Handling */
if (n < 0)
{
     cout << "Error reading: " << strerror(errno) << endl;
}

/* Print what I read... */
cout << "Read: " << buf << endl;

close(USB);
 return 0;
}

```

How can I read the correct value being sent every time?

# Answer
> 4 votes
There are a few issues at play here. One is that the Arduino resets every time you open the serial connection on the PC side. You can prevent this by putting a 1 µF (or more) capacitor between 5V and RESET. A second issue is that the tty driver may be keeping old data in its buffer, and you get this data when you open the connection. The third issue is that `read()` returns as soon as it is able to read *some* data: it doesn't wait until it has got `sizeof buf` bytes.

To fix those issues, I suggest:

1. Have some form of handshake, where the PC sends a request to the Arduino, and then the Arduino acknowledges and starts to send the data. The PC program would then discard everything preceding the acknowledgement.
2. On the PC, repeatedly `read()` until you have a full line (which ends with CRLF). You may want to use a line-oriented stream if you want the libc to handle this for you: see fdopen(3) setlinebuf(3).

**Edit**: A very simple example of handshake: the PC sends `S` (for “start”), then the Arduino sends `OK`, then it starts sending the data. On the Arduino side:

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

    // Wait for the 'S' (start) command from the computer.
    while (Serial.read() != 'S')
        /* wait */ ;

    // Send acknowledgement.
    Serial.println("OK");
}

```

A longer “start” command would be more robust, but a bit more complex to handle on the Arduino. The PC should wait a bit before sending the command (in case the Arduino is restarting), or maybe send it multiple times until it gets an answer.

# Answer
> 1 votes
A USB connection is actually very complex. And serial communications (or the CDC class of USB) is only 1 of over a dozen protocols used over USB. Most cheap embedded processors save money by leaving out this feature. Most Arduino's use cheap embedded processors. For instance, the classic Arduino Uno needs a second chip (search for New USB in this link) to even talk Serial over the USB port. Fortunately this is what Serial.print() does. It takes care of setting up the Serial protocol over the USB port for you. And will send your data over that connection.

How you pick up that data at the other end of the USB connection is usually beyond the discussion range of this stack exchange site. But if you are on a windows machine it will probably be one of the COM ports. And on Linux it will probably be something like /dev/ttyUSB0 or 1.

---
Tags: serial, programming, c++, communication
---


# Question
Title: how to config the Arduino ADC'S input on A0 instead of use default?
I am try to build this AC-DC meter, the code original used default A3 as input, how can change the input on A0? the link: https://simple-circuit.com/arduino-autoranging-ac-dc-voltmeter-with-trms/

Thanks for help Adam

```

/**************************************************************************
*
* Arduino autoranging AC/DC voltmeter.
* Voltage and frequency are printed on 1602 LCD screen.
* This is a free software with NO WARRANTY - Use it at your own risk!
* https://simple-circuit.com/
*
*************************************************************************/

#include <LiquidCrystal.h>   // include Arduino LCD library
// LCD module connections (RS, E, D4, D5, D6, D7)
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);

// define autoranging channel pins
#define CH0  2
#define CH1  3
#define CH2  4
#define CH3  5

const uint16_t Time_Out = 50000,  // time out in microseconds
              Periods  = 10;     // number of periods of measurement (for AC voltage only)

// variables
byte ch_number;
const uint16_t res_table[4] = {2444, 244, 94, 47},  // voltage divider resistances in tenths kOhms
              total_res = 22444;                   // total resistance in tenths kOhms
uint16_t current_res;
volatile byte per;

void setup(void)
{
 pinMode(CH0, OUTPUT);
 pinMode(CH1, OUTPUT);
 pinMode(CH2, OUTPUT);
 pinMode(CH3, OUTPUT);

 lcd.begin(16, 2);     // set up the LCD's number of columns and rows
 lcd.setCursor(1, 0);
 lcd.print("Voltage:");

 ch_number = 0;
 ch_select(ch_number);

 // ADC and analog comparator configuration
 ADMUX  = 0x03;
 ADCSRA = 0x87;
 ADCSRB = (0 << ACME);  // select AIN1 as comparator negative input
 ACSR   = 0x13;         // turn on analog comparator

}

// analog comparator ISR
ISR (ANALOG_COMP_vect)
{
 byte count = 0;
 for(byte i = 0; i < 50; i++) {
   if ( ACSR & 0x20 )
     count++;
 }

 if(count > 48)
   per++;
}

// main loop
void loop()
{
 bool dc_flag = 0; // DC voltage flag bit
 int32_t sum = 0;  // sum of all readings
 uint16_t n = 0;   // number of readings (samples)

 ACSR = (1 << ACI);   // clear analog comparator interrupt flag
 ACSR = (1 << ACIE);  // enable analog comparator interrupt

 uint32_t current_m = micros();  // save current millis
 byte current_per = per;         // save current period number
 while ( (current_per == per) && (micros() - current_m < Time_Out) ) ;

 if( micros() - current_m >= Time_Out ) {  // if there's time out event ==> voltage signal is DC
   dc_flag = 1;
   for (byte i = 0; i < 200; i++) {
     ADCSRA |= 1 << ADSC;   // start conversion
     while(ADCSRA & 0x40);  // wait for conversion complete
     int16_t an = (int16_t)(ADCL | (uint16_t)ADCH << 8) - 511;
     sum += an;
     n++;         // increment number of readings
     delay(1);
   }
 }

 else {   // here, voltage signal is AC
   current_m = micros();  // save current millis()
   per = 0;
   while ( (per < Periods) && (micros() - current_m < (uint32_t)Time_Out * Periods) ) {
     ADCSRA |= 1 << ADSC;   // start conversion
     while(ADCSRA & 0x40);  // wait for conversion complete
     int32_t an = (int16_t)(ADCL | (uint16_t)ADCH << 8) - 511;
     sum += sq(an);  // sq: square
     n++;            // increment number of readings
   }
 }

 ACSR = (0 << ACIE);  // disable analog comparator interrupt
 uint32_t total_time = micros() - current_m;  // used to claculate frequency

 // voltage calculation
 float v;
 if(dc_flag)   // if voltage signal is DC
   v = (4 * sum)/n;   // calculate Arduino analog channel DC voltage in milli-Volts

 else  // here voltage signal is AC
   v = 4 * sqrt(sum/n);   // calculate Arduino analog channel RMS voltage in milli-Volts

 // claculate actual (input) voltage in milli-Volts (apply voltage divider equation)
 v = v * (float)total_res/current_res;
 v /= 1000;  // get voltage in Volts

 uint16_t v_abs = abs(int16_t(v));
 if( (v_abs >= 10 && ch_number == 0) || (v_abs >= 100 && ch_number == 1) || (v_abs >= 250 && ch_number == 2) ) {
   ch_number++;
   ch_select(ch_number);
   delay(10);
   return;
 }

 if( (v_abs < 220 && ch_number == 3) || (v_abs < 80 && ch_number == 2) || (v_abs < 8 && ch_number == 1) ) {
   ch_number--;
   ch_select(ch_number);
   delay(10);
   return;
 }

 char _buffer[8];
 lcd.setCursor(0, 1);
 if( v < 0)
   lcd.print('-');
 else
   lcd.print(' ');
 if(v_abs < 10)
   sprintf( _buffer, "%01u.%02u", v_abs, abs((int16_t)(v * 100)) % 100 );
 else if( v_abs < 100)
   sprintf( _buffer, "%02u.%01u", v_abs, abs((int16_t)(v * 10)) % 10 );
 else
   sprintf( _buffer, "%03u ", v_abs );

 lcd.print(_buffer);
 if(dc_flag)
   lcd.print("VDC        ");
 else {
   lcd.print("VAC ");
   // calculate signal frequency in Hz
   uint32_t period_time = total_time/Periods;
   float freq = 1000000.0/period_time;
   sprintf( _buffer, "%02u.%02uHz", (uint16_t)freq % 100, (uint16_t)(freq * 100) % 100 );
   lcd.print(_buffer);
 }

 delay(500);    // wait half a second

}

void ch_select(byte n) {
 switch(n) {
   case 0:
     digitalWrite(CH0, HIGH);
     digitalWrite(CH1, LOW);
     digitalWrite(CH2, LOW);
     digitalWrite(CH3, LOW);
     break;
   case 1:
     digitalWrite(CH0, LOW);
     digitalWrite(CH1, HIGH);
     digitalWrite(CH2, LOW);
     digitalWrite(CH3, LOW);
     break;
   case 2:
     digitalWrite(CH0, LOW);
     digitalWrite(CH1, LOW);
     digitalWrite(CH2, HIGH);
     digitalWrite(CH3, LOW);
     break;
   case 3:
     digitalWrite(CH0, LOW);
     digitalWrite(CH1, LOW);
     digitalWrite(CH2, LOW);
     digitalWrite(CH3, HIGH);
 }
 current_res = res_table[n];
}

// end of code.

```

# Answer
The input to the ADC is selected by the four least-significant bits of the “ADC Multiplexer Selection Register”, aka `ADMUX`. It is set to analog input 3 by this line of code:

```
ADMUX  = 0x03;

```

Change this line to `ADMUX = 0;` and the ADC will read pin A0.
> 1 votes

# Answer
Your code is to hard to read, it is just a blob of characters on my screen but you have a pretty picture of the arduino. Change your code to use A0 instead of A3. Change your physical connection from A3 to A0 and you are all set. I miss read the code you posted.

It is a tricky circuit and he did all of the the registers directly, making it extremely hard to follow. I do not know the register set well enough to speak knowledgeable about what he is doing. The Optocouplers short out parts of the input divider network which he selects in his code. This is how he does the ranging. The optocouplers are drawn in reverse with the output on the left and the input on the right. Try this link to Nick Gammon's site: https://www.gammon.com.au/adc Also try this one: https://www.arduino.cc/en/Reference/PortManipulation
> -1 votes

---
Tags: programming, adc, input, analog, arduino-setup
---


title: How to reduce AnalogRead noise?

text:
# Question
Title: How to reduce AnalogRead noise?
Currently trying to read off values from a photodiode through analogread. It's constantly so noisy and I thought it might be something wrong with my low-pass filter, but I decided to just connect a 1.5V battery to an analog pin and had just as much noise (upwards of 10mV oscillations). Is there a way around all of this noise? Because this makes the collected data unusable for my project.

Code to read off analog values:

```
int diodePin = A0;
int sensorValue = 0;
int sensorVoltage = 0;

void setup() {

  Serial.begin(57600);

}

void loop() {

sensorValue = analogRead(diodePin);
sensorVoltage = sensorValue*(5000/1024);
Serial.println(sensorVoltage);
delay(10);

}

```

# Answer
> 3 votes
I always do two things for when "reading" analog data with an Arduino.

1. Measuring the voltage supply of the arduino board through its internal reference and calibrating with another 'good" voltmeter ("4 1/2" digits-20000 points or "3 3/4" digits-6000 points). ( Usefull link https://www.instructables.com/Secret-Arduino-Voltmeter/ )
2. Sampling more analog datas to calculate a "mean" ... This can remove some "noise" and add "some bits". 16 samples would add "4" bits at your "readings". Of course, the global sample rate will be lower.

**Don't forget, ground star of wires !!!**

---
Tags: analogread
---


# Question
Title: How to fix serial communication problem between Arduino UNO and sim900A
I've connected the arduino UNO to the sim900a. But after checking the serial communication between the two I keep getting these output.

Here is the connections and code that I used

```
#include <SoftwareSerial.h>
SoftwareSerial SIM900A(2, 3);
// Connect the SIM900A TX to Arduino pin 2 RX.
// Connect the SIM900A RX to Arduino pin 3 TX.
char c = ' ';
void setup()
{
 // start th serial communication with the host computer
 Serial.begin(9600);
 while (!Serial);
 Serial.println("Arduino with SIM900A is ready");
 // start communication with the SIM900A in 9600
 SIM900A.begin(9600);
 Serial.println("SIM900A started at 9600");
 delay(1000);
 Serial.println("Setup Complete! SIM900A is Ready!");
 }
 void loop()
 {
  // Keep reading from SIM900 and send to Arduino Serial Monitor
  if (SIM900A.available())
  { c = SIM900A.read();
    Serial.write(c);
   }
  // Keep reading from Arduino Serial Monitor and send to SIM900A
  if (Serial.available())
  { c = Serial.read();
   SIM900A.write(c);
  }
 }

```

How can I fix this?

# Answer
> 0 votes
You are using the wrong pins on the SIM900A to communicate with your Arduino.

That specific module has a MAX232 interface on it to convert TTL UART to RS232. That is not compatible with the Arduino unless you add another MAX232 to undo the conversion that the one on the board does.

Instead you need to use the other 3-pin header at the other end of the board. It should (according to this site) be wired like this:

Of course you can use other pins than 0/1 on your Arduino, as long as you connect them to the right place on the SIM900A module as shown in that diagram.

Also note what I take to be a pair of jumpers bridging pins on the header you're currently connecting to (ring around them in the diagram).

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


# Question
Title: avrdude: verification error, first mismatch at byte 0x0000 : 0x00 != 0x16 using USBasp
I'm having this strange error, which pops up around 90% of the time. I am trying to program my attiny25 using USBasp and the Arduino IDE / library. Sometimes it works, most times it doesn't.. This error occurs on large sketches as well as new sketches, with just the empty setup() and loop() functions. The error looks quite random to me, because my program just uploaded after trying around 10 times. Compiling goes fine. The error always occurs at byte 0x0000, and always in the format 0x00 != 0x _ \_. I have six wires (correctly) connected from the USBasp to the attiny25. I do not use any resistors, capacitors etc.

Could anyone tell me what could possibly cause this error, and what to do to fix it?

# Answer
The cause is most likely the fact that you *"... do not use any resistors, capacitors etc."*

Connect a 100nF capacitor between Vcc and GND. Connect a 10KΩ resistor between RESET and Vcc.
> 4 votes

# Answer
The problem has to do with the auto-reset feature, so you have to make sure the Reset pin is connected to VCC via a pull-up resistor. Generally, a 10k resistor will be just fine.
> 1 votes

# Answer
I had the same issue even with capacitor between Vcc and GND and resistor between RESET and Vcc. Finally, I use 5V Instead of 3.3V to power up my ATTINY and the problem was solved!
> 1 votes

---
Tags: arduino-ide, uploading, attiny, avrdude
---


title: Read serial with header and end marker

text:
# Question
Title: Read serial with header and end marker
I am trying to use Topway display for HMI lcd with Arduino. This display using RS232C protocol at docs it has a "Communication Packet Structure" like this.

**So my query should start with AA and end with CC 33 C3 3C**. This sample reading code was taking topway youtube channel.

```
Serial.write(0xaa); // packet head
Serial.write(0x3e); // VP_N16 read command
Serial.write(0x00); // VP_N16 address
Serial.write(0x08);
Serial.write(0x00);
Serial.write(0x00);
Serial.write(0xcc); // packet tail
Serial.write(0x33); // packet tail
Serial.write(0xc3); // packet tail
Serial.write(0x3c); // packet tail

```

3E is the command (for reading) code and this is the list of all commands. docs over here

The point is parsing of smart LCD's response at the original. They use this code: (at first comment)

```
     while (!Serial.available()) {}
     if (Serial.read()==0xaa) {                     // packet head
     packet_OK=1;
     while (!Serial.available()) {}
     if (Serial.read()==0x3e) {                   // packet command
      while (!Serial.available()) {}
      temp_h=Serial.read();                      // read back value high byte
      while (!Serial.available()) {}
      temp_l=Serial.read();                      // read back value low byte
      while (!Serial.available()) {}
      if (!(Serial.read()==0xcc)) {packet_OK=0;} // packet tail
      while (!Serial.available()) {}
      if (!(Serial.read()==0x33)) {packet_OK=0;} // packet tail
      while (!Serial.available()) {}
      if (!(Serial.read()==0xc3)) {packet_OK=0;} // packet tail
      while (!Serial.available()) {}
      if (!(Serial.read()==0x3c)) {packet_OK=0;} // packet tail
      }
      else
      {packet_OK=0;}
     }
     else
     {packet_OK=0;}

```

It looks nasty and cumbersome because I must write different method for each LCD display commands. **Is there any way to read all serial response them as a char array with starting marker "0xAA" and read until finishing marker "0xCC 0x33 0xC3 0x3C" and after that parse it?**

You can watch and check this code on youtube

# Answer
> 6 votes
The short answer to your question is “yes, there is a way”. Multiple ways actually. You could write a *blocking* function, which follows more or less the logic of the example you show, blocking while waiting for each new byte. Or you could write a *non blocking* function, which always return *immediately* and, either gives you the complete packet, or tells you that no full packet has been received so far.

The non-blocking way may be a bit more complicated, but it is more useful, because you program can do other stuff, and be responsive, while waiting for a packet. Here is my take at it. It is based on a finite state machine:

```
// Return whether the payload of this command is of string type.
bool command_payload_is_string(uint8_t command);

// Return the expected packet length for the provided command,
// excluding header and tail.
int packet_length(uint8_t command);

// Attempt to read a packet, but do not block.
// Return a pointer to a static buffer holding the packet,
// or nullptr if no complete packet was received this time.
uint8_t *read_packet() {
    const uint8_t expected_header = 0xaa;
    const uint8_t expected_tail[4] = {0xcc, 0x33, 0xc3, 0x3c};

    // Return immediately unless we have a byte to process.
    if (Serial.available() == 0) return nullptr;
    uint8_t data = Serial.read();

    static uint8_t buffer[BUFFER_SIZE];
    static int bytes_received, bytes_expected;
    static enum {
        EXPECTING_HEADER, EXPECTING_COMMAND,
        EXPECTING_STRING, EXPECTING_PAYLOAD, EXPECTING_TAIL
    } state = EXPECTING_HEADER;
    switch (state) {
        case EXPECTING_HEADER:
            if (data = expected_header)
                state = EXPECTING_COMMAND;
            break;
        case EXPECTING_COMMAND:
            buffer[0] = data;  // command byte
            bytes_received = 1;
            if (command_payload_is_string(data)) {
                state = EXPECTING_STRING;
                // bytes_expected is not relevant in this case.
            } else {
                state = EXPECTING_PAYLOAD;
                bytes_expected = packet_length(data);
            }
            break;
        case EXPECTING_STRING:
            if (data == '\0') {  // end of string
                buffer[bytes_received++] = '\0';
                state = EXPECTING_TAIL;
                bytes_expected = 4;
                bytes_received = 0;
            } else if (bytes_received < BUFFER_SIZE - 1) {
                buffer[bytes_received++] = data;
            } else {
                // Do nothing. As the string is too long
                // to fit in the buffer, this byte is discarded.
            }
            break;
        case EXPECTING_PAYLOAD:
            buffer[bytes_received++] = data;
            if (bytes_received >= bytes_expected) {
                state = EXPECTING_TAIL;
                bytes_expected = 4;
                bytes_received = 0;
            }
            break;
        case EXPECTING_TAIL:
            // If we don't get the expected tail,
            // give up and wait for a new header.
            if (data != expected_tail[bytes_received++]) {
                state = EXPECTING_HEADER;
                break;
            }
            // If the tail is all right, return the buffer
            // and get ready for the next packet.
            if (bytes_received >= bytes_expected) {
                state = EXPECTING_HEADER;
                return buffer;
            }
    }
    return nullptr;
}

```

It will be up to you to implement `packet_length()`. See jstola's comment on why it is needed.

You would use `read_packet()` like this:

```
void loop() {
    uint8_t *packet = read_packet();
    if (packet)
        parse_and_handle(packet);

    // the rest of the program, never blocked by read_packet()...
}

```

**Edit**: According to your comment, some commands have a payload which is a string of unknown length, but seemingly NUL-terminated. I edited the code, and added an extra `EXPECTING_STRING` state to handle this special case. It is up to you to implement the boolean function `command_payload_is_string()`.

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


# Question
Title: How to fade LED in a defined time using FastLED
I'm using FastLED library, Arduino Nano and 5 addressable LEDs (WS2812B). I'd like to create the sequence in the image attached. (all in white color for example)

I know how to turn ON each LED every 0.2 sec and I know how to fade. I don't know how to make sure each LED goes from 0% brightness to 100% in 0.4 sec + start fading in the next LED after 0.2 sec.

Here is a fading LED:

```
void loop() {
  uint32_t cur_ms = millis();
    if (cur_ms - fade_ms > 200) {
        fade_ms = cur_ms;
        brightness += 5;
        leds[0] = CHSV(255, 0, brightness);
    }

FastLED.show();
// delay(10);

```

}

Can anyone help me figure it out?

# Answer
One of the SimpleTimer libraries such as this one by Marcello Romani (which I mention because I have used it; there are others). It creates a timers object that has 10 (in this case) software-based timers with a variety of operating modes (run once, run x times, run forever, e.g.).

The basic idea (for a 1-LED example) is that you write a function (known as a "callback" to step up the brightness of an LED by one step. Let's call it `stepUp()`.

You write another callback function to turn off the LED and start a timer that will call `stepUp()` at whatever interval you choose for as many times as it takes to reach 100%. Let's call this one `cycleLED()`.

In your `setup()`, you'll start another timer that will call `cycleLED()` as often as you want that process to run - every 1200 mSec in this case - and for as many times (or forever) as you choose.

In your loop() function, you'll need a call to your timer object's .run() function as often as possible - that is what makes the timers work, and it is the timers that will call your callback functions to make your LEDs behave as you want them to.

So far, we one fading-up LED, and I'd recommend you implement this much at first.

There are two ways to go from here. You can write the above pair of callbacks for each LED, but they will be nearly identical and why write maintain the same code, several times over? Or you can use another feature of the library - a pointer-to-void argument to the callback function - in which you can pass any value, such as an LED's number or address, so that one callback could operate on the specified LED.

If you go with first option, your `setup()` function will need to to start 5 timers, one for each `cycleLED()` function (which would need to have distinct names, of course), and those timers start-times will need to be staggered.

With the second option, you would write a third callback, `allCycles()` that sequences the starts of each `cycleLED()` in turn. In this case, your `setup()` function would only need to start a timer to repeatedly call `allCycles()`.

There's a lot there, if these are new concepts. If so, it will be a lot easier to experiment with the SimpleTimer library doing something trivial at first, like flashing (not fading) one LED, then several LEDs, until this way of coding timed events feels less foreign.
> 1 votes

---
Tags: arduino-nano, c++, led, c, adafruit
---


# Question
Title: How to clear of contents of string in Arduino?
Currently I convert the characters in `char received[20]` to string using `String randomString(received)` and I am able to display it using `Serial.println(randomString)`. After displaying the string, I would like to know the easiest way to clear out its contents.

# Answer
> 2 votes
In C and C++ a null terminated array of characters **is** a string (although not a String). Many routines for reading input terminate the result with a null as does an assignment like"

```
char foo[] = "This is a string.";

```

All you would need to do to "clear" this string is to assign a null to the first character. For example:

```
foo[0] = '\0';

```

# Answer
> 0 votes
First version with conversion from char\[\] to Arduino String class:

```
char received[20];
...
// Some code that assigns received
...
String randomString(received);
Serial.println(randomString);

// Clear string
randomString = "";

```

Second version without the Arduino String class:

```
char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Empty received buffer
received[0] = 0;

```

And third version where the buffer is cleared:

```
char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Clear received buffer
memset(received, 0, sizeof(received));

```

Cheers!

# Answer
> 0 votes
Although an old question, I thought I would chime in. If I took the time to understand the question properly, I believe you wanted to clear the contents of the String and not the char array. This may help those who wanted to empty a string for other reasons.

```
String randomString(received);
Serial.println(randomString);
randomString.clear(); // This will clear the string

```

It should be noted that for outputing, there was no need to convert to string first if that was all that was required, because println will prefer a char array anyway.

Again String has a `.clear()` method for those who reached this page via web search.

Update: It has been pointed out thanks to @VE7JRO in the comments, that the `clear` methods availablity is not universal. The ESP devices with Arduino compatibile core libraries do have it, as may others. But AVR devices such as the UNO do not. Which I have confirmed.

A revised version to suit all cases where the `.clear` method is unavailable.

```
String randomString(received);
Serial.println(randomString);
randomString = ""; // This will clear the string

```

---
Tags: string
---


# Question
Title: I am building a coin operated machine and am using arduino uno its working but i have to press the switch twice for credit to show on seven segment
```
int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
volatile byte  num = 0;
int coinPin = 2;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(coinPin), inc_counter, RISING );
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);
  pinMode(pin4, OUTPUT);
}

void display(int num) {
  digitalWrite(pin1, bitRead(num, 1));
  digitalWrite(pin2, bitRead(num, 2));
  digitalWrite(pin3, bitRead(num, 3));
  digitalWrite(pin4, bitRead(num, 4));
}

void loop() {
  Serial.print(num);
  Serial.print("credit(s) towards balance");
  display(num);
  delay(500);
}

void inc_counter() {
  num++;
}

```

# Answer
> 1 votes
Based on the code supplied, you are only updating the display every half second because of the `delay(500)`. You could press the button a number of times in 500mills.

I feel it may be better to update a flag and check that in your loop to increment your value and trigger the display update.

Based on the info provided, this may help in your endeavours.

```
int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
int coinPin = 2;
int num = 0;
volatile bool coinFlag = false; // When true there is a coin.

void coin_present()
{
    coinFlag = true;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(coinPin), coin_present, RISING);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(pin3, OUTPUT);
    pinMode(pin4, OUTPUT);
}

void display(int num)
{
    digitalWrite(pin1, bitRead(num, 1));
    digitalWrite(pin2, bitRead(num, 2));
    digitalWrite(pin3, bitRead(num, 3));
    digitalWrite(pin4, bitRead(num, 4));
}

void loop()
{
    // If the flag is set increment num and then display value.
    if (coinFlag)
    {
        //We have a coin, reset the flag first.
        coinFlag = false;

        num++;        // Increment value
        display(num); //
        Serial.print(num);
        Serial.println("credit(s) towards balance");
    }

    // No need for a delay as only `coinFlag` being `true` will update the display.
}

```

Hope this helps in someway.

---
Tags: interrupt
---


# Question
Title: Why when I try to connect my ESP8266 to my node sever in my localhost it keep getting disconnect and connect?
I think the issue is within the library because I have try to implement this code according to the tutorial that I found in YouTube Youtube. The discussion of this tutorial is the first they implement the node js server for listening to specific event from socket io, second part they build a simple iOS application using swift to control an RGB light on the ESP8266 and the last part they make ESP8266 to listen to the event that have payload as RGB values. However, in my implementation, I use angular web application to control ON-OFF light on the Arduino but the problem when I try to listen to event that on and off, my ESP8266 don't connect to my server and print all of that message on the serial.

Here is the code for my ESP8266 to connect to my node server.

```

#include <SocketIoClient.h>
#include<ESP8266WiFi.h>
#include<Arduino.h>
#define USER_SERIAL Serial

SocketIoClient socket;
const char* ssid = "bunvath_guest";
const char* pass = "*************";
void setup() {
  USER_SERIAL.begin(115200);
  searchWifi();
  initWiFi();
  socket.on("message", handleMessage);
  socket.on("light_on",handleMessage);
  socket.emit("message","hello from esp");
  socket.begin("192.168.0.102",3000);
}

void loop() {
  socket.loop();
}
void handleMessage(const char* message, size_t length){
  USER_SERIAL.println(message);
}

  void initWiFi(){
      WiFi.mode(WIFI_STA);
      WiFi.hostname("ESP-host");
      WiFi.setPhyMode(WIFI_PHY_MODE_11G);
      WiFi.enableInsecureWEP(true);
      WiFi.begin(ssid,pass);
      while(WiFi.status() != WL_CONNECTED){
        USER_SERIAL.print(".");
        delay(1000);
      }
      USER_SERIAL.print("");
      USER_SERIAL.println("WiFi connected");
      USER_SERIAL.print("IP Address: ");
      USER_SERIAL.println(WiFi.localIP());
      WiFi.setAutoReconnect(true);
      WiFi.persistent(true);

  }
 void searchWifi(){
  int numberOfNetwork = WiFi.scanNetworks();
  USER_SERIAL.println("-----");
  for ( int i = 0; i< numberOfNetwork;i++){
    USER_SERIAL.print("Network name: ");
    USER_SERIAL.println(WiFi.SSID(i));
    USER_SERIAL.print("Signal Strength: ");
    USER_SERIAL.println(WiFi.RSSI(i));
    USER_SERIAL.println("-------------");
  }
}

```

Here is my node server code for receiving all connection from client and print the client id when new client is connecting. Moreover, this node server will listen to all the event that client emit and broadcast to other client.

```

var port = process.env.PORT||3000
const http = require('http')
const app = require('./app')

const cors = require('cors');
let message = ''
const server = http.createServer(app)
const io = require('socket.io')(server,{cors:{
    origin:'http://localhost:4200',
    credentials: true
}}
    )

server.listen(port,()=>{
    console.log("server run on ", port)
})

io.on("connection",(socket)=>{
    console.log(socket.id)
    socket.on('message', data =>{
        // console.log(data)
        socket.broadcast.emit('message',data)
    })
    socket.on('open_light',data=>{
        socket.broadcast.emit('open_light',data)
        console.log(data)
    })

})

```

Here is the message that I got from serial monitor, I feel like my Arduino has already connected to my server but it keep getting reconnect. Moreover, in my sever I did not see any new client connect to server so I am really what going on with this. Plus, I am sure that my node server is working perfectly fine because I have implement angular web application to emit event, and I saw that event printing in server.

```
12:57:13.083 -> Network name: Meas Nakry
12:57:13.083 -> Signal Strength: -85
12:57:13.083 -> -------------
12:57:13.083 -> Network name: bunvath_guest
12:57:13.083 -> Signal Strength: -57
12:57:13.083 -> -------------
12:57:13.083 -> Network name: BLaNKxD
12:57:13.083 -> Signal Strength: -89
12:57:13.121 -> -------------
12:57:13.121 -> Network name: Tuy vanny1
12:57:13.121 -> Signal Strength: -85
12:57:13.121 -> -------------
12:57:13.121 -> ....WiFi connected
12:57:17.165 -> IP Address: 192.168.0.100
12:57:17.165 -> [SIoC] add packet 42["message",hello from esp]
12:57:17.269 -> [SIoC] Disconnected!
12:57:17.269 -> [SIoC] event disconnected not found. 2 events available
12:57:17.787 -> [SIoC] Disconnected!
12:57:17.787 -> [SIoC] event disconnected not found. 2 events available
12:57:18.376 -> [SIoC] Disconnected!
12:57:18.376 -> [SIoC] event disconnected not found. 2 events available
12:57:18.992 -> [SIoC] Disconnected!
12:57:18.992 -> [SIoC] event disconnected not found. 2 events available
12:57:19.633 -> [SIoC] Disconnected!
12:57:19.633 -> [SIoC] event disconnected not found. 2 events available
12:57:20.217 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:20.217 -> [SIoC] packet "42["message",hello from esp]" emitted
12:57:20.251 -> [SIoC] Disconnected!
12:57:20.251 -> [SIoC] event disconnected not found. 2 events available
12:57:20.771 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:20.771 -> [SIoC] Disconnected!
12:57:20.771 -> [SIoC] event disconnected not found. 2 events available
12:57:21.435 -> [SIoC] Disconnected!
12:57:21.435 -> [SIoC] event disconnected not found. 2 events available
12:57:22.044 -> [SIoC] Disconnected!
12:57:22.044 -> [SIoC] event disconnected not found. 2 events available
12:57:22.596 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:22.596 -> [SIoC] Disconnected!
12:57:22.596 -> [SIoC] event disconnected not found. 2 events available
12:57:23.178 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:23.178 -> [SIoC] Disconnected!
12:57:23.178 -> [SIoC] event disconnected not found. 2 events available
12:57:23.798 -> [SIoC] Disconnected!
12:57:23.798 -> [SIoC] event disconnected not found. 2 events available
12:57:24.403 -> [SIoC] Disconnected!
12:57:24.403 -> [SIoC] event disconnected not found. 2 events available
12:57:24.945 -> [SIoC] Disconnected!
12:57:24.945 -> [SIoC] event disconnected not found. 2 events available
12:57:25.533 -> [SIoC] Disconnected!
12:57:25.533 -> [SIoC] event disconnected not found. 2 events available
12:57:26.201 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:26.201 -> [SIoC] Disconnected!
12:57:26.201 -> [SIoC] event disconnected not found. 2 events available
12:57:26.792 -> [SIoC] Disconnected!
12:57:26.792 -> [SIoC] event disconnected not found. 2 events available
12:57:27.380 -> [SIoC] Disconnected!
12:57:27.380 -> [SIoC] event disconnected not found. 2 events available
12:57:27.894 -> [SIoC] Disconnected!
12:57:27.894 -> [SIoC] event disconnected not found. 2 events available
12:57:28.711 -> [SIoC] Disconnected!
12:57:28.711 -> [SIoC] event disconnected not found. 2 events available
12:57:29.426 -> [SIoC] Disconnected!
12:57:29.426 -> [SIoC] event disconnected not found. 2 events available
12:57:30.131 -> [SIoC] Disconnected!
12:57:30.131 -> [SIoC] event disconnected not found. 2 events available
12:57:30.655 -> [SIoC] Disconnected!
12:57:30.655 -> [SIoC] event disconnected not found. 2 events available
12:57:31.254 -> [SIoC] Disconnected!
12:57:31.254 -> [SIoC] event disconnected not found. 2 events available
12:57:31.787 -> [SIoC] Disconnected!
12:57:31.787 -> [SIoC] event disconnected not found. 2 events available
12:57:32.375 -> [SIoC] Disconnected!
12:57:32.375 -> [SIoC] event disconnected not found. 2 events available
12:57:33.171 -> [SIoC] Disconnected!
12:57:33.171 -> [SIoC] event disconnected not found. 2 events available
12:57:33.731 -> [SIoC] Disconnected!
12:57:33.731 -> [SIoC] event disconnected not found. 2 events available
12:57:34.435 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:34.435 -> [SIoC] Disconnected!
12:57:34.435 -> [SIoC] event disconnected not found. 2 events available
12:57:34.978 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:34.978 -> [SIoC] Disconnected!
12:57:34.978 -> [SIoC] event disconnected not found. 2 events available
12:57:35.581 -> [SIoC] Disconnected!
12:57:35.581 -> [SIoC] event disconnected not found. 2 events available
12:57:36.180 -> [SIoC] Disconnected!
12:57:36.180 -> [SIoC] event disconnected not found. 2 events available

```

Hope anyone can find what is the issue in these codes, I am really frustrated about this for 3 days already.

# Answer
I think you need to allow all origins, at least to begin with. At the moment, only connections coming from the machine running node can access the sever.

Removing credentials as a next step, which I can't see being used, may also move your testing along.

```
const io = require('socket.io')(server,{cors:{
    origin:'*:*',
    credentials: true
}}

```
> -1 votes

---
Tags: esp8266, nodemcu, web-server, node.js, web-service
---


title: Arduino Reset via Software (every day)

text:
# Question
Title: Arduino Reset via Software (every day)
Dear Stack Exchanger's,

I want to reset my Arduino and system in every 24h for preventing frozen software and also other connectivity stuffs.

I wrote a program which connects a digital pin to reset pin of Arduino and I want to reset with that way.

For example my code :

```
unsigned long myTime; // Millis() function time value
int timeExpected = 5000; // I want to reset it in every 5 secs for testing.
const int RESET_PIN = 2; // Reset pin's connection

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN,OUTPUT);
}
void loop() {
  digitalWrite(LED_BUILTIN,HIGH);
    myTime = millis();
    Serial.println(myTime); // prints time since program started
     delay(1000);

   if(myTime % timeExpected == 0) {
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
     Serial.println("RESET");
    //digitalWrite(RESET_PIN, LOW);(I just test with LED_BUILTIN Low function)
    }

  }

```

I have tried the watchdog timer but I cannot do it for 24 hours. If you have another solution for reset in 24h please tell me and send me the related article/book/link etc. I will check and implement into my code.

UPDATE: I have done this but it does not reset at very 5s . Code :

```
#include <avr/wdt.h>
unsigned long myTime;
int timeExpected = 5000;

void setup() {
  Serial.begin(9600);
Serial.println("Setup started :");
// make a delay before enable WDT
// this delay help to complete all initial tasks
delay(2000);
wdt_enable(WDTO_2S);
}

void loop() {
    myTime = millis();
    delay(1000);
    Serial.println(myTime); // prints time since program started
   if(myTime == timeExpected) {
     Serial.println("RESET");
    wdt_reset();
    }

```

# Answer
> 2 votes
You can use the watchdog timer, but you have to change the way you measure the elapsed time. Try this code:

```
#include <avr/wdt.h>

unsigned long myTime; // Millis() function time value
unsigned long elapsedTime;
unsigned long timeExpected = 5000; // I want to reset it in every 5 secs for testing.
const int RESET_PIN = 2; // Reset pin's connection

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  myTime = millis();
  Serial.println("INIT");
  wdt_enable(WDTO_2S); //Enable wdt every two seconds

}
void loop() {

  //************RESET HANDLER********************//
  elapsedTime = millis() - myTime;
  if (elapsedTime > timeExpected) {
    Serial.print("RESET");
    while (1); //Intentionally halt the program, so the watchdog performs the reset
  }
  //**********************************************
  //****************REST OF THE PROGRAM***********
  wdt_reset(); //Ensure one call to this function at least one time in two seconds or less
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.println(elapsedTime); // prints time since program started
  delay(1000);
}

```

Please note that if you have multiple delays in your program, you have to ensure the call to wdt\_reset() in order to prevent unwanted resets. Personally I try not to use delays and would recommend avoid delays as much as possible. You may check out this tutorial if you want to see how to avoid delays. If you achieve avoiding delays you can call wdt\_reset() just one time at the begining of the loop.

# Answer
> 1 votes
You can do an almost immediate full reset with watchdog by activating it 'on place'.

```
wdt_enable(WDTO_15MS); // resets the MCU after 15 milliseconds
while (true);

```

You can use millis() for timing the reset as any other timed function.

---
Tags: arduino-uno, timers, millis, reset, watchdog
---


title: SMBus on ATTiny204

text:
# Question
Title: SMBus on ATTiny204
So I want to connect multiple LED Panels with dynamic addressing to a Master Controller. Seems like SMBus should be able to do that, however I don't find any Library for the Arduino framework. Does SMBus require Hardware implementation and if if works in Software is there a library for that and does it even work on the ATTiny?

# Answer
> 1 votes
The AVR chips lack hardware support for bus arbitration when operating as a slave device in I2C, which would be required for it to work as SMBus with ARP.

You would have to write your own bit-banged driver to act as a slave whilst monitoring the SDA pin whenever it transmits to look for bus collisions.

A better solution would be to allocate each device a unique address using an address space of your choosing (to give you enough addresses for uniqueness) at build / programming time. A bus of some design (maybe RS485 would be a good choice for this) can then be scanned looking for, and cataloguing, what addresses are in use.

---
Tags: i2c, attiny
---


title: Find OK or ERROR in serial string

text:
# Question
Title: Find OK or ERROR in serial string
I am trying to figure out how to capture the `OK` or the `ERROR` from a SIM800l.

I have tried

```
mySerial.println("AT");
while (mySerial.available() > 0 ) {
String str = mySerial.readString();
Serial.println(str);
     if (str.equals("OK")) {
        Serial.println("ok");
     } else {
        Serial.println("unknown");
     }
   }

```

But I always getting nothing back?

# Answer
> 0 votes
You can use `.indexOf` to find characters in a String. It returns a `-1` if a match is not found. See https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

```
mySerial.println("AT");
String str;

while (mySerial.available() > 0 )
{
    str = mySerial.readString();
    Serial.println(str);

    if (str.indexOf("OK") != -1)
    {
        Serial.println("ok");
    } else if (str.indexOf("ERROR") != -1)
    {
        Serial.println("error!");
    } else {
        Serial.println("unknown");
    }
}

```

---
Tags: serial, softwareserial, string, serial-data
---


# Question
Title: Attiny85 microcontroller programming without arduino
I have decided to make a simple project so thinked about arduino but that seems very worthy so i decided to use attiny85 ic for my project,but i don't have arduino or avr to program it. Is there any way to program the below ic without arduino or avr?.

# Answer
> 2 votes
> **Is there any way to program \[a bare AVR microcontroller\] without Arduino \[hardware\] or AVR \[hardware programmer\]?**

Programming a *bare* AVR microcontoller like the ATtiny85 *IC* needs either another Arduino board or an AVR programmer device.

---

### Programmer $4-$7

Something like the Pololu AVR Programmer v2.1 can be bought for $7 and used with the free Arduino development software (IDE). I have used this to program an ATtiny85. This is what I would suggest, because a programmer is the most versatile solution.

Even cheaper, a $4 USBASP

---

### Arduino as ISP $4.50

I have used an old Arduino Duemilanove using the Arduino as ISP sketch as a programmer for an ATtiny85 but any Arduino with inbuilt USB and enough GPIO could be used. There are some low cost ATmega328P or ATmega32u4 based Arduino clones that would be suitable. A Nano v3 clone costs $4.50.

---

### Development Board with USB $3

As others have commented, you can buy a "digispark" (just Google and click "shopping") for three or four dollars. This is essentially a breakout board with an ATtiny85, a USB connector and a soft-USB-capable bootloader pre-loaded onto the ATtiny85. You can program it with the Arduino IDE after using the IDE's board-manager to install Digistump's "core" definitions for the Digispark. It doesn't need another Arduino nor an AVR Programmer. I bought three on Amazon for $9 a month ago.

Since it *is* an Arduino-compatible development board, it doesn't really meet your requirement of "without Arduino" - but it might be the closest solution to what you have in mind.

---

Useful resources and inspiration:

Yes, 12 LEDs individually controlled with just four resistors and four pins of an eight-pin ATtiny85 and and no other components!

I have no affiliation with the above site, I just think it is one anyone new to electronics with an ATtiny85 would find interesting.

# Answer
> 1 votes
> **Is there any way to program \[a bare AVR microcontroller\] without Arduino \[IDE software\] or AVR \[software development toolkit\]?**

I believe you can use

* A text editor of your choice to create and edit source code files.
* The GNU compiler GCC-AVR to compile source code into machine-code.
* The avrdude program to install the compiled code onto the microcontroller.

All these can be obtained at zero cost.

---
Tags: arduino-uno, programming, avr, attiny85
---


# Question
Title: Using index of to search for multiple characters
In my Arduino project, a string will be received. I understand using `.indexof` to find the placement of a certain character in the string. My problem is that I need to find the first occurrence of any letter A-Z and haven't found any resources regarding using `or` statements in an `.indexof` aka `string.indexof("a" || "b" ....)`.

Is this something that is not possible using indexof functions and if so is there any function that I can use to solve this! Thanks!

# Answer
Here are two functions that I hope help in your endeavours. You can supply either a String or a char array and you should get the first position of an alpha character. Returns -1 if not present.

See https://www.arduino.cc/reference/en/language/functions/characters/isalpha/

Update:

Thanks to great comments from Edgar & Mat I have updated the functions with best practise and cost improvements.

```
int alphaPos(const char* str)
{
  for (int i = 0; str[i] !=0 ; ++i) {
    if (isAlpha(str[i]))
    {
      return i;
    }
  }

  return -1;
}

int alphaPos(const String& str)
{
  return alphaPos(str.c_str());
}

/*
    Usage:

    String bobble = "&&&88434a";
    int x = alphaPos(bobble);

    if (x != -1)
    {
      ...x has the position in the string
    }
    else
    {
     ...There is no alpha char present.
    }
*/

```
> 2 votes

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


# Question
Title: How to reset ESP32 after a certain duration?
I would like to reset my ESP32 from the software, how do I do it and how to make it do this at regular intervals.

# Answer
Hope this helps.

```

uint32_t resetAfterMillis = 30000; // Reset after 30 seconds.
uint32_t lastResetWas;

void setup() {
   lastResetWas = millis();
}

void loop() {
  uint32_t now = millis();
  if (now >= lastResetWas + resetAfterMillis)
  {
      lastResetWas = now;

      // Whatever you want to do here
      ESP.restart();

  }

}

```
> 3 votes

---
Tags: esp32, millis
---


title: How to convert a String to Hex array

text:
# Question
Title: How to convert a String to Hex array
I am trying use a HMI display. If I want to send a data, for example I want to write "TOPWAY" to 0x00000080 address it should like that:

```
    Serial.write(0xaa); // packet head
    Serial.write(0x42); // VP_N16 string write command
    Serial.write(0x00); // VP_N16 address
    Serial.write(0x00);
    Serial.write(0x00);
    Serial.write(0x80);
    Serial.write(0x54); //T
    Serial.write(0x4f); //O
    Serial.write(0x50); //P
    Serial.write(0x57); //W
    Serial.write(0x41); //A
    Serial.write(0x59); //Y
    Serial.write(0x00); //string end with "\0"
    Serial.write(0xcc); // packet tail
    Serial.write(0x33); // packet tail
    Serial.write(0xc3); // packet tail
    Serial.write(0x3c); // packet tail

```

I want to make a method like SendString(String abc) to send that like above. I need convert string a hex array and call in Serial.write(array\[i\]). Can you hep me?

# Answer
I don't know anything about the particular display, but based on the information provided I hope this is at least shows the foundation of one way you could approach a final solution.

**Update:**

* Incorporated great improvements and a fix from Edgar in the comments.
* String overload.
* Display baud rate suggested by mehmet

```
#define DISPLAY_DEVICE Serial
#define DISPLAY_DEVICE_BAUD 9600

static uint8_t displayPktStart[] = {
    0xaa, // packet headchar
    0x42, // VP_N16 string write command
    0x00, // VP_N16 address
    0x00, // ...Fill
    0x00,
    0x80
  };

static uint8_t displayPktEnd[] = {
    0x00, // End of text
    0xcc, // packet tail
    0x33, // packet tail
    0xc3, // packet tail
    0x3c // packet tail
  };

void writeDisplay(const char* text)
{
  // Write packet headers
  DISPLAY_DEVICE.write(displayPktStart, sizeof displayPktStart);

  // Send text
  DISPLAY_DEVICE.print(text);

  // Write packet tail
  DISPLAY_DEVICE.write(displayPktEnd, sizeof displayPktEnd);
}

void writeDisplay(const String& text)
{
  writeDisplay(text.c_str());
}

void setup()
{
  DISPLAY_DEVICE.begin(DISPLAY_DEVICE_BAUD);
}

void loop()
{
  String msg = "TOPWAY";
  writeDisplay(msg);

  delay(2000);
  writeDisplay("Peanuts taste like chicken");
  delay(500);
  writeDisplay("");
  delay(1000);
  writeDisplay("No. Seriously");
  delay(2000);
}

```
> 5 votes

---
Tags: arduino-uno, serial, string, array, hex
---


title: L298 motor controller board

text:
# Question
Title: L298 motor controller board
Hello I have 2 questions: A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move. B) What is the purpose of the black plastic casing that I have pointed out?

# Answer
> A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.

Those aren't "casings", those are diodes. They are part of the circuit and must be left alone.

> B) What is the purpose of the black plastic casing that I have pointed out?

That is a "jumper" and is used to connect the +5V pin to the internal 5V regulator so the board can be run from just the 12V input power supply. Remove that if, and only if, you want to supply 5V to the board separately from elsewhere.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How to Burn Bootloader with custom Fuses
I have a Atmega328p IC without external Crystal (My target).

When I use a arduino to burn the bootloader to my target, the Arduino as ISP sketch changes the fuses of my target, so it tries to use its external crystal, which is not connected, So it cannot proceed the bootloader burn.

How can I modify the Fuse settings while Burning bootloader with arduino?

# Answer
You need to either adjust the current board fuse settings in `boards.txt` or create a new board variant that matches your settings.

For example the Uno is set up with:

```
uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0xFD
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

```
> 2 votes

# Answer
You can use MiniCore boards support package for Arduino IDE to work with nonstandard AVR boards or breadboard setups. This core has many settings in Tools menu to set different parameters of the board.
> 3 votes

---
Tags: bootloader, fuses, arduino-as-isp
---


title: Arduino Pull-Down Resistors

text:
# Question
Title: Arduino Pull-Down Resistors
I'm building what I thought was a simple Arduino Nano project... right up until it caught fire!

I am a long-time reader of stack exchange and I always find the answers to my questions somewhere on Google, but this seems to be a bit of a head scratcher.

The project is a 4 pin 7 segment LED screen with a timer that counts when Analog pin 0 receives a voltage signal of ~2.5-5v.

Testing the project worked as expected, but when I soldered everything together, I was getting static or white noise from the Analog pin with no voltage being supplied.

I figured I needed a Pull-Down resistor to keep the Analog pin grounded until it received a voltage signal to get rid of any interference.

I connected a 220ohm resistor DIRECTLY from GND and DIRECTLY to Analog Pin 0 and connected the voltage signal wire to Pin 0 as well.

When I actually tested the hardware while connected to the car battery, that's when it shorted out and caused a mini fire.

I was able to read the voltage with my multimeter before the chip burnt out, I was reading ~15.5v total. I'm guessing it's the car battery plus the input voltage on Pin 0.

I only do clean and precise soldering, so there were no unaccounted for connections.

I'm unsure if the issue was too many volts running through the Nano altogether or because I don't really understand how the Pull-Down resistor works and messed that up.

Please help me understand what the issue is and what I can do for a solution.

Thank you.

# Answer
> 1 votes
You violated the voltage input specification of A0 by a lot. What happened is what I would expect. The input protection diode on A0 conducted the battery voltage (- the protection diode drop) into the VCC of the Nano, this overvoltage fried just about all semiconductors and possibly several of the passive components on the board. It sounds like they do what they do when abused and they let the smoke out destroying the Nano and possible several other components. Hopefully this explains what happened. If you had connected the resistor between A0 and the battery it might have survived.

# Answer
> 0 votes
**Input power**

Car power systems operate between 13 and 15 volts when the car is running. Might be too high for the voltage regulator on the Nano. Mine is a AMS1117 which goes up to 15v. Sounds like that's what fried based on your description. Some fail closed circuit, so may have exposed the ATMega to 14v. There's some alternative voltage regulators with the same footprint that will go up to 20v or more input, look for one of those. SOT-223 footprint.

**Button**

The Nano/ATMegs has internal pullups. I'd use those; connect the one side of your button to ground rather than 5v, and the other to the Nano digital input. In your code, activate on LOW rather than HIGH. Then you can skip your external pullup.

**Pullups**

220 ohms is a very strong pulldown for the 5v signal. It will be seeing .11 watts of power dissipation. Use something higher like 10K or 100K. Put a 1K resistor on the 5v signal to limit it's current. You're Arduino is only sensing the voltage, so with a 10K to GND and 1K from 5v signal, the resistor divider will signal 4.5v, plenty for your Nano to detect "HIGH".

---
Tags: arduino-nano
---


# Question
Title: Creating a timer using a Real Time Clock with start and stop times
I have an Arduino Uno with a motor shield, as well as a DS1307 RTC that I am using to control 2 pumps.

Ideally I would like to set a start time (startHour + startMinute) and end time (endHour + endMinute) for each pump.

I have had luck using `if` statements to control my timer like below (adapted from Iain Foulds):

```
byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

byte startHour2=22
byte startMinute2=30
byte endHour2= 2
byte endMinute2= 45

void loop() {
  byte checkStartTime1() {
    DateTime now = RTC.now();
    // Read in what our current datestamp is from RTC
    if (now.hour() == startHour && now.minute() == startMinute) {
      validStart1 = 1;
    } else {
      validStart1 = 0;
    }
    return validStart1;
    // Return the status for powering up
  }
}

```

But my concern is that this only checks for equivalency at the moment, and if I lost power when my start time came up my pump would not come on. So I was hoping to set up an `if` statement that can deal with "\>=" as opposed to just "==".

Which I can use if I only deal with the hour section:

```
if (now.hour() >= startHour && <= endHour)

```

But things get complicated when I try to add in minutes to the control structure. I end up with a series of nested for loops that do not work.

I'm hoping someone can help me write an `if` statement (or `switch case`) that can accommodate hours and minutes. So that any time between 8:15-14:20

```
validStart1=1

```

and anytime other time

```
validStart1=0

```

And please note the addition of the second set for this timer (StartHour2)- which I threw as my second pump will need to deal with the switch over past midnight.

# Answer
> 5 votes
I had a similar problem when i tried to control some heating source here at home.This was how I made my steps to get it working. First I will assume you are using the library time.h and DS1307RTC.h (check here for info: https://www.pjrc.com/teensy/td\_libs\_Time.html).

Assuming that you will need 3 variables of the type tmElements\_t. tm will store your current time( the one you get from DS1307). The other two are auxiliary for defining time you start and time you stop the pump. In similar way, you will need 3 variables of type time\_t for the same reasons. time\_t variables store a the timestamps since 01/01/1970 (Unix epoch) which are easier to work with but tmElements structures are more human friendly.

```
tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

```

Now in your loop you need to get the current time from rtc:

```
time_t now = RTC.get();

```

after, use the breaktime funtion to convert the timestamp value to tmElements struture:

```
breakTime(now, tm);

```

Next step is to copy contents of tm to the other auxiliary structures, use the memcpy function:

```
memcpy(&tm_hour_start, &tm, sizeof(tm));
memcpy(&tm_hour_end, &tm, sizeof(tm));

```

after, change the the auxiliaries vars to meet your correct schedule of start and stop (are seconds important? if so, do similar way):

```
tm_hour_start.Hour = startHour;
tm_hour_start.Minute = startMinute;
tm_hour_start.Second = 0;
tm_hour_end.Hour = endHour;
tm_hour_end.Minute = endMinute;
tm_hour_end.Second = 0;

```

Ok, we have the more human friendly start and end structures, lets get the timestamps from them. To do soo we use the makeTime function that converts tmElements\_t structures to time\_t:

```
t_hour_start = makeTime(tm_hour_start);
t_hour_end = makeTime(tm_hour_end);

```

All you need to do now, is check if your current timestamp (now) is between this newly created timestamps:

```
if ((t_hour_start <= now) && (now <= t_hour_end)){
   //do something is soo...
}else{
   // do something if not...
}

```

**Extra tip:** In case your stop hour goes past midnight, add one more day to the timestamp:

```
if (startHour > endHour) //past midnight correction
   t_hour_end = t_hour_end + SECS_PER_DAY;

```

clean code:

```
#include <time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

// setup function and other needed things...

void loop(){
  //get current timestamp
  time_t now = RTC.get();
  // make current date and time structure
  breakTime(now, tm);
  // make auxiliary structures to be more human editable and friendly
  memcpy(&tm_hour_start, &tm, sizeof(tm));
  memcpy(&tm_hour_end, &tm, sizeof(tm));
  // change auxiliary structures to meet your start and end schedule
  tm_hour_start.Hour = startHour;
  tm_hour_start.Minute = startMinute;
  tm_hour_start.Second = 0;
  tm_hour_end.Hour = endHour;
  tm_hour_end.Minute = endMinute;
  tm_hour_end.Second = 0;
  // reverse process to get timestamps
  t_hour_start = makeTime(tm_hour_start);
  t_hour_end = makeTime(tm_hour_end);
  // check if end time is past midnight and correct if needed
  if (startHour > endHour) //past midnight correction
       t_hour_end = t_hour_end + SECS_PER_DAY;

  //final part
  if ((t_hour_start <= now) && (now <= t_hour_end)){
          //do something is soo...
  }else{
          // do something if not...
  }

}

```

**EDIT:** to correct the thing about midnight checks spotted in comments. New code:

```
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour = 8;
byte startMinute = 15;
byte endHour = 14;
byte endMinute = 20;

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now_, t_hour_start, t_hour_end;
boolean update_tm = 1;

// setup function and other needed things...
void setup(){};

void loop(){
  //get current timestamp
  time_t now_ = RTC.get();
  // make current date and time structure
  breakTime(now_, tm);
  // make auxiliary structures to be more human editable and friendly
  if(update_tm){
    memcpy(&tm_hour_start, &tm, sizeof(tm));
    memcpy(&tm_hour_end, &tm, sizeof(tm));
    // change auxiliary structures to meet your start and end schedule
    tm_hour_start.Hour = startHour;
    tm_hour_start.Minute = startMinute;
    tm_hour_start.Second = 0;
    tm_hour_end.Hour = endHour;
    tm_hour_end.Minute = endMinute;
    tm_hour_end.Second = 0;
    // reverse process to get timestamps
    t_hour_start = makeTime(tm_hour_start);
    t_hour_end = makeTime(tm_hour_end);

    // check if end time is past midnight and correct if needed
    if (startHour > endHour) //past midnight correction
      t_hour_end = t_hour_end + SECS_PER_DAY;
  }
  //final part
  if ((t_hour_start <= now_) && (now_ <= t_hour_end)){
    /* if we got a valid schedule, don't change the tm_hour structures and the
    respective t_hour_start and t_hour_end timestamps. They should be updated
    after exiting the valid schedule */
    if(update_tm)
      update_tm = 0;

    //do something is soo...
  }else{
    if(update_tm == 0)
      update_tm = 1;
    // do something if not...
  }

}

```

# Answer
> 3 votes
What you need to do is convert the time into some standard single number and then compare those numbers.

A popular method is to calculate the number of seconds since an *epoch*. An *epoch* is an arbitrary point in time that you measure time since. Microsoft chose 01/01/0000 for their epoch - Unix chose 01/01/1970.

The Time.h library contains functions for manipulating time values - one of the functions in it can convert a full date and time specification into the number of seconds since 01/01/1970 (Unix epoch). If you want ideas then look at the source code for that.

A similar approach can be used to just work on the hours and minutes within a day. One hour is 60 minutes, so you can create a number that is the number of hours multiplied by 60 plus the number of minutes in the current hour. That will give you the number of minutes since midnight. You can even add in the seconds if you want even more accuracy.

Once you have that single value it's very easy to compare it with a `>=`.

# Answer
> 3 votes
Gerben, thanks for your code. I took it and added seconds to the check, and tidied up a few typos. This isn't as sophisticated as other methods, but might be good for beginners to follow logic. hope it helps

```
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

int openHH = 9;
int openMM = 10;
int openSS = 0;
int closeHH = 9;
int closeMM = 40;
int closeSS = 0;

bool isOpenTime()
{
  time_t t = now(); // Read in what our current datestamp is from RTC
//  DateTime now = RTC.now();  // if using timeRTC lib, i think

  int nowHH = hour(t); int nowMM = minute(t); int nowSS = second(t);  // put into local variables for easier read

  if ((
        (nowHH>openHH)                        // check hours first
        || ((nowHH==openHH) && (nowMM>openMM))             // check minutes if in same hour
        || ((nowHH==openHH) && (nowMM==openMM) && (nowSS>=openSS))    // check seconds if in same hour & minute
      )
      &&                                  // both conditions must be valid
      (
        (nowHH<closeHH)                       // check hours first
        || ((nowHH==closeHH) && (nowMM<closeMM)))             // check minutes if in same hour
        || ((nowHH==closeHH) && (nowMM==closeMM) && (nowSS<=closeSS)) // check seconds if in same hour & minute
      )
  { return true; } else { return false; }
}

  // usage
  if (isOpenTime) {
    // ... do something, eg open door
  } else {
    // ... do something, eg close door
  }

```

# Answer
> 1 votes
```
byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

byte startHour2=22
byte startMinute2=30
byte endHour2= 2
byte endMinute2= 45

void loop()
{
  DateTime now = RTC.now();  // Read in what our current datestamp is from RTC

  if (
    ( (now.hour()==startHour && now.minute()>= startMinute) || (now.hour()>startHour)
    && ( (now.hour()==endHour && now.minute()< endMinute) || (now.hour()<endHour) ) {
    validStart1 = 1;

  } else {
    validStart1 = 0;  //
  }

return validStart1; // Return the status for powering up
 }
}

```

# Answer
> 0 votes
Use the time in number of seconds total.

```
ontime=((sethour*60)+(setmin*60)+setsec);
offtime=((ofsethour*60)+(ofsetmin*60)+ofsetsec);
currenttime=((t.hour*60)+(t.min*60)+(t.sec);
if ((currenttime>ontime)&&(currenttime<offtime));
  {
  pumpon();
  }
else
  {
  pumpoff();
  }
delay(1000);

```

# Answer
> 0 votes
A simple and effecient way is to use relative days and make use of the fact that the days, hours, minutes, and seconds are byte-sized data types that can fit into a single 32-bit data type.

| byte 3 | byte 2 | byte 1 | byte 0 |
| --- | --- | --- | --- |
| Day | Hour | Minute | Second |

This can be achieved with the following function:

```
constexpr uint32_t MakeTimestamp(const byte day, const byte hour, const byte minute, const byte second)
{
  // Pack the 4 individual bytes into a single 4-byte data type in order of precedence.
  return uint32_t(day) << 24 | uint32_t(hour) << 16 | uint32_t(minute) << 8 | uint32_t(second);
}

```

This 32-bit timestamp can be easily compared with other ones to test whether a timestamp is within a timespan:

```
bool WithinTimespan(const uint32_t& timestamp, const uint32_t& begin, const uint32_t& end)
{
  if (end < begin)
  {
    // Crossing midnight.
    return timestamp >= begin || timestamp <= end;
  }
  // Single day.
  return timestamp >= begin && timestamp <= end;
}

```

By using relative days to declare the motor start and stop times, the comparison takes care of the rollover to tomorrow:

```
const byte motor1_start_hour = 8;
const byte motor1_start_minute = 15;
const byte motor1_stop_hour = 14;
const byte motor1_stop_minute = 20;

const byte motor2_start_hour = 22;
const byte motor2_start_minute = 30;
const byte motor2_stop_hour = 2;
const byte motor2_stop_minute = 45;

const uint32_t motor1_start_time = MakeTimestamp(0, motor1_start_hour, motor1_start_minute, 0);
const uint32_t motor1_stop_time = MakeTimestamp(0, motor1_stop_hour, motor1_stop_minute, 0);

const uint32_t motor2_start_time = MakeTimestamp(0, motor2_start_hour, motor2_start_minute, 0);
const uint32_t motor2_stop_time = MakeTimestamp(0, motor2_stop_hour, motor2_stop_minute, 0);

```

Then the `loop()` is simply something like this:

```
void loop()
{
  const DateTime now = rtc.now();
  const uint32_t timestamp = MakeTimestamp(0, now.hour(), now.minute(), now.second());

  bool motor1_on = WithinTimespan(timestamp, motor1_start_time, motor1_stop_time);
  bool motor2_on = WithinTimespan(timestamp, motor2_start_time, motor2_stop_time);

  UpdateMotor1(motor1_on);
  UpdateMotor2(motor2_on);
}

```

---
Tags: arduino-uno, timers, rtc
---


# Question
Title: ESPTOOL not recognizing ESP32-S2 chip for SPIFFs transfer
I have a spiff file that uploads fine using a regular esp32, but when I try on the esp32-32, with a fresh installation, I get:

esptool.py v3.0-dev Serial port COM3 Connecting....

A fatal error occurred: This chip is ESP32-S2 not ESP32. Wrong --chip argument? SPIFFS Upload failed!

Any ideas??

Thanks

# Answer
Is the missing double dash?

```
esptool.py --chip esp32s2 --port COM3 --baud 115200 write_flash -z 0x110000 filename.spiffs.bin

```
> 1 votes

---
Tags: esp32, espressif, spiffs
---