# Question
Title: Error for compiling for board Arduino Uno
I am new to Arduino and just got this error after writing this code:The error message is pasted after the code. I am kindly requesting for assistance so that someone can help me understand why it isn't compiling. I even changed the board to mega at the tools section but still get the same error

```

    #include <Tone.h>

int ledred1 = 2;
int ledgreen1 = 3;
int ledorange1 = 4;
int ledred2 = 5;
int ledgreen2 = 6;
int ledorange2 = 7;
int ledred3 = 8;
int ledgreen3 = 9;
int ledorange3 = 10;

int sound = 250;

int trigPin1 = 11;
int echoPin1 = 12;

int trigPin2 = 13;
int echoPin2 = 14;

int trigPin3 = 15;
int echoPin3 = 16;

#define buzzer1 17
#define buzzer2 18
#define buzzer3 19

Tone tone1;
Tone tone2;
Tone tone3;

long distance1=0;
long distance2=0;
long distance3=0;

long t1=-10000;
long t2=-10000;
long t3=-10000;

void checkDistance(long distance, Tone toneobj, int frequency, long *timer);

long measure(int trigger, int echo);

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);

  tone1.begin(buzzer1);
  tone2.begin(buzzer2);
  tone3.begin(buzzer3);

  pinMode(ledred1, OUTPUT);
  pinMode(ledred2, OUTPUT);
  pinMode(ledgreen1, OUTPUT);
  pinMode(ledgreen2, OUTPUT);
  pinMode(ledred3, OUTPUT);
  pinMode(ledgreen3, OUTPUT);
}
void firstsensor(){ // This function is for first sensor.
  int duration1, distance1;
  digitalWrite (trigPin1, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin1, LOW);
  duration1 = pulseIn (echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

      Serial.print("1st Sensor: ");
      Serial.print(distance1);
      Serial.print("cm    ");

  if (distance1 <=200&& distance1>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,HIGH);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance1 <100&& distance1>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,HIGH);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance1 <50&& distance1>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, HIGH);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance1>200 || distance1<0){
    Serial.println("Out of Range");
    noTone(buzzer1);
  }
  else{
    Serial.print(distance1);
    Serial.println("cm");
    tone(buzzer1,sound);

  }
}
void secondsensor(){ // This function is for second sensor.
    int duration2, distance2;
    digitalWrite (trigPin2, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin2, LOW);
    duration2 = pulseIn (echoPin2, HIGH);
    distance2 = (duration2/2) / 29.1;

      Serial.print("2nd Sensor: ");
      Serial.print(distance2);
      Serial.print("cm    ");

     if (distance2 <=200&& distance2>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, HIGH);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance2 <100&& distance2>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,HIGH);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance2 <50&& distance2>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, HIGH);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance2>200 || distance2<0){
    Serial.println("Out of Range");
    noTone(buzzer2);
  }
  else{
    Serial.print(distance2);
    Serial.println("cm");
    tone(buzzer2,sound);

  }
}
void thirdsensor(){ // This function is for third sensor.
    int duration3, distance3;
    digitalWrite (trigPin3, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin3, LOW);
    duration3 = pulseIn (echoPin3, HIGH);
    distance3 = (duration3/2) / 29.1;

      Serial.print("3rd Sensor: ");
      Serial.print(distance3);
      Serial.print("cm");

     if (distance3 <=200&& distance3>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, HIGH);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance3 <100&& distance3>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,HIGH);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance1 <50&& distance1>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance3>200 || distance3<0){
    Serial.println("Out of Range");
    noTone(buzzer3);
  }
  else{
    Serial.print(distance3);
    Serial.println("cm");
    tone(buzzer3,sound);

  }
}

void loop() {
Serial.println("\n");
firstsensor();
secondsensor();
thirdsensor();
delay(100);
}

```

This is the error message: Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

```
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer0_pin_port'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer0_pin_mask'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer1_pin_port'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer1_pin_mask'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer2_pin_port'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer2_pin_mask'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer0_toggle_count'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer1_toggle_count'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer2_toggle_count'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
> 1 votes
You include the Tone library and you use the `tone()` function from core. They are in conflict.

Use `tone1.tone()` or remove the Tone library and use the `tone()` function.

---
Tags: arduino-uno, arduino-mega, hc-sr04
---


# Question
Title: Issues converting an uint32_t into a char*
I'm using a capacitive touch sensor that as 12 touch points and stores it's state data as a binary number.

I want to take that state, add a bit of data onto the front, and then send it up to a server via websockets. I'm using the Arduino Websockets library for my websocket client.

The library has a `sendBinary` method that allows you to provide a character pointer for the data.

So, I wrote a function that makes a new 32 bit unsigned integer, adds my metadata, then the touch state, and then attempts to take the address of the payload integer and cast it to a character pointer:

```
void sendTouchStateToServer()
{
    Serial.println("sending state to server");

    uint32_t payload = touchControllerMessageType << 12;
    Serial.println(payload);
    payload |= currentTouchState;

    Serial.print("Payload contents: ");
    Serial.println(payload);
    Serial.print("Payload contents cast as character pointer: ");
    Serial.println((char *)&payload);
    Serial.print("Payload size: ");
    Serial.println(sizeof(payload));

    client.sendBinary((char *)&payload, sizeof(payload));
}

```

The issue is that while the integer version of the payload looks fine, when I try to cast it into a character pointer the contents is wrong.

I've also tried creating a `payloadPointer` and directly set the address of the integer as the pointer address, but this also fails.

(I should take this moment to say I'm still pretty green to arduino cpp concepts like this).

What's the right way of doing this? I'm reading up on pointers and trying to understand how to properly do it, but I can't quite figure it out. Could someone explain the correct way of doing it and why? I want this to work, but more than that I want to understand the "why and how" of the proper way.

Thanks! :bows:

# Answer
Your code with `sendBinary` is probably fine, as long as on the other side you *also* use a function that expects to receive exactly 32 bits of binary data (in little-endian format).

Trying to print `(char*)&some_32bit_int` on the other hand will not do anything useful.

The short version is this:

* if you want to send (or receive) binary data, use functions made for binary data - they will usually take a pointer to `char` (or `uint8_t` or something like that) *and a length*.
* if you want to send (or receive) strings, use functions meant for strings. They'll sometimes take `String`, or `std::string` or, unfortunately perhaps, `char *` for C strings.

Never mix both.

Functions that expect a (C) string expect it to actually *be* a C string, i.e. a sequence of chars ending with a null byte (`0x00`). The chars are expected to be mostly ASCII printable characters. If you give them just plain raw data like the memory address of an `int`, you won't get what you want.

Trying to print raw data using a function that expects a C string will result in garbage (or nothing at all, or a lot more garbage than you expected!). (Details in the second part.)

If you want to format your data into a string for sending (using a string/text protocol), then use functions like `sprintf` to do the conversion. (Or use a library that does JSON if your receiver is a web thing - that's pretty handy.)

e.g.

```
char buffer[32];
sprintf(buffer, "{data:%d}", payload);

```

Then send `buffer` via a function that expects a C string.

---

Consider this:

```
uint32_t payload = 0x00323130;

```

The first line initializes a 32 bit int to a specific value, `0x00323130` in hex. Now let's assume that `payload` was stored in memory at address `0x0100`. The memory after that assignment would look like this:

```
Addr.  Val
0x0100 0x30  // our same number 0x00323130 stored in little-endian format
0x0101 0x31
0x0102 0x32
0x0103 0x00

```

When you do:

```
client.sendBinary(&payload, 4);

```

Those four bytes get send over the wire (or the air) exactly as they are. Nothing more, nothing less. If that's what the receiver expects you're golden.

Now if you do:

```
Serial.println((char *) &payload);

```

`Serial.println` is an overloaded function. When you give it a `char *`, it expects a C-string, which is a series of characters terminated by a "null byte", i.e. a byte value of zero. `Serial.println` will then look at the first byte pointed to by the argument. If it's zero, it stops. Otherwise it outputs that char to the serial line, and moves on to the next character. Repeat until a zero byte is found.

In the specially crafted case here with that specific value of `payload`, `Serial.println` would receive address `0x0100` and:

* Look at the value at `0x0100`, get `0x30`, check that it's not zero, and pass it on to the serial line. Serial monitor would receive `0x30` and display that. By lucky coincidence this is the ASCII character code for the digit "0".
* Look at the value at `0x0101`, get `0x31`, check that it's not zero, and pass it on to the serial line. Serial monitor would receive `0x31` and display that. By lucky coincidence this is the ASCII character code for the digit "1".
* Look at the value at `0x0102`, get `0x32`, ... serial monitor displays "2".
* Loot at the value at `0x0103`, get `0x00`. That is a null byte, so it stops there, and sends a newline sequence to the serial.

So in this fabricated scenario the output on the serial monitor would be "123".

Try it with `payload = 0x00616263;` \- serial monitor will display "cba".

In short, `Serial.println` will output exactly the bytes it finds in memory to the serial, until it encounters a zero byte. The serial monitor will try to display those bytes. But, unless you've crafted those values very carefully, all you'll get out of it is garbage - relatively few 8bit values map to printable characters, and even when they do they won't "look" anything like the raw data you had.

If your number happens to start with a zero byte in its binary little-endian representation, `Serial.println` won't print anything - like if you had given it an empty string.

If your number *doesn't* contain a zero byte, it will keep on reading memory past the storage allocated for `payload` until it finds one - possibly outputing much more "junk" than a 32bit variable could ever contain.
> 2 votes

# Answer
The sending with `client.sendBinary((char *)&payload, sizeof(payload));` is OK.

Your attempts to print binary data are wrong.

A `print()` of the 4 bytes of uint32\_t as char array will print 4 characters which ASCII codes are in those 4 bytes and then continue print characters from memory after the variable, until a byte with 0 is read. Some of the characters can be a not printable terminal control characters.

A `Serial.write((char *)&payload, sizeof(payload));` will print 4 characters which ASCII codes are in those 4 bytes.

The simplest way to visualize your binary payload is `Serial.println(payload, BIN);`. This will print the uint32\_t value in binary.
> 2 votes

---
Tags: pointer
---


# Question
Title: How do I make a motor spin every 10 minutes?
I am new to Arduino, please don't be harsh. I want to make a motor spin at every x amount of time (Lets say 10 minutes). Once the program is started, I want it to start the motor (stop after 10 seconds), and every 10 minutes, it continues the process. Is it possible to make it?,

# Answer
> 1 votes
The simplest option is to use `delay()` to implement the waits:

```
void loop() {
    turn_motor_on();
    delay(10000);  // 10 seconds
    turn_motor_off();
    delay(600000);  // 10 minutes
}

```

Since these long numbers may be difficult to read, you can make them more readable by defining some units:

```
const unsigned long second = 1000;
const unsigned long minute = 60000;

```

Then you can for example `delay(10 * minute);`

Beware there is a trap if you try to do arithmetics with integer literals. The following:

```
delay(10 * 60 * 1000);  // BUG!

```

will **not** work on most Arduinos, as the multiplications will be performed on the `int` data type, which can only hold numbers up to 32,767. It is safer to use either explicitly typed constants (`unsigned long` is the appropriate type for delays) or integer literals typed with the suffix `UL` (which stands for “unsigned long”).

Note that the Arduino will do no useful work while delaying. If you want to do any kind of work during the delay, see the “Blink Without Delay” Arduino example.

# Answer
> 0 votes
Yes, of course it's possible. The loop() function might look something like:

```
loop(){
    turn_motor_on();
    wait_seconds(10);
    turn_motor_off();
    wait_minutes(10);
}

```

Now all you have to do is write your turn\_motor\_on() and off functions and also wait\_seconds() and wait\_minutes(). I'll leave the motor controls to you since you have not provided any detail on how the motor is hooked up.

You could use the Arduino delay() function:

```
void wait_seconds(int num_seconds){
    for(int i=0; i<num_seconds; i++){
        delay(1000);
    }
}

void wait_minutes(int num_minutes){
    for(int i=0; i<num_minutes; i++){
        delay_seconds(60);
    }
}

```

Of course there are many other ways to do this but this method is simple and easy to understand and will get you started easily.

---
Tags: motor
---


# Question
Title: Do the I/O pins on Arduino read current or voltage?
So I've recently started Arduino and I just had a question about the digitalRead() function.

Does the IO Pins read Voltage or Current?

The reason I'm asking is because of the attached circuit.

So IO pin 7 is HIGH when the button is not pressed because the resistor is connected to 5V through the resistor. When the button is pressed the button is shorted to ground and is LOW. Why does it read LOW? Surely it would still read 5v because it is still connected to 5V through the resistor?

# Answer
They read voltage. When you close the pushbutton switch the input should have a 0V or digital "0" on it. When you open the pushbutton the resistor should pull the input to 5V or digital "1".

Yes, it is still connected to +5V via the resistor but the nearly 0 Ohm switch pulls the line all the way (or very close) to 0V.
> 5 votes

---
Tags: pins, current, voltage
---


# Question
Title: ESP8266 occasionally stops receiving data
So I have an ESP8266 board that I am using to control some LED lights. I wasn't a fan of the needing to reflash my board everytime I wanted to try a new light pattern, so I decided to send the light data over wifi (UDP), and that works for certain light patterns, but any pattern that has leds that turn on/off starts to stutter and stop after a while. If every light is on, there's no problem with the speed I'm sending data, but if there are some that are on and some off, without fail it will always stop receiving data at a certain point. I've got a couple points of failure and this is my first time messing with an arduino so I'm not sure whether the problem could be on my local program, on the program for the board, the data, my wifi, or something else.

# Answer
dandavis helped me find the answer! Turns out it was a memory leak, due to some poor math on my end. All I had to do was fix that up and it worked fine.
> 1 votes

---
Tags: esp8266
---


# Question
Title: RadioHead library change the state when a new message is received
I would like to control a toy car from the server. I use RadioHead library for communication and it works fine.

The application running on the server side is as follows.

```
#include <RHReliableDatagram.h>
#include <RH_ASK.h>
#include <SPI.h>

#define SERVER_ADDRESS 1
#define ROBOT_ADDRESS 2
#define GO_RIGHT "Go right"
#define GO_LEFT "Go left"
#define GO_FORWARD "Go forward"
#define GO_BACK "Go back"
#define STOP "Stop"
#define SERVER_DELAY 500

unsigned int transmitterPin = 10;
unsigned int receiverPin = 12;

RH_ASK transmitterServer(2000, receiverPin, transmitterPin, 0);

RHReliableDatagram radioCommunication(transmitterServer, SERVER_ADDRESS);

void setup()
{
    Serial.begin(9600);
    if (!radioCommunication.init())
        Serial.println("Radio communication failed");
}

uint8_t buffer[RH_ASK_MAX_MESSAGE_LEN];

void sendData(uint8_t * data, uint8_t length)
{
    Serial.println("I'm sending commands to the robot");

    // Send a command to the robot
    if (radioCommunication.sendtoWait(data, length, ROBOT_ADDRESS))
    {
        // Now wait for a response from robot
        uint8_t from;
        if (radioCommunication.recvfromAckTimeout(buffer, &length, 2000, &from))
        {
            Serial.print("I've got - ");
            Serial.print((char*) buffer);
            Serial.print(" - message from the robot whose addres is : ");
            Serial.print("0x");
            Serial.println(from, HEX);
        }
        else
        {
            Serial.println("No response. Does the robot works?");
        }
    }
    else
        Serial.println("Attempt to resend data failed.");
    delay(SERVER_DELAY);
}

void loop()
{
    sendData(GO_RIGHT, sizeof(GO_RIGHT));
    sendData(GO_LEFT, sizeof(GO_LEFT));
    sendData(GO_FORWARD, sizeof(GO_FORWARD));
    sendData(STOP, sizeof(STOP));
    sendData(GO_BACK, sizeof(GO_BACK));
    sendData(STOP, sizeof(STOP));
}

```

The application running on the robot is as follows.

```
#include <RHReliableDatagram.h>
#include <RH_ASK.h>
#include <SPI.h>

#define SERVER_ADDRESS 1
#define ROBOT_ADDRESS 2
#define GO_RIGHT "Go right"
#define GO_LEFT "Go left"
#define GO_FORWARD "Go forward"
#define GO_BACK "Go back"
#define STOP "Stop"
#define RIGHT_LIGHT 4
#define LEFT_LIGHT 7
#define FORWARD_LIGHT 8

unsigned int receiverPin = 2;
unsigned int transmitterPin = 12;

RH_ASK robotTransmitter(2000, receiverPin, transmitterPin, 0);
RHReliableDatagram radioCommunication(robotTransmitter, ROBOT_ADDRESS);

void setup()
{
    Serial.begin(9600);
    pinMode(RIGHT_LIGHT, OUTPUT);
    pinMode(LEFT_LIGHT, OUTPUT);
    pinMode(FORWARD_LIGHT, OUTPUT);

    if (!radioCommunication.init())
        Serial.println("Radio communication failed");
}

uint8_t buffer[RH_ASK_MAX_MESSAGE_LEN];
uint8_t command[RH_ASK_MAX_MESSAGE_LEN];

void moveRight()
{
    Serial.println("------------");
    Serial.println("I'm going right");
    Serial.println("------------");

    /*
       // Time consuming task

    for (int i = 0; i < 3; ++i)
    {
        digitalWrite(RIGHT_LIGHT, HIGH);
        delay(1000);
        digitalWrite(RIGHT_LIGHT, LOW);
        delay(1000);
    }

    */
}

void moveLeft()
{
    Serial.println("------------");
    Serial.println("I'm going left");
    Serial.println("------------");

    /*
       // Time consuming task

    for (int i = 0; i < 3; ++i)
    {
        digitalWrite(LEFT_LIGHT, HIGH);
        delay(1000);
        digitalWrite(LEFT_LIGHT, LOW);
        delay(1000);
    }

    */
}

void runCommand(char* command)
{
    if (strcmp(command, GO_RIGHT) == 0)
    {
        moveRight();
    }
    else if (strcmp(command, GO_LEFT) == 0)
    {
        moveLeft();
    }
}

void loop()
{
    uint8_t response[] = "OK";
    if (radioCommunication.available())
    {
        uint8_t length = sizeof(buffer);
        uint8_t from;
        if (radioCommunication.recvfromAck(buffer, &length, &from))
        {
            Serial.print("I got - ");
            Serial.print((char*) buffer);
            Serial.print(" - command from the server whose addres is ");
            Serial.print("0x");
            Serial.println(from, HEX);
        }
        // Send the message to the server (with retries) and wait for an ack.
        if (!radioCommunication.sendtoWait(response, sizeof(response), from))
            Serial.println("Repeated attemps to send data to server failed");
        strncpy(command, buffer, sizeof(command));
        runCommand(command);
    }
}

```

As it stands, the serial output of robot is as follows:

Let's increase the `SERVER_DELAY` variable to `2000`. This way the server will send a command every two seconds.

Besides this, let's run a command that will take some time on the robot. To do this we might uncomment time consuming task lines.

So that, when the robot receives `Go right` command, it will try to turn on and off lights three times.

After making these changes let's look at the serial output of robot.

What happens is, after receiving the `Go left` command it tries to blink `LEFT_LIGHT` three times. But meanwhile it misses `Go forward` command. And again after receiving the `Go right` command it tries to blink `RIGHT_LIGHT` three times but misses `Go left` command.

What I would like to do is when robot receives a new command, it should stop whatever it was doing and execute the new command.

How should I do this? Any ideas. Thanks.

# Answer
An easy-enough fix would be to replace your `delay` calls with something that regularly checks if data is available from the server.

Something like:

```
/* returns true if the sleep was interrupted by incoming data */
/* warning: does not wait at all if data is available */
bool interruptible_delay(unsigned long ms)
{
  unsigned long end = millis() + ms;
  while (millis() < end) {
    if (radioCommunication.available()) {
      return true;
    }
    delay(10); /* tune to taste */
  }
  return false;
}

```

This should work as long as the innner delay is much shorter than your communication timeouts.

You will most likely need to handle the case where the sleep was interrupted in your "action" functions if they become more complexe than a led blink. I.e. if your action is a series of complex motor moves, and a message arrives in the middle, you need to design the function so that it is in a safe or neutral state before returning to the main loop.
> 0 votes

---
Tags: arduino-uno, arduino-pro-mini, rf
---


# Question
Title: Ultrasonic Sensor(HC-SR04) recording random distance
I am am trying to make a code which automatically controls relay on basis of ultrasonic sensor measurements. I am using a nodeMCU as a microcontroller rather than an arduino. The relay and the ultrasonic sensor is being powered from a 5V source and nodemcu from a 3.3V Source. I don't think none of the sensors are interfering with each other as all the sensors are kept at a distance. Due to the random values my relay is being latched without any reason. Can someone please help me out with the problem. I don't want these values(above 3000) being shown in the serial monitor.

```
#define TRIGGER 5
#define ECHO    4
#define RELAY   0

void setup() {
  Serial.begin(9600);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  pinMode(RELAY, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  }else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

```

# Answer
These random values could be nothing but noise as your receiver may be sensing other source of ultra sound. In your case, the circuit is especially sensitive as the output powers a relay and any noise in the input side will cause the relay to "chatter". There are many approaches to filtering and smoothing out the signal. One method would be to implement a basic averaging algorithm where you take several readings and then average out the result. Compare this result with the threshold and the output should be smoother.

**EDIT**

Here is a rudimentry example, where I take multiple readings (`nb_measurements` measurements) and then take the average over it:

```
long getDuration() {
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  return pulseIn(ECHO, HIGH);
}

void loop() {
  float duration = 0, distance = 0;
  int nb_measurements = 10;
  for (int i = 0; i < nb_measurements; i++) {
    duration += getDuration();
  }
  duration = duration/nb_measurements;
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  } else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

```

Due to the extra processing, this will be in theory slower than your previous code but in practice, you wouldn't perceive it as long as you keep `nb_measurements` at a reasonable value. There are more complex digital signal filtering algorithms, search around and you can find good documentation and libraries online.
> 1 votes

---
Tags: arduino-uno, esp8266, nodemcu, relay, hc-sr04
---


# Question
Title: How to identify pinout of ATmega 2560 derivative board?
My 3d printer, Creality Ender 4, has an ATmega 2560 chip based card, and I need to identify the number associated with a particular Pin. I read, on the official Arduino website, a simple tutorial in which through a small led connected to two pins of the card, you wrote a code (sketch) that made it turn on, but you had to know the Pin number. I would like to do this on my board, I unplug all cables (power supply, motors, etc.) and connect it to the PC via USB and from Arduino IDE, I execute the code, connecting the LED on the ground and on the signal (see image). To identify the Pin number I thought I would go to exclusion, because I know all the PIN numers of the chip, until the LED lights up. So I ask, is that correct? is there a chance of damaging the card? or is there a better method? Thanks in advance

# Answer
> 1 votes
Disconnect everything but the switch.
Run this:

```
for each pin,
  set the pin to INPUT_PULLUP mode;
  do,
    read and print the pin number and pin state;
  until operator touches a key;
  read and discard the serial input;
end;

```

You do:

* Each time a new pin number prints on the terminal, toggle the switch a few times to confirm whether you are seeing the result of your actions.
* If not, touch the spacebar to try the next pin #
* else, you found it.

---
Tags: atmega2560
---


# Question
Title: How to send Serial data from an Arduino Uno into the Serial of an ESP-01?
So, i need to send sound sensor data from an Arduino Uno to the ESP8266 (ESP-01), so it can output a push notification to my phone whenever there's a loud noise. I have the sensor just powered and hooked up to the Analog 0 pin, and the ESP powered and hooked up to the Arduino Serial pins in reverse (RX to TX, TX to RX)

This is the code i have on the Arduino:

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

void loop() {
  Serial.write(analogRead(A0) + "\r\n");
  delay(100);
}

```

And this is the code i have on the ESP:
(i'm omitting the notification part for clarity, it doesn't even use Serial, so i don't think it should interfere)

```
void setup() {
  Serial.begin(115200);
}
void loop() {
  String val;
  val = Serial.readString();
  if( val.toInt() < 50 ){ sendNotification("Hello!"); delay(10000);}
}

```

I have tested the Sensor output and it seems fine, whenever i snap or clap the readings show a peak (although reversed, it stays on 1023 constantly then peaks to around 0~50), and the ESP can also send notifications normally. But the trigger on the notification never seems to fire, so i guess the ESP is not receiving the data properly.

I'm new-ish to Arduino, so i don't know if i'm doing something wrong here, Thanks in advance!

# Answer
> 2 votes
# Writing Junk From Memory

```
Serial.write(analogRead(A0) + "\r\n");

```

This is advancing a pointer to "\r\n" by whatever number is being returned by analogRead. In other words, you are not sending the measurement but junk from memory after (or sometimes at) `"\r\n"`'s memory location.

`Serial.println(analogRead(A0));` appears to be what you were going for here. `println`'s line termination for the UNO serial connection is `"\r\n"`.

# Logic Levels

When it comes to attaching the serial connections together, there should be some level conversion going on. Because an UNO's pins are 5V logic levels and the ESP-01 expects 3.3v levels.

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


# Question
Title: Switch case options get broken after a function call
I'm sorry for the basic question, but I have a switch case where any code placed after a certain function call simply never gets called, and I've spent half a day looking at it, so thank you so much for your help.

Running on an Arduino UNO.

Here is the loop, and every option in the switch case after the call to moist\_sensor.read() simply never gets in:

```

void loop() {

  while (Serial.available() > 0) {
    char val = (char)Serial.read(); // read data byte by byte and store it
    Serial.println(val);
    switch(val) {

      case 'O':
            digitalWrite(13, LOW);

            break;

      case 'I':
            digitalWrite(13, HIGH);

            break;

      case 'W':
            water(2000);
            break;

      case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

//it never enters any of these cases below

      case 'M':

        //String reading2 = moist_sensor.packaged_reading();
        //Serial.println(reading2); // send the received data back to raspberry pi
        break;

      case 'W':

        water(5000);
        break;

      default:

        delay(5000);

    }
  }

```

I've tried changing the name of the function with fears of special keywords, swapping it with other cases (such as putting case 'W' above, where it works, and vice versa), and I always get the same behaviour. If i comment the line, everything works as expected.

I know the method isn't actually called all the time, but for sanity's sake, moist\_sensor.readd() right now is just:

```
int readd() {
return 0;
}

```

It also works fine if its the last case, but this buggs me, and I want to create other cases with function calls.

Thank you so much!

# Answer
You seemed to have solved it. For the reason, take a look at the compiler errors:

```
sketch_nov22a:31: error: jump to case label [-fpermissive]
       case 'M':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:38: error: jump to case label [-fpermissive]
       case 'W':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:43: error: jump to case label [-fpermissive]
       default:
       ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
exit status 1

```

If you got it to compile your compiler must be configured a bit differently to mine. However you can see that by putting `int reading = ...` in the case block, the compiler tries to execute that first (to initialize `reading`) which causes it to jump case labels.

By moving `int reading` outside the case statement, the compiler no longer has to initialize the variable, and that line merely becomes a function call and assignment (not a variable initialization).

---

You can avoid that by putting the code into its own block, that is, instead of:

```
  case 'E':

        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        break;

```

Use:

```
  case 'E':
        {
        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        }
        break;

```
> 5 votes

# Answer
As soon as I posted this, I looked at the variable declaration inside the case and thought I'd fix this ugly code, and turns out that is what breaks the entire thing, I had no idea...

```
case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

```

should just be

```
case 'E':

            reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

```

with the "int reading;" declaration somewhere else above.
> 4 votes

---
Tags: arduino-uno, c
---


title: How come my transistor doesn't work?

text:
# Question
Title: How come my transistor doesn't work?
I have a TIP 120 to 229 NON 60V 5A transistor

I'm trying to use it to switch an electro magnet. Using the blink example to test it out:

```
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
}

```

pin 13 is connected to the base and I'm trying to powering the magnet with a 12V DC adapter. I'm not sure if the transistor is before or after the magnet, but I'm not sure how that would make a difference.

I'm not great with diagrams but something like this (the power source might be the other way around:

simulate this circuit – Schematic created using CircuitLab

I've tried switching between the collector and the emitter. In one instance the magnet is always active and in one instance it's always passive. What could be wrong?

The cords running of the table in the bottom is just a bit of extra wiring.

# Answer
Is there the only wire from Arduino to the Base of Transistor?

Basically you need something like this:

If you reverse the transistor (E and C), builtin protection diode will be in forward direction, so electro magnet is on.

If you have only one wire to the base, it cannot work as you need current to the base.

If you don't have R1 into the base (about 500R-1K), it'll burn your output eventually. (not if you don't have common ground)

If you have electro magnet between ground and Emitter, you'll have negative current feedback and about 4.2V on L1 tops as there must be some current into the base.
> 5 votes

# Answer
The program is fine.

Looking at the first photograph - The Ground of the Arduino needs to be connected to the ground of your circuit.

I do not understand the two-transistor part of your circuit, so I can't say if this is OK or not. You could also switch the electro-magnet using a relay.
> 2 votes

# Answer
Assuming the - of the power supply is connected to ground your circuit becomes an emitter follower utilizing a Darlington transistor. In that case the emitter will have the same voltage as the base - the VBE which is about 5 Volts. If you reverse it, you will need about 5 volts VBE to turn it on. Note since it is a transistor there is no protection diode. Best suggestion is to use a MOSFET, that will give you a lot more speed then a power transistor. Substitute the MOSFET in the circuit shown above. Source connects to the Emitter point, the Drain connects to the Collector point and the Gate connects to the base. Use something in the 50 Ohm range for the resistor. Your 12V - becomes ground connected to the Arduino ground. Use a logic level avalanche protected MOSFET and the diode is not needed.
> 0 votes

---
Tags: arduino-uno, power, transistor
---


# Question
Title: Arduino zero programming port recognized as EDBG USB port
I am using Arduino Zero with Windows 10. I tried following the procedure listed in Getting started with Arduino to set up my Arduino/environment, however, when I connect the Zero's Programming Port to my laptop's USB 3.0 port, it detects it as **"Atmel Corp. EDBG USB Port"** instead of **"Arduino Zero Prog. Port"** (or something similar) as described under the section "Installing Drivers for the Zero" in the above link. Since it is recognized as an EDBG USB Port, I am unable to burn bootloader or upload sketches using the Programming port as it cannot detect CMSIS-DAP.

when I try to upload a sketch I get the following error:

```
Arduino: 1.8.13 (Windows 10), Board: "Arduino Zero (Programming Port)"
Sketch uses 23496 bytes (8%) of program storage space. Maximum is 262144 bytes.
Global variables use 3536 bytes (10%) of dynamic memory, leaving 29232 bytes for local variables. Maximum is 32768 bytes.
Open On-Chip Debugger 0.10.0+dev-gf0767a31 (2018-06-11-13:36)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
none separate
adapter speed: 400 kHz
cortex_m reset_config sysresetreq
Error: unable to open CMSIS-DAP device 0x3eb:0x2111
Error: No Valid JTAG Interface Configured.
Error: No Valid JTAG Interface Configured.

```

When I try to burn bootloader I get the following error:

```
Open On-Chip Debugger 0.10.0+dev-gf0767a31 (2018-06-11-13:36)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
none separate
adapter speed: 400 kHz
cortex_m reset_config sysresetreq
Error: unable to open CMSIS-DAP device 0x3eb:0x2111

Error while burning bootloader.

```

**How can I fix this?**

So far, I tried

1. re-installing the IDE several times, and also tried uninstalling the device- but it auto installs the driver when I connect again.
2. Starting IDE as an admin did not help, although I think the issue is the EDBG CMSIS-DAP is not installed, and instead, the EDBG USB driver is installed

# Answer
I don't have one of these to test with, but in looking at the driver installation instructions, I would expect it to say "EDBG Virtual COM Port" before a driver is installed and "Atmel Corp. EDBG CMSIS-DAP" after the driver is installed.

The "Arduino Zero Programming Port" is something I expect only appears in the Tools/Port menu in the IDE, despite what it says in the article. You can see this name given in the boards.txt file. And this makes sense to me, given that the EDBG firmware is Atmel's not Arduino's and there appears to be no indication in the driver directory, the content of the INF files, to suggest that they they're providing their own customized driver for the programming port. So I would trust what you see in the images, suggesting it *should* say CMSIS-DAP without mention of "Arduino Zero" at all. So far as I can tell, you're not doing anything incorrect driver-wise, but I'm also not seeing everything.

In any case, it appears you should have the VID (**03eb**) and PID (**2157**) in the device properties that boards.txt instructs the IDE to look for:

```
arduino_zero_edbg.name=Arduino/Genuino Zero (Programming Port)
  1 arduino_zero_edbg.vid.0=0x03eb
  2 arduino_zero_edbg.pid.0=0x2157

```

However, your error mentions PID=**2111**. I looked this up in a USB VID/PID database, and it mentions the an ATMEL Xplained board, which is not a completely unrelated thing, but this VID:PID are not mentioned in the driver information or boards.txt for the Arduino Zero.

I did find this one mention that the Xplained USB PID was used on the M0 Pro which is a different beast from the Zero.

In any case, I would not worry about not seeing something like "Arduino Zero Prog. Port" in device manager itself for the programming port.

Make sure you are using Zero and not M0 Pro. **If you have the M0 pro**, in which case properties in Device Manager may show PID as ***2111**, I'm not sure what to suggest except that maybe you should install Microchip Studio since this seems to be the only way I can find to get the Xplained EDBG drivers. Some work may still be required after that to get it to work in the IDE.

If you have a Zero and not M0 Pro installing Microchip Studio may also install the EDBG driver for it as well, although this really shouldn't be necessary.
> 0 votes

---
Tags: arduino-zero
---


# Question
Title: Unable to upload sketch using Platformio (but Arduino IDE works)
I am using an Arduino Nano (Clone) which I was programming with the Arduino IDE (Version 1.8.5 on Mac OS X 10.10.5).

Using the Arduino IDE I need to re-plug the Nano before uploading, but after doing this everything works as expected and the sketch is being uploaded successfully.

I then tried to use Platformio core (CLI) and get the well-known `not in sync` error:

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

```

As said, this error is well-known, esp. in relation to Arduino clones, and reported several times around the Internet with different solutions.

I just wonder how Arduino IDE is able to upload the code successfully, but Platformio is not since both Arduino IDE and Platformio CLI are just calling `avrdude` to upload the code.

Remark: Uploading the same code to an Arduino Uno works like a charm with both using Arduino IDE and Platformio.

---

*Updates due to further investigation:*

I enabled verbose output for both Arduino IDE and Platformio showing the exact `avrdude` command executed to upload the built hex-file. I adopted the call to `avrdude` from Arduino IDE with the path of the compiled Platformio code. This works as expected:

```
avrdude -v -p atmega328p -c arduino -b 57600 -D -P /dev/cu.usbserial-00000000 -U flash:w:.pioenvs/nano/firmware.hex:i

```

I then had a look at the command used by Platformio which is quite similar but provides an additional `-C` for a config-file:

```
avrdude -v -p atmega328p -C /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf -c arduino -b 57600 -D -P "/dev/cu.usbserial-00000000" -U flash:w:.pioenvs/nano/firmware.hex:i

```

Unfortunately, I am not able to run this command from the Terminal due to an error:

```
avrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf"
avrdude: syntax error at /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf:1080

```

# Answer
> 1 votes
Please use board = nanoatmega328new in your platformio.ini

---
Tags: arduino-ide, sketch, uploading, avrdude, clones
---


# Question
Title: Is there any way to catch the response of SIM800L after sending the at command?
I am using sim 800l with arduino. I am successfully sending AT command from arduino, not in serial monitor but I am unable to catch the response after each successful command execution if its ok or not. I want to do that because, if there is an error in a certain command the next command will not be executed unless its successful. Can you tell me is there any way to do so?

# Answer
for a polling serial read I use this method :

```
bool tSim8_sendCommand(uint8_t sim_cmd[])
{
    uint8_t simOK[2] = {0}, i=20;
    tSoftSerial1_write(sim_cmd);
    tSoftSerial1_write("\r\n");
    while (i--)
    {
        simOK[0] = simOK[1];
        simOK[1] = tSoftSerial1_readChar();
        if(simOK[0] == 'O' || simOK[1] =='K')
        {
            return true;
        }
    }
    return false;
}

```

the variable `i` i the while loop, is used just for retries, so the program doesn't get trapped in an infinite loop. the code is self-explanatory. the incoming characters are "pushed" into an array till the array reads "OK".

for a non-blocking one, it's a bit complicated as you have to define state-machines and concurret loops. here is a method I use for finding out if the last transmission was OK:

```
void tsim_phase_ok_routine(uint8_t inChar)
{
    if(tsim_aux_buff[0] == 'O' && tsim_aux_buff[1] =='K' && tsim_aux_buff[2] =='\r')
    {
        tsim_status_flag |= (1<<PHASE_OK);
        tsim_status_flag &=~(1<<PHASE_CON_ERR);
        return;
    }
    else
    {
        tsim_aux_buff[0] = tsim_aux_buff[1];
        tsim_aux_buff[1] = tsim_aux_buff[2];
        tsim_aux_buff[2] = inChar;
        err_timeout--;
    }
    if(!(tsim_status_flag & (1<<PHASE_OK)) && !err_timeout)
    {
        tsim_status_flag &=~(1<<PHASE_OK);
        tsim_status_flag |= (1<<PHASE_CON_ERR);
    }

}

```

I define "PHASES" to find out which phase is sim800 in. the whole function would be written in RX interrupt service routine and the input character would be fed to it.
> -1 votes

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


# Question
Title: USING HX711 ( WITH LOADCELL) WITH PCF8574 IN NODEMCU
I have used hx711 and loadcell with nodemcu (esp8266) in its D1 and D2 pins ( here I have used Logic level shifter and a 5v supply to power hx711).It worked perfectly fine.

Due to the lack of enough pins to accommodate other sensors in Nodemcu, I'm using PCF8574. I have connected hx711 to pins P0 and P1 of PCF8574.I'm not able to get any output in serial monitor while running like this.

The PCF8574 was connected using resource -

https://www.instructables.com/id/PCF8574-GPIO-Extender-With-Arduino-and-NodeMCU/

The Hx711 was connected using this code.It is compiling but not getting any output in serial monitor.

```
#include "Arduino.h"
#include "PCF8574.h"

// Set i2c HEX address
PCF8574 pcf8574(0x20); // A0,A1,A2 all connected to GND
unsigned long timeElapsed;

include <HX711.h>
HX711 scale;

void setup() {
  Serial.begin(9600);
  Serial.println("initializing");
  pcf8574.pinMode(P0,INPUT);
  pcf8574.pinMode(P1,OUTPUT);
  pcf8574.begin();

  Serial.println("initializing");

  scale.begin(P0,P1); //dt , sck
  scale.get_value(5);  // print the avg of 5 readings from ADC minus tare weight
  scale.set_scale(-450.f); // callibration value
  scale.tare();// reset scale to zero
}

void loop() {

  int weight = scale.get_units(3);
  Serial.println(weight);
  delay(1000)

}

```

Or how about this code without a library? Can I do some changes to it and use pcf8574 ?

```

#define DT D1
#define SCK D2

long sample=0;
float val=0;
long count=0;

unsigned long readCount(void)
{
  unsigned long Count;
  unsigned char i;
  pinMode(DT, OUTPUT);
  digitalWrite(DT,HIGH);
  digitalWrite(SCK,LOW);
  Count=0;
  pinMode(DT, INPUT);
  while(digitalRead(DT));
  for (i=0;i<24;i++)
  {
    digitalWrite(SCK,HIGH);
    Count=Count<<1;
    digitalWrite(SCK,LOW);
    if(digitalRead(DT))
    Count++;
  }
  digitalWrite(SCK,HIGH);
  Count=Count^0x800000;
  digitalWrite(SCK,LOW);
  return(Count);
}

void setup()
{
  Serial.begin(9600);
  pinMode(SCK, OUTPUT);
  Serial.println("Weight");
  Serial.println(" Measurement ");
  delay(1000);
  calibrate();
}

void loop()
{
  count= readCount();
  int w=(((count-sample)/val)-2*((count-sample)/val));
  Serial.print("weight:");
  Serial.print(w);
  Serial.println("g");

 delay(100);
   // val=0;
   // sample=0;
    w=0;
    count=0;
   // calibrate();

}

void calibrate()
{

  //Serial.println("Calibrating...");
  //Serial.println("Please Wait...");
  for(int i=0;i<100;i++)
  {
    yield();
    count=readCount();
    sample+=count;
   // Serial.println(count);
  }
  sample/=100;
  //Serial.print("Avg:");
  //Serial.println(sample);
  count=0;
  while(count<1000)
  {
    yield();
    count=readCount();
    count=sample-count;
    //Serial.println(count);
  }

  //Serial.println("Please Wait....");
  delay(100);
  for(int i=0;i<100;i++)
  {
    yield();
    count=readCount();
    val+=sample-count;
   //Serial.println(sample-count);
  }
  val=val/100.0;
  val=val/100.0;
  //Serial.println(val);
}

```

# Answer
PCF8574 takes around 256us to update pins (at standard 100khz i2c). This too high compared to hx711 sck timing constraint which is 50us max. So, it's not possible to communicate with hx711 using PCF8574. wasted two days in finding out this.
> 2 votes

# Answer
According to library, hx711 sending pulses to mcu and we are scaling with take this pulses. I think you must connect DOUT and SCK pins directly to the MCU or you must counting pulses via I2C after all create a scaling value according the library code and send it to mcu.
> 1 votes

# Answer
I didnt try this method but; when i check the data sheet, i found this code on last page:

```
    sbit ADDO = P1^5;
    sbit ADSK = P0^0;
    unsigned long ReadCount(void){
     unsigned long Count;
     unsigned char i;
     ADDO=1;
     ADSK=0;
     Count=0;
     while(ADDO);
     for (i=0;i<24;i++){
     ADSK=1;
     Count=Count<<1;
     ADSK=0;
     if(ADDO) Count++;
     }
     ADSK=1;
     Count=Count^0x800000;
     ADSK=0;
     return(Count);
}

```

Here is the pulse counting method i think. So if we are using I2C IC, we must get pulse datas over it to our MCU and count them. But before this scaling method; we must calibrate loadcells and tare them absolutely. And i found a link that pointing i2c with hx711. They used sparkfuns IO expander(communicating via I2C) to fix low io problem and connect loadcells to this expander and how read scalings completely. Here is the link: if you can check, maybe find a solution for your problem. Sparkfun's I2c Expander with Hx711
> 1 votes

---
Tags: i2c, nodemcu, pins
---


# Question
Title: Register writing by compound assignment and pointer in Arduino due
I'm confused with register wrting method by compound assignment and/or pointer because I don't know where are some of the values come from.

**Example 1**

```
REG_PMC_PCER1 |= PMC_PCER1_PID36;  // Enable PWM - Peripheral Identifiers 36

```
* This works the same as `REG_PMC_PCER1 = (1<<4)`
* `REG_PMC_PCER1` is not readable, so `|=` operator shouldn't work.
* What is `PMC_PCER1_PID36` ? Is the some sort of bit mask defined in the IDE ?

**Example 2**

```
PMC->PMC_PCER0 |= PMC_PCER0_PID13;   // PWM controller power ON

```
* This works the same as `REG_PMC_PCER0 = (1<<13)`
* This is similar to Example 1 but there is pointer `PMC`. Why it's needed ? If `PMC_PCER0_PID13` is a bit mask then `REG_PMC_PCER0` need not indexing.

**So my questions are:**

1. Why compound assignment works on write-only registers ?
2. Where are those constants (`PMC_PCER1_PID36`,`PMC`,etc.) defined ?

Thanks in advance !

# Answer
> 1 votes
> Why compound assignment works on write-only registers ?

Probably out of force of habit more than anything. People are used to having to set bits in registers where the other bits can be read and they want them to stay the same, in which case `|=` makes sense.

I'd considered that `|=` might be generating a more efficient instruction, but at least with your `REG_PMC_PCER1 |= PMC_PCER1_PID36` example objdump indicates that this is not the case.

> Where are those constants (PMC\_PCER1\_PID36,PMC,etc.) defined ?

Code-wise, they're defined in the ATMEL's (now Microchip's) CMSIS files. These are header files whose existence is somewhat standardized by ARM for these ARM Cortex processors. Much of their content isn't however. E.g., you may see a few things related Cortex M3 that are the same between this ATMEL device in an STM32 counterpart, but GPIO registers may be completely different.

My broadly, they're defined by ATMEL in their datasheets.

---
Tags: arduino-ide, arduino-due
---


# Question
Title: How to make a pairing and mode button on a remote control receiver
I'm working on a remote control project and have come across many different RF receiver/transmitter modules. Many have a pairing/mode button on the receiver that serves to pair the receiver and transmitter and to choose which mode the transmitter is in, momentary, latching, toggle, etc.

How can I replicate this feature using Arduino and those cheap RF transmitter/receiver combos on Ebay? Specific code would be nice, but just a general idea as to how it would be done in theory will work too. I've watched several tutorials that explain the use of the Radiohead library with the cheap RF combos, but none demonstrate how to set up a feature such as this. Thanks.

# Answer
Remote sends a number before the command bits. The receiver checks if this number is the same with the number that corresponds with the position of the switches.

You can do the same in software. Have the first few bits be some number. The receiver can then check if the first few bits of the received "message" matches that number. If it doesn't it will just throw it out.

This is the same method used with IR-remote controls. The signal from your VCR remote will also be received by your TV. But the TV sees that the code doesn't match the one it's expecting. So it will ignore those.
> 1 votes

---
Tags: rf, remote-control
---


# Question
Title: Turning on and off two set of LEDs with two tactile buttons
I have two sets of 4 LEDs.

Set A (Led1 Led2, Led3, Led4) Set B (Led5 Led6, Led7, Led8)

Both sets have its own tactile button:

Tactile A, Tactile B,

Tactile A, turning on the LEDs set A and tactile B turning on the LEDs on set B.

So each time I press the tactile A, Led1 from Set A will turn on. The next press will turn on Led2 and LED1 off, then Led3 on, Led2 off, and Led4 on and led3 off.

Same for Tactile B and set B.

Tactile A will not change the set be and same tactile B.

So I came up with the below code. It works fine for Tactile A, for set A. But I am not able to turn on the set B with Tactile B. Tactile B is keep switching itself one after another the tactile B is no functioning. Each set should work with its own tactile button.

```
//Start -- Power supply on/off code

#include <Bounce2.h>

#define POWER_PIN 13
#define power 12

//End -- Power supply on/off code

//Start -- Switching Leds
// Leds set A
#define button 2
#define led1 8
#define led2 7
#define led3 6
#define led4 5
//Leds set B
#define tactile 3
#define led5 11
#define led6 4
#define led7 9
#define led8 10
int state = 0;      //integer to hold the current state Set A
int old = 0;        //integer to hold the last state Set A
int tactitleState = 0;      //integer to hold the current state Set B
int oldState = 0;        //integer to hold the last state Set B
int buttonPoll = 0; //integer to hold the button state for set A
int tactilePoll = 0; //integer to hold the button state for set B
//End -- Switching power

//Start -- Power supply on/off code

int powerState = LOW;
Bounce b = Bounce(); // Instantiate a Bounce object

//End -- Power supply on/off code

void setup() {
  //Start -- Power supply on/off code

  b.attach(POWER_PIN, INPUT_PULLUP); // Attach the debouncer to a pin with INPUT_PULLUP mode
  b.interval(25); // Use a debounce interval of 25 milliseconds
  pinMode(power, OUTPUT); // Setup the LED
  digitalWrite(power, powerState); // Turn off the LED

  //End -- Power supply on/off code

  //Start -- Switching power

  pinMode(button, INPUT); //button set as input
  pinMode(led1, OUTPUT); //Output set Led1
  pinMode(led2, OUTPUT); //Output set Led2
  pinMode(led3, OUTPUT); //Output set Led3
  pinMode(led4, OUTPUT); //Output set Led4

  digitalWrite (led1, HIGH); //set state Led1
  digitalWrite (led2, HIGH); //set state Led2
  digitalWrite (led3, HIGH); //set state Led3
  digitalWrite (led4, HIGH); //set state Led4

  digitalWrite (power, HIGH); //state of the input power

  //Second relay
  pinMode(tactile, INPUT); //button set as input
  pinMode(led5, OUTPUT); //Output set Led5
  pinMode(led6, OUTPUT); //Output set Led6
  pinMode(led7, OUTPUT); //Output set Led7
  pinMode(led8, OUTPUT); //Output set Led8

  digitalWrite (led5, HIGH); //set state Led5
  digitalWrite (led6, HIGH); //set state Led6
  digitalWrite (led7, HIGH); //set state Led7
  digitalWrite (led8, HIGH); //set state Led8

  //End -- Switching power

}

void loop() {
  //Start -- Power supply on/off code
  b.update(); // Update the Bounce instance
  if ( b.fell() ) {  // Call code if button transitions from HIGH to LOW
    powerState = !powerState; // Toggle LED state
    digitalWrite(power, powerState); // Apply new LED state
  }
  //End -- Power supply on/off code

  //Start -- Switching power Set A.

  buttonPoll = digitalRead(button); //Detect the state of the button
  if (buttonPoll == 1) {              //Check if the button pressed
    delay (50);                       //Delay 50ms
    buttonPoll = digitalRead (button); //Poll button again
    if (buttonPoll == 0) {           //if it is 0 considered one press
      state = old + 1;               //increas state by 1
    }
  }
  else {
    delay (100);                    //Delay 100ms
  }
  switch (state) {     //react tot button press & state
    case 1:
      digitalWrite (led1, LOW); //led1 is on
      digitalWrite (led2, HIGH); //led2 is off
      digitalWrite (led3, HIGH); //led3 is off
      digitalWrite (led4, HIGH); //led4 is off
      old = state;
      break;
    case 2:
      digitalWrite (led1, HIGH); //led1 is off
      digitalWrite (led2, LOW); //led2 is on
      digitalWrite (led3, HIGH); //led3 is off
      digitalWrite (led4, HIGH); //led4 is off
      old = state;
      break;
    case 3:
      digitalWrite (led1, HIGH); //led1 is off
      digitalWrite (led2, HIGH); //led2 is off
      digitalWrite (led3, LOW); //led3 is on
      digitalWrite (led4, HIGH); //led4 is off
      old = state;
      break;
    case 4:
      digitalWrite (led1, HIGH); //led1 is of
      digitalWrite (led2, HIGH); //led2 is off
      digitalWrite (led3, HIGH); //led3 is off
      digitalWrite (led4, LOW); //led4 is on
      old = state;
      break;
    default:                   //if the there is no state, then all leds are off
      digitalWrite (led1, HIGH); //led1 is of
      digitalWrite (led2, HIGH); //led2 is off
      digitalWrite (led3, HIGH); //led3 is off
      digitalWrite (led4, HIGH); //led4 is off
      old = 0;   // All states are reset to 0 off
      break;
  }
  //End -- Switching  led set A
  //Start -- Switching led set B

  tactilePoll = digitalRead(tactile); //Detect the state of the button
  if (tactilePoll == 1) {              //Check if the button pressed
    delay (50);                       //Delay 50ms
    tactilePoll = digitalRead (tactile); //Poll button again
    if (tactilePoll == 0) {           //if it is 0 considered one press
      tactitleState = oldState + 1;               //increas state by 1
    }
  }
  else {
    delay (100);                    //Delay 100ms
  }
  switch (tactitleState) {     //react tot button press & state
      case 1:
      digitalWrite (led5, LOW); //led5 is on
      digitalWrite (led6, HIGH); //led6 is off
      digitalWrite (led7, HIGH); //led7 is off
      digitalWrite (led8, HIGH); //led8 is off
      oldState = tactitleState;
      break;
    case 2:
      digitalWrite (led5, HIGH); //led5 is off
      digitalWrite (led6, LOW); //led6 is on
      digitalWrite (led7, HIGH); //led7 is off
      digitalWrite (led8, HIGH); //led8 is off
      oldState = tactitleState;
      break;
    case 3:
      digitalWrite (led5, HIGH); //led5 is off
      digitalWrite (led6, HIGH); //led6 is off
      digitalWrite (led7, LOW); //led7 is on
      digitalWrite (led8, HIGH); //led8 is off
      oldState = tactitleState;
      break;
    case 4:
      digitalWrite (led5, HIGH); //led5 is off
      digitalWrite (led6, HIGH); //led6 is off
      digitalWrite (led7, HIGH); //led7 is off
      digitalWrite (led8, LOW); //led8 is on
      oldState = tactitleState;
      break;
    default:                   //if the there is no state, then all leds are off
      digitalWrite (led5, HIGH); //led5 is off
      digitalWrite (led6, HIGH); //led6 is off
      digitalWrite (led7, HIGH); //led7 is off
      digitalWrite (led8, HIGH); //led8 is off
      oldState = 0;   // All states are reset to 0 off
      break;
  }
  //End -- Switching Leds set B
}

```

# Answer
> 1 votes
Your code is rather hard to follow.

Your code to read a button press doesn't make much sense:

```
  buttonPoll = digitalRead(button); //Detect the state of the button
  if (buttonPoll == 1) {              //Check if the button pressed
    delay (50);                       //Delay 50ms
    buttonPoll = digitalRead (button); //Poll button again
    if (buttonPoll == 0) {           //if it is 0 considered one press
      state = old + 1;               //increas state by 1
    }
  }
  else {
    delay (100);                    //Delay 100ms
  }

```

That code will, I *think*, only detect a button press if you press the button for exactly 50 mS. Given that you already use the Bounce library, why don't you create Bounce instances for your LED controller buttons and use those to read those buttons as well?

Next issue: you are setting your `button` and `tactile` pins to `INPUT` rather than `INPUT_PULLUP`. Do you have pulldown resistors on those? (when your input is set to `INPUT` mode you need pulldown resistors, and need to connect the switches to +5V. If you use INPUT\_PULLUP mode you don't need any resistors, but you connect your switches to ground. They then read HIGH until you press a switch, at which point the switch connects the pin to ground and pulls it LOW.)

Next issue: You are treating a value of `1` as pressed and `0` as not pressed. You should use the constants `HIGH` and `LOW` instead. (And note that if you use `INPUT_PULLUP` mode for your pins, you should wire your buttons to VCC, and treat HIGH as not pressed and LOW as button pressed.)

I would suggest renaming your variables and using arrays of LED pin numbers:

```
int set1Button 2;
int set1LEDs[] = {8, 7, 6, 5};
int set1State = 0; //No LEDs lit

int set2Button 3;
int set2LEDs[] = {11, 4, 9, 10};
int set2State = 0; //No LEDs lit

```

Pressing `setButton1` should advance `set1State`, and pushing `set2Button` should advance `set2State`.

For value 0, set all LEDs to off. any other value, set the LED at index `setXState - 1` on and all others off.

This code would work for the first set of LEDs:

```
for (int index = 1; index <= 4; index++) {
     int value = set1State == index ? HIGH : LOW;
     digitalWrite (set1LEDs[index-1], value);
}

```

---
Tags: arduino-uno, arduino-nano, led, code-review
---


# Question
Title: Uno doesn’t get enough power from 5v barrel connector. Why?
I’m using a 5v 20a power supply run through a barrel connector into an Arduino Uno to control an LED strip. When only the barrel is connected, the green light on the Uno comes on but the yellow light lights dimly for a few milliseconds then goes dark. The light strip doesn’t light at all. When a USB is also connected, the board lights up fully (green and yellow LED) and the LED strip runs through its routine.

I’m making this as Christmas lights on a tree outside so I want it to run on the stand alone power supply. Why doesn’t the barrel work on 5v?

# Answer
## Voltage Drop

Well, if you put 5V into your barrel jack, your UNO's onboard 5V regulator is going to drop that down to 3.5V or so. You must have more than 5V into the regulator to get 5V out of it. This is referred to as the regulator's "drop out" voltage. The specs for an UNO say to power it from at least 7V for that reason.

As an experiment you can power it this way without your lights attached and measure the "5V" header to GND to see this happening.

## Power Dissipation

Linear regulators like that found on the UNO are not efficient. They waste energy as heat in proportion to the current through it and voltage dropped by it.

If you provide it with 7V at the regulator and your project draws 0.5 amps from the regulator, you will try to generate 0.5A * (7V - 5V), that is 1 Watt of heat. Your regulator can probably dissipate half that with how it's mounted on the UNO and normal ambient air temperature.

Note this situation gets worse if you put 12V (for example) into the barrel jack, as you'd be dropping 7V across the regulator.

Many linear regulators have thermal overload protection built into them. They'll stop producing as much voltage at the output as they heat up to try to survive the event. And that's likely what you're seeing if you're trying to power your christmas lights from the regulator.

If you want to see this yourself might try **very** briefly tapping the regulator with your finger; it may be **blazing hot**. You might just dampen your finger and hold it *near* the regulator's surface to feel the heat coming off of it.

You will more than likely need to route power around the Arduino board to your lights to prevent this.
> 5 votes

---
Tags: arduino-uno, power, electricity
---


# Question
Title: How do i make my DC motors run simultaneously?
Im coding an adafruit motor shield for 3 DC motors to go forward & backwards, and so my concern is why only my motor3 is running the whole time and motors 1 & 2 are switching off meaning 1 goes than 2 goes and on and on? My code is below if you see where my mistake is in the code can you just tell me what it is and what to do to make them run simultaneously?

```
#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor(3);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");
  // turn on motor
  motor1.setSpeed(300);
  motor2.setSpeed(200);
  motor.setSpeed(500);
  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  //third motor
  Serial.print("tick");
  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  //second motor
  Serial.print("tick");
  motor2.run(FORWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }
  Serial.print("tack");
  motor2.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");
  motor1.run(FORWARD);
  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
  Serial.print("tack");
  motor1.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
}

```

# Answer
The simplest approach to include a delay in your sketch is to call the Arduino delay() function. Pass this function a delay value in milliseconds. For example, a 1 second delay is 1000 milliseconds.

As simple as this method is, it is not recommended if your sketch is required to accomplish tasks during the delay. This is a common requirement and frustrates many new programmers.

In order to accomplish tasks while waiting for an arbitrary period of time, do not use the Arduino delay() function. Instead use the Arudino millis() function. The millis() function will return the number of milliseconds passed since the Arduino board began running the current program. Record this number, execute the desired action then enter an infinite loop until millis() return a number which indicates the desired number of seconds have passed. While in the infinite loop the program can execute other tasks as long as they take small amounts of time relative to the desired delay. Such as testing for a switch closure and turning on an LED.

Essentially, this new program is now a simple finite state machine.
> 1 votes

# Answer
What you're searching for is called "non-blocking programming", a technique in which you frequently test or evaluate whether something needs to be done, and either do it or not, but *move on immediately*. For one motor, you could block successfully (do nothing else while you wait for something to happen): start/wait/stop/reverse/wait/stop/... etc.

But for two more more motors that need to run independently, your code must not block but decide *quickly* whether to do a particular thing now or not (start or stop a motor, f/ex), and *move on to the next decision*.

This article describes how to do that in more detail (full disclosure: it's one of mine).
> 1 votes

# Answer
Start with the BlinkWithoutDelay example code and make modifications to suit your needs.

This is the original code.

```
    /*
  Blink without Delay

  Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

```

---

Here are the changes that cause the LED to light up for 500 ms, then go dark for 5000 ms.

The changes are marked by `// *************`.

Hopefully, this will get you the idea about how to use millis() to control a device at desired intervals.

```
        /*
          Blink without Delay
          http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
        */

        const int ledPin =  LED_BUILTIN;                        // the number of the LED pin

    //  int ledState = LOW;                    // ************* // change this assignment as follows

        int ledState = 0;                      // ************* // ledState used as a state counter

        unsigned long previousMillis = 0;

    //  const long interval = 1000;            // ************* // change the interval as follows

        const long interval =  500;            // ************* // use a 500 ms interval

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

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

          if (currentMillis - previousMillis >= interval) {

            previousMillis = currentMillis;    // ************* // program arrives here every 500 ms

    //      if (ledState == LOW) {             // ************* // this code is not needed
    //        ledState = HIGH;                 // *************
    //      } else {                           // *************
    //        ledState = LOW;                  // *************
    //      }                                  // *************

    //      digitalWrite(ledPin, ledState);    // *************

            if (ledState == 0 ) {              // *************
                digitalWrite(ledPin, HIGH);    // ************* // turn on LED at start of cycle
            }                                  // *************
            else if (ledState == 1 ) {         // *************
                digitalWrite(ledPin, LOW);     // ************* // turn off LED at end of 500 ms
            }                                  // *************

            ledState++;                        // ************* // increment state counter
            if (ledState > 10 )  ledState = 0; // ************* // reset ledState when it has reached end of cycle

          }                                                     // end of if
        }                                                       // end of loop

```
> 1 votes

---
Tags: arduino-mega, programming, motor, adafruit
---


# Question
Title: Using Arduino UNO to retrieve ATMega328P-PU chip signature
Good day.

I have successfully built and tested an Arduino-on-breadboard about 2 days ago.

The device is rather straight forward, I have added a voltage divider and an LED to indicate power.

The schematics are as follows:

And this is a picture of the actual board:

I am using an ATMega328P-PU as a Microcontroller chip.

I uploaded quite a few sketches on the board and all seemed to work well. I was trying to upload a sketch yesterday but I got: **"avrdude: Yikes! invalid device signature"**.

I rebooted the computer, rebuilt the entire board again, and tried once again to load a sketch using Arduino as ISP. The message changed again to:

**avrdude: Expected signature for ATmega328P is 1E 95 0F Double check chip, or use -F to override this check. Wrong microcontroller found. Did you select the right board from the Tools \> Board menu?**

I did a search online and I have found many forums suggesting that I change the avrdude.conf file parameters to different signatures "Although these are mainly targeted at people using ATMega328-PU, not ATMega328P-PU" but this also did not help.

I tried burning the bootloader again but I still get the same error message.

I tried to find a way to "retrieve" the chip signature, but I didn't.

I know that there is a chance that I have bricked the chip somehow, but how do I know for sure? and is there anyway that one can use and Arduino as a tool to retrieve the chip signature or verify if the chip itself is dead?

Thank You

# Answer
> 1 votes
There is a nice explanation here about Atmel chip signatures.

It sounds like you already know this, so for others looking for help:

*It says that there are different signatures in the Atmel chips you mention. That you can over ride the Avrdude program using an "-F" switch. Or you can change the Avrdude configurations to use the "other" Atmel chip (however, the consequences if any were unknown by the author).*

This may be an obvious step, but double check to make sure the IDE's target board settings are correct.

You may also want to check the communications between the programmer and the target. You might look into dropping the speed. But the better way is to scope the lines to see if data is being sent to the target and if the target is talking back. From that you can infer if the problems is a bad connection or if the chip has been damaged.

If you want to dig further using software tools you could look into driving Avrdude for your self. There is a easy to read tutorial here and what appears to be an everything you wanted to know and more document here.

In the 1st tutorial (from ladyada.net) we see a test which they purposely try the wrong signature:

> Just for kicks try running this command avrdude -c usbtiny -p atmega8 -U flash:w:test\_leds.hex

> You'll see that it stops at step 2, once the signature is different than the expected one it stops. This is because code that is compiled for an attiny2313 wont run on an atmega8 (this is true of most microcontrollers, the .hex files are not cross compatible)

But more interestingly, Avrdude prints out the signature read back from the target! So, if you run the same test, you could tell if Avrdude is able to communicate at all with the target. That is, you may see all zeros or all ones or even an alternate message from Avrdude. Which could be an indication that the target is not talking.

# Answer
> 1 votes
More than a year down the road, I learned a few things, and I am answering my own question so that if anyone faces the problem I faced (and I know how stressful it is) can give this a go. It may help.

One of the most interesting things I have learned is Mr. Nick Gammon's (Someone have actually called him *Mr. Arduino*) wonderful collection of sketches designed to do exactly this sort of thing.

If you ever need to find out what is the signature of your ATMega328 (or any arduino micro controller chip for this matter, visit this site.

The main reason I asked the question was to "un-brick" my ATMega328s, and I have actually done some thing wrong that to this day I can not figure out that resulted in 4 chips giving the error in the question. Just when I was about to give up, I found this link from Mr Gammon's website which sorted out the problem in 3 out of the 4 ATMegas, the fourth I am keeping to test a high voltage programmer in the future.

Thank you.

# Answer
> 1 votes
when you try to change the signature there are 2 areas where the code 1E 95 0F is displayed. If you try changing the signature in the wrong position, then will it show the error message 'microcontroller not found'. I did the same mistake once. I would suggest you rely on the find option in the Edit menu and search for the code. Edit \> Find \> Search 1E 95 0F \> ( opt for 'down') search next.

---
Tags: arduino-uno, atmega328, avrdude, arduinoisp
---


title: Arduino Pro Micro bricked?

text:
# Question
Title: Arduino Pro Micro bricked?
I have a Pro Micro board at which tried to upload a sketch with sparkfun's Pro Micro 3.3v processor selected.

After the upload completed successfully the board did not run again and is not even detected from the arduino ide anymore.

When I uploaded sketches with the leonardo 5.5v board selected everything went well and I had no problem. Now I can not burn the bootloader because of the arduino ide not detecting the board.

What can i do?

# Answer
Problem solved! By taping twice the reset and holding it the second time I managed to program my board and now the arduino ide detectes it and it works as expected.

Taping and releasing the button twice did not work but holding it the second time worked for me. I am a almost complete noob in electronics for now so to me is black magic that not releasing the button did the job instead of what everyone else is suggesting.

I hope this helps a newbie sometime in the future that is frustrated with his/er bricked board
> 3 votes

# Answer
After bricking a few units I finally sat down and read the manual for my SparkFun Qwiic Pro Micro - USB-C (ATmega32U4). I also figured out the cause.

The cause of my unit bricking was bad code. Compiled and profiled fine, but crashed the unit when uploaded. As a result the port became unavailable and seemingly gone. In my particular case one brick was via and unsupported command in my source. The second brick was abuse of memory. Sketches would upload, then the unit dies and the no connection message pops up.

The solution for this unit was use of the reset switch with some key timing, and a trusted script to recapture the device. This page was all I needed to read, classif #RTFM syndrome.

The following is a layman version of events for those less fortunate having not endured decades of software brain melt.

## Recovery in a Nutshell

The USB port/comm when working will/can flip between the "normal" mode and the bootloader mode. Bootloader is a mode where the devices is exposed and can receive code and special commands.

If something, like the code, is causing the device to crash, such as I had, then the desired USB/serial port is not available.

### The Reset Switch

The reset switch may also be some pins to be shorted. The manual talks about high/low and resistance. Generally I have found you just short the damn thing, milage may vary. I used the button.

Per the instructions you can double tab the button and then I seem to trail off and not really absorb the rest. Eventually I got the pattern.

### The Pattern

If you double click the reset button the device goes into boot loader for 8 seconds.

Find a short "hello world" sketch and have it ready.

Double tap the reset button and **immediately** upload the sketch.

> That may not work...

When uploading a sketch the beginning of the upload is the compile step. This must complete before there is anything to ship to the device.

I had to click upload and then double tap and get the timing right. Eventually I would use the shortcut (CMD/CRTL + U). The sketch takes and the device is back to normal.

Hope this helps someone - I needed the dummy version.
> 0 votes

---
Tags: bootloader, arduino-pro-micro, reset
---


title: Arduino keypad variables to serial port

text:
# Question
Title: Arduino keypad variables to serial port
I've been trying, for over a week now, to create a program that will store my keypad presses into variable, and with a press of an enter, it will switch to the next variable to store the presses. The program is made to load addresses (mainly IP addresses) to different devices over serial connections. Because there are different types of addresses, each time the user press enter in the keypad (made the # button to a '\r' char) the program needs to switch to the next type of address and get the key presses from the keypad and store them until the next '\r' press. My problem is that I don't know how to store those addresses in the Arduino, and switch to a different "char" (I used char because I didn't knew how to convert them to store key presses into string) every '\r' press. I've included the handler for this part of my code. This is my first post here so if anything is missing let me know. thanks ahead.

```
bool handlerManualEntry( void )
{
    static uint8_t stateManualEntry = statesFunc::ST_INIT;

    char keyval = ReadKey();
    switch( stateManualEntry )
    {
        case    statesFunc::ST_INIT:
            //do whatever inits you need here (screen, variables etc)

            stateManualEntry = statesFunc::ST_RUN;

        break;

        case    statesFunc::ST_RUN:
            //is there a keypress?
            if( keyval != NO_KEY )
            {
                switch( keyval )
                {

                    case    '\r':
                        //when we get a return, send it to the serial port
                        Serial.print( '\n' );
                        u8g2log.print('\f');
                        for(int i=0; i<6; i++)
                        {
                          if(i == 0)
                          {
                          Serial.print(ethernetIP);
                          }
                        else if(i == 1)
                          {
                          Serial.print(ethernetSubnet);
                          }
                        else if(i == 2)
                          {
                          Serial.print(ethernetGetway);
                          }
                        else if(i == 3)
                          {
                          Serial.print(vmeIP);
                          }
                        else if(i == 4)
                          {
                          Serial.print(vmeSubnet);
                          }
                        else if(i == 5)
                          {
                          Serial.print(eventPort);
                          }
                        else if(i == 6)
                          {
                          Serial.print(timeOut);
                          }
                        }
                        //and finish out by returning the state to INIT and returning true
                        //stateManualEntry = statesFunc::ST_INIT;
                        //return true;

                    break;
                    case 'D':
                          u8g2log.print('N');
                          Serial.print('N');
                    break;

                    case 'C':
                          u8g2log.print('Y');
                          Serial.print('Y');
                    break;

                    default:
                        //for any other key, print to the serial port and LCD
                        u8g2log.print(keyval);

                        enterAddresses();
                    break;

                }

            }

        break;

    }

    return false;

}

void enterAddresses()
{
  int x;
  if(keyval != '\r')
  {
    if(pointer == 1)
    {

      keyval = keypad.getKey();
      u8g2log.print(keyval);
      ethernetIP += keyval;
    }
    else if(pointer == 2)
    {
      keyval = keypad.getKey();
      u8g2log.print(keyval);
      ethernetSubnet += keyval;
      }
    }
    else if(pointer == 3)
    {

      keyval = keypad.getKey();
      u8g2log.print(keyval);
      ethernetGetway += keyval;

    }
    else if(pointer == 4)
    {
      keyval = keypad.getKey();
      u8g2log.print(keyval);
      vmeIP += keyval;
    }
    else if(pointer == 5)
    {
        keyval = keypad.getKey();
      u8g2log.print(keyval);
      vmeSubnet += keyval;
    }
    else if(pointer == 6)
    {
      keyval = keypad.getKey();
      u8g2log.print(keyval);
      eventPort += keyval;
    }
    else if(pointer == 7)
    {

      keyval = keypad.getKey();
      u8g2log.print(keyval);
      timeOut += keyval;

    }
    pointer++;
    u8g2log.print('\f');

}

char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'.','0','\r','D'}
};

byte rowPins[ROWS]={39,41,43,45};
byte colPins[COLS]={31,33,35,37};

//Create an object of keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
char keyval;

```

# Answer
* Consider constraining the user and simplifying your code.

Simplify your code by putting rules on how the IP address is entered. When entering the IPv4 address in dot-decimal notation require that all 3 digits are always used for each of the four quad-dotted notation values. For example, the IPv4 address 192.168.10.20 would be entered as "192168010020".

* Eliminate unnecessary keypad buttons.

The only keys required for the above scheme are 0, 1, 2, ..., 9. No other keys need to be detected or supported by additional software.

* Start simple, get that working then add complexity.

Essentially, a state machine is most often used as the underlying coding pattern when interfacing with a user. Keeping track of what the user has done, the current state the user is in and where the user may go is the job of the state machine. To implement the above, the state machine will need to be complex enough to track the 1s, 10s & 100s position of each quad-dotted notation values as well as which quad-dotted notation value is currently being entered. This is complex enough for a first pass. Later, in subsequent passes, consider adding an "abort" key for when the user feels a new attempt is in order. Still later, consider adding a "back space" key. Finally, consider adding an "enter" key and dripping the 3 digit per quad-dotted notation value requirement.
> 1 votes

---
Tags: serial, string, keypad
---


# Question
Title: What are patterns of bits sent to or read from GPIO pins called?
I want to call them “words”, but I’m uncertain if this is how they are referred to in documentation for the use of a header board that might plug into an ardino board.

So if you have a sequence of ONs and OFFs being read or sent from a microcontroller board are those called words? What are they called?

# Answer
> 1 votes
Here is a simplistic diagram.

Larger than 8 bits is usually referred to as WORD.

# Answer
> 1 votes
Consider backing away from Arduino hardware for just a moment

> I want to call them “words”, but I’m uncertain ...

For most computers and processors a word is comprised of bytes and bytes are comprised of bits. A bit is an individual 0 or 1. That's always true. A byte is almost always made up of 8 bits. Why? Because it is always convenient to do things on a computer or processor in powers of 2. That is, 2 or 4 or 8 or 16 or 32 or ... (keeps going). And 8 is a convenient sized number of bits! A word is usually 2 bytes or 16 bits. But that's not always true. For some computers it is more.

Keep in mind, so far, we are just talking about data. Not physical GPIO pins. When we do interface through the GPIO pins this data can be sent out in parallel or in serial form. It really depends on how we want to interface with the world! For instance, many Arduino projects uses a serial interface called an I2C bus to talk with peripherals such as a temperature sensor.

> So if you have a sequence of ONs and OFFs being read or sent from a microcontroller board are those called words?

This sounds like you are talking about serial data (as apposed to parallel data).

* Talking about the hardware: The GPIO lines on most embedded processors are designed to interface with the world using parallel data. You can use software and "emulate" a serial stream of data on one of the GPIO lines. But you might not be able to send out data fast. Instead, most embedded processors have special serial port pins which are connected to fast hardware usually called UARTs. When sending or receiving serial data, it is almost always better to use a pin connected to a UART.
* Talking about the data: Again, word can mean different amounts of data on different processors. And to further complicate things, some serial protocols mix things up and end up sending out or reading data using an odd number of bits. Which makes talking about the combined bits as a word confusing. At this point I would just stop using the word "word" to describe the data and just call it "data".

Besides, most Arduino boards (like the Arduino Uno) use embedded processors which interface directly to peripherals such as temperature sensors over serial ports. As such, the data format is usually spelled out by the peripheral and is (very) specific for the purpose of the peripheral (temperature sensing in this case). It is recommended to read the specifications for the peripheral and use the terminology presented there when communicating with others regarding that particular peripheral.

---
Tags: arduino-uno, header
---