# Question
Title: Arduino remote-controlled car stops after a few seconds
I am making a remotely controlled car for a project at Uni. The car is made from an Arduino Uno, a 2 motor driver and a Bluetooth transceiver. I have written some code for it, but it randomly stops after 2 or 3 loops.

Here is my code:

```
#include "SoftwareSerial.h"

typedef unsigned char u8;

typedef struct {
  u8 right;
  u8 left;
} speed;

SoftwareSerial bluetooth(4, 2);

const u8 RIGHT_MOTOR_PIN1 = 3;
const u8 RIGHT_MOTOR_PIN2 = 5;
const u8 LEFT_MOTOR_PIN1 = 6;
const u8 LEFT_MOTOR_PIN2 = 9;

const u8 MAX_SPEED = 0xFFU;
const u8 HALF_SPEED = MAX_SPEED / 2;
const u8 NO_SPEED = 0x0U;

static u8 command = 0U;
static speed potentialSpeed;
static speed actualSpeed;

void setup() {
  bluetooth.begin(115200);
  while (0U != bluetooth.available()) bluetooth.read();
  potentialSpeed.right = MAX_SPEED;
  potentialSpeed.left = MAX_SPEED;
  actualSpeed.right = NO_SPEED;
  actualSpeed.left = NO_SPEED;
}

void loop() {
  readCommand();
  {
    if (clockwise(command)) {
      if (0U == (command & 0xFEU)) {
        actualSpeed.right = - MAX_SPEED;
        actualSpeed.left = + MAX_SPEED;
      }
    } else if (counterclockwise(command)) {
      if (0U == (command & 0xFDU)) {
        actualSpeed.right = + MAX_SPEED;
        actualSpeed.left = - MAX_SPEED;
      }
    } else {
      if (right(command)) {
        potentialSpeed.right = HALF_SPEED;
      }
      if (left(command)) {
        potentialSpeed.left = HALF_SPEED;
      }
      if (forward(command)) {
        if (!backward(command)) {
          actualSpeed.right = + potentialSpeed.right;
          actualSpeed.left = + potentialSpeed.left;
        }
      } else if (backward(command)) {
        actualSpeed.right = - potentialSpeed.right;
        actualSpeed.left = - potentialSpeed.left;
      }
    }
    if (0U == command) {
      potentialSpeed.right = MAX_SPEED;
      potentialSpeed.left = MAX_SPEED;
      actualSpeed.right = NO_SPEED;
      actualSpeed.left = NO_SPEED;
    }
  }
  runAt(actualSpeed);
  delay(95);
}

void readCommand(void) {
  command = 0U;
  if (1U == bluetooth.available())
    command = bluetooth.read();
}

inline boolean clockwise(u8 command) {
  return (boolean)((command >> 0U) & 1U);
}
inline boolean counterclockwise(u8 command) {
  return (boolean)((command >> 1U) & 1U);
}
inline boolean right(u8 command) {
  return (boolean)((command >> 2U) & 1U);
}
inline boolean left(u8 command) {
  return (boolean)((command >> 3U) & 1U);
}
inline boolean forward(u8 command) {
  return (boolean)((command >> 4U) & 1U);
}
inline boolean backward(u8 command) {
  return (boolean)((command >> 5U) & 1U);
}

void runAt(speed Speed) {
  if (Speed.right > 0U) {
    analogWrite(RIGHT_MOTOR_PIN1, 0U);
    analogWrite(RIGHT_MOTOR_PIN2, Speed.right);
  } else {
    analogWrite(RIGHT_MOTOR_PIN1, (-(Speed.right)));
    analogWrite(RIGHT_MOTOR_PIN2, 0U);
  }
  if (Speed.left > 0U) {
    analogWrite(LEFT_MOTOR_PIN1, 0U);
    analogWrite(LEFT_MOTOR_PIN2, Speed.left);
  }
  else {
    analogWrite(LEFT_MOTOR_PIN1, (-(Speed.left)));
    analogWrite(LEFT_MOTOR_PIN2, 0U);
  }
}

```

Could you please help me find the cause?
Also, I am unable to make it go backwards. Can that be related?

# Answer
> 1 votes
The problem was that the bluetooth module would receive bytes faster than the SoftwareSerial was able to read, so `bluetooth.available()` would return more than `1U` after a couple of loops. This was fixed by changing the following:

```
void readCommand(void) {
  command = 0U;
  if (bluetooth.available()) {
    while(bluetooth.available() > 1U)
      bluetooth.read();
    command = bluetooth.read();
  }
}

```

The 'make-it-run-backwards' problem was also solved, but was unrelated.

---
Tags: arduino-uno, motor
---


title: Wireless Communication with NRF24L01+

text:
# Question
Title: Wireless Communication with NRF24L01+
I have decided to use NRF24L01+’s for my Arduino project for wireless communication. I am using the RF24 library by TMRh20 to talk back and forth.

Github Link: https://github.com/nRF24/RF24

I want to be able to send and receive data as fast as possible between the remote, and the receiver. After reading through the library I was able to create a some simple code that allowed the remote to transmit ~600 32-byte messages a second and the receiver was able to read ~490 messages a second.

Transmitter Loop Code:

`if (radio.available())
 { radio.read( &myData, sizeof(myData) ); }`

Receiver Loop Code:

`radio.write( &myData, sizeof(myData), 1);`

With this code however, the remote control cannot receive telemetry data back from the receiver. It is only a one way communication with no acknowledgments.

I have a few questions about wireless communication with the NRF24L01+. First, what is an acknowledgement? I understand it is a way for the transmitter to know that the receiver got the message, but what is being sent in the acknowledgment?

What is the difference between commands such as radio.write, radio.writefast, radio.startwrite, and radio.startwritefast. The RF24.h file has explnations of these commands but their desrciption does not make too much sense to me.

After doing some research, I found that to write, I must stop listening, write the message, and then start listening again for messages. The issue with this code is that the NRF is never listening long enough to receive a message (unless I add in a delay where it stays in RX mode). Is there anyway to keep a reading pipe open while writing and then pick it up from the FIFO when I am ready to read?

It seems that it is possible to write an ACK Payload, and this allows the NRF to transmit a message without leaving RX mode. Is this a possibility, and what is an ACK Payload?

What is the best practice for achieving the fastest speed two-way communication. Is it common practice to have two NRF’s and have one dedicated to listening and one dedicated to writing on each Arduino? Is there a good way to achieve high speed two-way communication rates with a single NRF?

# Answer
firstly, the `radio.write` command is used for checking for the acknowledgement from the RX after the `FIFOs` are full for a single write. But `radio.writefast` will not wait for the acknowledgement from the RX and would continuously transmit the payload for a single write. Similarly for `radio.startwrite` and `radio.startwritefast` commands.

Coming to the keeping the NRF in listening mode, even I haven't tried it before so I cannot suggest an exact solution for this problem. But as far as I know, you can go for `writestart` command to keep the reading pipes open while you are sending. But I would personally suggest you to confirm this from datasheet again before experimenting.

For ACK payload, it depends upon the master unit controlling the `SPI communication` with the NRF chip and thus, by maintaining a mutual understanding between the RX and TX units, you can define the payload for acknowledgement signal as well.

Coming to best speed possibility, To increase speed, NRF has three speeds from which you can select the highest value available. Also see which `pipe/channel` works the best for you so that you can achieve the least number of lost packets.
> 3 votes

---
Tags: nrf24l01+, wireless
---


# Question
Title: atmega88 timer2 32.768KHz and Serial problem
I am trying to use atmega88 timer2 with a 32.768KHz crystal. I'm using a slightly modified version of Nick Gammon's code. I am using Minicore. No bootloader, 1MHz clock from internal oscillator, BOD disabled. Sleep is interrupted every 8 seconds. I use a counter to count 12 minutes. Since it overshoots about 8 seconds every 6 hours, I am subtracting 8 sec every 6 hours. I hope to eventually make a weather logger with this.

The code is mostly working in it's bare stripped down version, after I add a delay(100) after the digitalWrite. However, I also need Serial. When I enable Serial, it does not sleep anymore. Also, the serial output has a lot of excess weird characters. This happens at all baud rates, even 1200 (serial monitor set to same baud rate as in program). I think some interrupts are being called during digitalWrite and when the usart is powered on and it is messing with the sleep. I am a beginner regarding uC programming, and am really struggling with the datasheet and the code. Any help will be appreciated.

Here is the test code:

```
#include <avr/sleep.h>
#include <avr/power.h>

const byte tickPin = 4;// (do not use 3 and 11)

//byte intCounter = 0;
//byte leapCounter = 0;

int intCounter = 0;
int leapCounter = 0;

unsigned long prevTime = 0;
unsigned long currTime = 0;

// interrupt on Timer 2 compare "A" completion - does nothing
EMPTY_INTERRUPT (TIMER2_COMPA_vect);

void setup(){
  pinMode (tickPin, OUTPUT);

  Serial.begin(9600);
  prevTime = millis();
  Serial.print(" P: ");
  Serial.println(prevTime);

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);

  // set up timer 2 to count up to 256 * 1024  (8 seconds)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  255;                                     // (zero-relative)

  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);

  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_twi_disable();
//  power_timer0_disable();
//  power_timer1_disable();
  power_spi_disable();
  power_usart0_disable();
  power_adc_disable ();

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);

  // get ready ...
  sleep_enable();

}  // end of setup

void loop(){
  sleep_cpu ();
  ++intCounter;

  power_usart0_enable();
  Serial.print("I: ");
  Serial.print(intCounter);
  Serial.print(" L: ");
  Serial.print(leapCounter);
  currTime = millis();
  Serial.print(" C: ");
  Serial.print(currTime);
  Serial.print(" E: ");
  Serial.print(currTime - prevTime);
  Serial.println();
  prevTime = currTime;
  power_usart0_disable();
  delay(1000);

  if ((leapCounter > 30) && (intCounter == 1)){
    leapCounter = 0;
    intCounter = 0;
  }
  if (intCounter > 89){
    ++leapCounter;
    intCounter = 0;
    digitalWrite (tickPin, ! digitalRead (tickPin));
    delay(100);
  }
//  digitalWrite (tickPin, ! digitalRead (tickPin));
//  delay(100);
}  // end of loop

```

The chip is an Atmega88 (not P). It is drawing the same 6.5uA during sleep, with or without timer0 and timer1. So, I probably don't care if I have to leave them enabled.

I am planning to use a DHT11 and a ds18B20 and write the data to a w25Q64 flash, every 12 minutes. I'd prefer reading it all out via serial port every few weeks, without having to stop the uC.

**update**

Calling timer2 ISR, instead of handling wake up directly in main loop. Possibly more stable (not affected by Serial and digitalWrite)... but I am not sure.

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

//const byte tickPin = 4;// (do not use 3 and 11)

volatile bool t2flag = LOW;
volatile byte t2counter = 0;

byte leapCounter = 0;

//preventing digitalWrite from causing interrupt (did not help much)
EMPTY_INTERRUPT(PCINT2_vect);

void setup(){
  pinMode (4, OUTPUT);
  pinMode (1, INPUT_PULLUP); //set TX pin default HIGH

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);
  // set up timer 2 to count up to 256 * 1024  (8 seconds)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  255;                                     // (zero-relative)
  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);
  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_twi_disable();
//  power_timer0_disable();
//  power_timer1_disable();
  power_spi_disable();
  power_usart0_disable();
  power_adc_disable();
  wdt_disable();// reduces 6.5uA to 2.2uA @ 3.3V

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);
  sleep_enable();
}

//ISR to handle timer2
ISR (TIMER2_COMPA_vect){
  ++t2counter;
  if (t2counter > 89){t2flag = HIGH;}
}

void loop(){
  if (t2flag == LOW){

    power_usart0_enable();
    Serial.begin(9600);
    Serial.print("I: ");
    Serial.print(t2counter);
    Serial.println();
    Serial.flush();
    delay(10);
    Serial.end();
    power_usart0_disable();

    //blip the tickPin every 8 sec
    PORTD |= (1<<PD4);
    delay(10);
    PORTD &= ~(1<<PD4);

    delay(100);//helps a lot
    sleep_cpu();
    return;
  }

  ++leapCounter;
  if (leapCounter == 30){
    t2flag = LOW;
    return; //delay another 8 sec every 6 hours
  }
  if (leapCounter > 30){leapCounter = 0;}

  t2flag = LOW;
  t2counter = 0;

  power_usart0_enable();
  Serial.begin(9600);
  Serial.print("L: ");
  Serial.print(leapCounter);
  Serial.println();
  Serial.flush();
  delay(10);
  Serial.end();
  power_usart0_disable();

  //long blip every 12 minutes
  PORTD |= (1<<PD4);
  delay(100);
  PORTD &= ~(1<<PD4);
}

```

The problem is not always present. But when it appears, it happens the same way. After pressing reset button, first led blink is always after 8 seconds. After that, one of three things seem to happen. 1. Second flash is after 8 seconds and everything works as expected. 2. Second flash is after 3 seconds and all flashes after that are also after every 3 seconds. 3. Second flash happens immediately after first flash (and any delay() in the code) and this keeps on happening. In all cases, the serial output also shows the same pattern.

Sometimes it seems that wires connected to the serial or miso, mosi, sck may be causing this, but that is not always the case. The problem may occur even if these wires are not connected. Also, the problem may or may not occur with the same code (e.g. pressing reset after 30 sec may not show any problem, but pressing reset within 5 or 10 seconds leads to problem cases 2 and 3 above. So there is some kind of race condition, or buffer or interrupt noise or something.

I have to program with Arduino as ISP, as the bootloader is unable to sync with the ftdi chip for some reason while uploading sketch. But data transfer from the sketch with serial.print is working fine. So pulling out the miso mosi sck pins everytime is a hassle. Everything is on breadboard. I transferred full circuit to new breadboard (from old loose breadboard) but there is no change. So maybe not a breadboard issue.

# Answer
I see two issues in this code.

The first is that you are trying to send data through an UART that has been powered off. `Serial.print()` doesn't wait for the data to get out, it merely stores it into a memory buffer. You should wait until everything gets out before switching the UART off. This can be done by calling either `Serial.flush()` or `Serial.end()`. I would use the latter, as it feels safer to stop the UART before switching if off. But then you have to `Serial.begin()` again on wakeup.

To avoid the garbled characters in the serial stream, you could try to either `pinMode(1, INPUT_PULLUP);` or `digitalWrite(1, HIGH);`. This way you ensure that the TX line stays `HIGH` (which is its normal idle state) when the UART goes off.

The second issue is your use of the Arduino timekeeping functions `millis()` and `delay()`. These functions rely on an interrupt triggered by Timer 0. If you power off that timer, `millis()` and `delay()` won't work. If you don't, `SLEEP_MODE_PWR_SAVE` does it for you while sleeping. Then those function will work while awake, but `millis()` will not count the time you spent sleeping.

---

**Edit:** There are two interrupts related to the UART that are enabled by `Serial.begin()`:

* `USART_UDRE`, “Data Register Empty”, is used for transmission. It fires when the hardware transmit buffer is ready to receive new data. The corresponding ISR's job is to copy one byte from the transmit memory buffer (the one `Serial.print()` writes into) into the hardware transmit buffer.
* `USART_RX`, “Receive Complete”, is used for reception. It fires when a byte is received. The corresponding ISR copies this byte into receive memory buffer (the one `Serial.read()` reads from).

The first one fires when transmitting. Once you wait for the end of the transmission (say with `Serial.flush()`), you shouldn't see this interrupt firing anymore.

The second one fires only when receiving. If you are not receiving anything, this interrupt shouldn't fire. If the RX pin is floating, the interrupt could be triggered by external noise. This can be prevented by enabling the internal pullup on the RX pin. Alternatively, you can disable the receiver part of the UART:

```
UCSR0B &= ~_BV(RXEN0);  // disable the UART receiver

```

Note that if you stop the UART with `Serial.end()`, both the transmitter and the receiver are disabled, and you don't get UART-related interrupts anymore.
> 2 votes

---
Tags: serial, interrupt, timers
---


# Question
Title: How to drive 16 stepper motors with Arduino?
I'm trying to drive 16 of these little steppers on an Arduino Uno.

Each test driver uses 4 digital pins for control (2 for each coil) so that would be 64 pins I will need.

I'm thinking either getting something like this or 4 of these.

Would something like that work ? What's the most straight forward way to drive these on an Arduino Uno ?

# Answer
> 1 votes
If you need to drive all 16 simultaneously and independently, the Uno may not have enough capability to do it. Consider the worst-case number of motors and highest rate(s) you expect to drive at once, plus anything else you need the Uno doing at the same time. You might try a simple sketch to do all of these things (substituting LEDs for the motor drivers) at once, and use a scope to examine those LED output signals for the right frequency, wave-form, and lack of jitter. Without I/O expanders, you won't get to 16 motors' worth of outputs (unless you already have an I/O expander) but you might try doubling up on the existing output (use non-overlapping motor phases if you can).

If the Uno can manage that with clean outputs, you'll have a better idea whether it can manage the full load. If it doesn't, you may need to reconsider your choice of processor with respect to its clock-speed, both kinds of memory (depending on what you learned), number of outputs, possibly number of available timers and of interrupts.

---
Tags: arduino-uno, i2c, pins, stepper, shift-register
---


title: Arduino IDE - Ubuntu Mono Font Name?

text:
# Question
Title: Arduino IDE - Ubuntu Mono Font Name?
I know that you go to *preferences.txt* and there is `editor.font=` line setting, but I can't get what font name to type in there to use **Ubuntu Mono**. I would like to use that font please. I've tried:

```
Ubuntu_Mono
Ubuntu-Mono
Ubuntu Mono
Ubuntu+Mono
Ubuntu.Mono
UbuntuMono
Ubuntumono
ubuntumono
'Ubuntu Mono'
"Ubuntu Mono"
'UbuntuMono'
"UbuntuMono"
'Ubuntu-Mono'
"Ubuntu-Mono"
'Ubuntu_Mono'
"Ubuntu_Mono"

```

Thanks for answer :\]

PS: Yes, I've restarted the studio every time, but some non-monotype/default font showed up.

# Answer
> 3 votes
You need to specify the font, style and size. I think you want

```
editor.font=Ubuntu Mono,plain,12

```

I don't know the exact name you should use for the font but you must have all three fields separated by commas.

The second field can be "plain", "bold" or "italic".

The third field is the font size, I'm not sure the units.

---
Tags: arduino-ide
---


# Question
Title: arduino nodejs serial data chunked and not in synch
I'm trying to get an arduino sending data to node but with no success. I'm connecting to an ar-drone 2.0 as in https://gist.github.com/maxogden/4152815

Here is my **Arduino** code:

```
    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    #include <Wire.h>
    #include "Adafruit_HTU21DF.h"
    /*
      Sketch per creare json contenente
      lat,lon,data,ora,temp, hum
    */
    static const int GPS_RXPin = 16, GPS_TXPin = 10;
    static const uint32_t GPSBaud = 9600;

    Adafruit_HTU21DF htu = Adafruit_HTU21DF();

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(GPS_RXPin, GPS_TXPin);

    //JSON
    const size_t bufferSize = JSON_OBJECT_SIZE(6);
    DynamicJsonBuffer jsonBuffer(bufferSize);
    JsonObject& oData = jsonBuffer.createObject();

    void setup()
    {
      Serial1.begin(9600);
      Serial.begin(9600);
      ss.begin(GPSBaud);
      if (!htu.begin()) {
        Serial1.println("Couldn't find Adafruit_HTU21DF!");
        while (1);
      }
    }

    void loop()
    {
      float lat = gps.location.lat();
      float lon = gps.location.lng();
      float date = gps.date.value();
      float timestamp = gps.time.value();
      float temp = htu.readTemperature();
      float hum = htu.readHumidity();

      Serial1.print(lat);
      Serial1.print(";");
      Serial1.print(lon);
      Serial1.print(";");
      Serial1.print(date);
      Serial1.print(";");
      Serial1.print(timestamp);
      Serial1.print(";");
      Serial1.print(temp);
      Serial1.print(";");
      Serial1.print(hum);
      Serial1.print(";\n");

      //////

      Serial.print(lat);
      Serial.print(";");
      Serial.print(lon);
      Serial.print(";");
      Serial.print(date);
      Serial.print(";");
      Serial.print(timestamp);
      Serial.print(";");
      Serial.print(temp);
      Serial.print(";");
      Serial.print(hum);
      Serial.print(";\n")

      smartDelay(1000);
      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial1.println(F("No GPS data received: check wiring"));
    }

    // This custom version of delay() ensures that the gps object
    // is being "fed".
    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

```

and this my **NodeJS** code:

```
    var serialport = require('node-serialport');
    var WebSocketServer = require('ws').Server;

    var wss = new WebSocketServer({host:'0.0.0.0',port: 9999});
    var sp = new serialport.SerialPort("/dev/ttyO3", {
      parser: serialport.parsers.readline("\n"),
      baud: 9600,
      buffersize: 65536
    });

    wss.on('connection', function(ws) {
      ws.send('connected');
      ws.on('message', function(message) {
        console.log('received: %s', message);
      });
      sp.on('data', function(chunk) {
        var fromArduino = chunk.toString();
        ws.send(fromArduino);
        console.log(fromArduino);
      });
    });

```

While the CSV comes out nice on Arduino IDE serial monitor, it is all messed up both on ws and node console.

I'm using this version of NodeJS and node-serial: https://github.com/felixge/node-cross-compiler/downloads

and set ttyO3 as in https://gist.github.com/maxogden/4152815

A voltage diveder is set between drone RX and Arduino TX1 to lower signal from 5v to 1.8v.

Thanks for any help!

Lorenzo

---

**UPDATE 2 JUN 2018** I managed to make things a little bettere with the following code: **ARDUINO:** #include #include #include "Adafruit\_HTU21DF.h" /\* Sketch per creare json contenente lat,lon,data,ora,temp, hum \*/ static const uint32\_t GPSBaud = 9600;

```
    Adafruit_HTU21DF htu = Adafruit_HTU21DF();

    // The TinyGPS++ object
    TinyGPSPlus gps;

    void setup()
    {
      Serial1.begin(9600);
      //  Serial.begin(9600);
      if (!htu.begin()) {
        Serial1.println("Couldn't find Adafruit_HTU21DF!");
        while (1);
      }
    }

    void loop()
    {
      while (Serial1.available()) {
        gps.encode(Serial1.read());
      }
      float lat = gps.location.lat();
      float lon = gps.location.lng();
      int date = gps.date.value();
      float timestamp = gps.time.value();
      float temp = htu.readTemperature();
      float hum = htu.readHumidity();

      Serial1.print(lat);
      Serial1.print(";");
      Serial1.print(lon);
      Serial1.print(";");
      Serial1.print(date);
      Serial1.print(";");
      Serial1.print(timestamp);
      Serial1.print(";");
      Serial1.print(temp);
      Serial1.print(";");
      Serial1.print(hum);
      Serial1.print(";_");
      Serial1.println();
    }

```

**NODE JS**:

```
    var serialport = require('node-serialport');
    var WebSocketServer = require('ws').Server;

    var wss = new WebSocketServer({host:'0.0.0.0',port: 9999});
    var sp = new serialport.SerialPort("/dev/ttyO3", {
      parser: serialport.parsers.readline("_"),
      // parser: serialport.parsers.raw,
      baud: 9600,
      buffersize: 1024
    });
    wss.on('connection', function(ws) {

      sp.on('data', function(chunk) {
        var fromArduino = chunk.toString();
        // console.log(fromArduino);
        ws.send(fromArduino);
        sp.flush();
      });
    });

```

Now data comes out tidy on both console and ws for most of the times: I guess the problem was the serialport buffersize.

I also removed serial software from Arduino code.

# Answer
```
  Serial.print(lat);
  Serial.print(";");
  Serial.print(lon);
  Serial.print(";");
  Serial.print(date);
  Serial.print(";");
  Serial.print(timestamp);
  Serial.print(";");
  Serial.print(temp);
  Serial.print(";");
  Serial.print(hum);
  Serial.println(";");

```

`Serial.println` will print an `\r\n` at the end (source). `\r` is a "carriage return" which will move the curser back to the beginning of the line.

Since you are reading your data with a parser that looks for `\n` and removes that, you are left with a string that looks like `[csv data..]\r`. Once you print that to console verbatim you get the behaviour you are looking at.

Replace `Serial.println(";");` by `Serial.print(";\n");` (same for `Serial1`) and see what happens.
> 2 votes

---
Tags: serial, communication, string, node.js
---


title: Compile Problem with RFDuino RFD22301

text:
# Question
Title: Compile Problem with RFDuino RFD22301
I have the following setup: \- Arduino IDE for Mac 1.8.5 \- RFDuino RFD220301 \- CP2102 USB to UART connector \- Board set to "RFduino" \- port set correctly (but shouldn't matter as it is a compile error) \- Programmer: AVRISP mkII

When trying to compile an example script using BLE (Such as AdvertisementContinuous) I get the following error

arm-none-eabi-g++: error: /var/folders/m6/mfwpb8b13wn4f9fvb4lhx\_v40000gp/T/arduino\_build\_188605/core/syscalls.c.o: No such file or directory

Any ideas?

Here's the -v log:

```
Arduino: 1.8.5 (Mac OS X), Board: "RFduino"

/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/julian/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/julian/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/julian/Documents/Arduino/libraries -fqbn=RFduino:RFduino:RFduino -ide-version=10805 -build-path /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200 -warnings=none -build-cache /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_cache_722169 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arm-none-eabi-gcc.path=/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1 -verbose /Users/julian/Code/openSleep/embedded/sleepduino/sleepduino.ino
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/julian/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/julian/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/julian/Documents/Arduino/libraries -fqbn=RFduino:RFduino:RFduino -ide-version=10805 -build-path /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200 -warnings=none -build-cache /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_cache_722169 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arm-none-eabi-gcc.path=/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1 -verbose /Users/julian/Code/openSleep/embedded/sleepduino/sleepduino.ino
Using board 'RFduino' from platform in folder: /Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3
Using core 'arduino' from platform in folder: /Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3
Detecting libraries used...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/dev/null"
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/dev/null"
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE/RFduinoBLE.cpp" -o "/dev/null"
Generating function prototypes...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/preproc/ctags_target_for_gcc_minus_e.cpp"
"/Applications/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/preproc/ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin -MMD -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp.o"
Compiling libraries...
Compiling library "RFduinoBLE"
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin -MMD -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE/RFduinoBLE.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/libraries/RFduinoBLE/RFduinoBLE.cpp.o"
Compiling core...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin -MMD -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/variant.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/variant.cpp.o"
Using precompiled core
Linking everything together...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -Wl,--gc-sections --specs=nano.specs -mcpu=cortex-m0 -mthumb -D__RFduino__ "-T/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/linker_scripts/gcc/RFduino.ld" "-Wl,-Map,/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sleepduino.ino.map" -Wl,--cref -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sleepduino.ino.elf" "-L/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200" -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/syscalls.c.o" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp.o" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/libraries/RFduinoBLE/RFduinoBLE.cpp.o" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/variant.cpp.o" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduinoSystem.a" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduino.a" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduinoBLE.a" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduinoGZLL.a" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/../arduino_cache_722169/core/core_RFduino_RFduino_RFduino_96c93913732efe419124a59ff97a44c7.a" -Wl,--end-group
arm-none-eabi-g++: error: /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/syscalls.c.o: No such file or directory
Using library RFduinoBLE in folder: /Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE (legacy)
exit status 1
Error compiling for board RFduino.

```

# Answer
> 1 votes
So it appears solved: Using Arduino 1.6.13 I don't get the compile error. Must be an incompatibility with the RFduino Board libraries and the 1.8x IDE.

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


title: How to create "Auto switch case"

text:
# Question
Title: How to create "Auto switch case"
I am new to programming. I want to modify this sketch and I really need help. I have a switch case in this sketch, and what I want is an auto change effect.

In this sketch 18 color effects for WS2812B led strip. To change effects you have to press ta button. How do I make it change effect automatically, for example 8-10 seconds. I don't know how to do this. So please help me, huge thanks!

```
#include "FastLED.h"
#include <EEPROM.h>
#define NUM_LEDS 60
CRGB leds[NUM_LEDS];
#define PIN 6

#define BUTTON 2
byte selectedEffect=0;

void setup()
{
  FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  digitalWrite (BUTTON, HIGH);  // internal pull-up resistor
  attachInterrupt (digitalPinToInterrupt (BUTTON), changeEffect, CHANGE); // pressed
}

// *** REPLACE FROM HERE ***
void loop() {
  EEPROM.get(0,selectedEffect);
  if(selectedEffect>18) {
    selectedEffect=0;
    EEPROM.put(0,0);
  }

  switch(selectedEffect) {

    case 0  : {
                // RGBLoop - no parameters
                RGBLoop();
                break;
              }

    case 1  : {
                // FadeInOut - Color (red, green. blue)
                FadeInOut(0xff, 0x00, 0x00); // red
                FadeInOut(0xff, 0xff, 0xff); // white
                FadeInOut(0x00, 0x00, 0xff); // blue
                break;
              }

    case 2  : {
                // Strobe - Color (red, green, blue), number of flashes, flash speed, end pause
                Strobe(0xff, 0xff, 0xff, 10, 50, 1000);
                break;
              }

    case 3  : {
                // HalloweenEyes - Color (red, green, blue), Size of eye, space between eyes, fade (true/false), steps, fade delay, end pause
                HalloweenEyes(0xff, 0x00, 0x00,
                              1, 4,
                              true, random(5,50), random(50,150),
                              random(1000, 10000));
                HalloweenEyes(0xff, 0x00, 0x00,
                              1, 4,
                              true, random(5,50), random(50,150),
                              random(1000, 10000));
                break;
              }

    case 4  : {
                // CylonBounce - Color (red, green, blue), eye size, speed delay, end pause
                CylonBounce(0xff, 0x00, 0x00, 4, 10, 50);
                break;
              }

    case 5  : {
                // NewKITT - Color (red, green, blue), eye size, speed delay, end pause
                NewKITT(0xff, 0x00, 0x00, 8, 10, 50);
                break;
              }

    case 6  : {
                // Twinkle - Color (red, green, blue), count, speed delay, only one twinkle (true/false)
                Twinkle(0xff, 0x00, 0x00, 10, 100, false);
                break;
              }

    case 7  : {
                // TwinkleRandom - twinkle count, speed delay, only one (true/false)
                TwinkleRandom(20, 100, false);
                break;
              }

    case 8  : {
                // Sparkle - Color (red, green, blue), speed delay
                Sparkle(0xff, 0xff, 0xff, 0);
                break;
              }

    case 9  : {
                // SnowSparkle - Color (red, green, blue), sparkle delay, speed delay
                SnowSparkle(0x10, 0x10, 0x10, 20, random(100,1000));
                break;
              }

    case 10 : {
                // Running Lights - Color (red, green, blue), wave dealy
                RunningLights(0xff,0x00,0x00, 50);  // red
                RunningLights(0xff,0xff,0xff, 50);  // white
                RunningLights(0x00,0x00,0xff, 50);  // blue
                break;
              }

    case 11 : {
                // colorWipe - Color (red, green, blue), speed delay
                colorWipe(0x00,0xff,0x00, 50);
                colorWipe(0x00,0x00,0x00, 50);
                break;
              }

    case 12 : {
                // rainbowCycle - speed delay
                rainbowCycle(20);
                break;
              }

    case 13 : {
                // theatherChase - Color (red, green, blue), speed delay
                theaterChase(0xff,0,0,50);
                break;
              }

    case 14 : {
                // theaterChaseRainbow - Speed delay
                theaterChaseRainbow(50);
                break;
              }

    case 15 : {
                // Fire - Cooling rate, Sparking rate, speed delay
                Fire(55,120,15);
                break;
              }

              // simple bouncingBalls not included, since BouncingColoredBalls can perform this as well as shown below
              // BouncingColoredBalls - Number of balls, color (red, green, blue) array, continuous
              // CAUTION: If set to continuous then this effect will never stop!!!

    case 16 : {
                // mimic BouncingBalls
                byte onecolor[1][3] = { {0xff, 0x00, 0x00} };
                BouncingColoredBalls(1, onecolor, false);
                break;
              }

    case 17 : {
                // multiple colored balls
                byte colors[3][3] = { {0xff, 0x00, 0x00},
                                      {0xff, 0xff, 0xff},
                                      {0x00, 0x00, 0xff} };
                BouncingColoredBalls(3, colors, false);
                break;
              }

    case 18 : {
                // meteorRain - Color (red, green, blue), meteor size, trail decay, random trail decay (true/false), speed delay
                meteorRain(0xff,0xff,0xff,10, 64, true, 30);
                break;
              }
  }
}

void changeEffect() {
  if (digitalRead (BUTTON) == HIGH) {
    selectedEffect++;
    EEPROM.put(0, selectedEffect);
    asm volatile ("  jmp 0");
  }
}

// *************************
// ** LEDEffect Functions **
// *************************

void RGBLoop(){
  for(int j = 0; j < 3; j++ ) {
    // Fade IN
    for(int k = 0; k < 256; k++) {
      switch(j) {
        case 0: setAll(k,0,0); break;
        case 1: setAll(0,k,0); break;
        case 2: setAll(0,0,k); break;
      }
      showStrip();
      delay(3);
    }
    // Fade OUT
    for(int k = 255; k >= 0; k--) {
      switch(j) {
        case 0: setAll(k,0,0); break;
        case 1: setAll(0,k,0); break;
        case 2: setAll(0,0,k); break;
      }
      showStrip();
      delay(3);
    }
  }
}

void FadeInOut(byte red, byte green, byte blue){
  float r, g, b;

  for(int k = 0; k < 256; k=k+1) {
    r = (k/256.0)*red;
    g = (k/256.0)*green;
    b = (k/256.0)*blue;
    setAll(r,g,b);
    showStrip();
  }

  for(int k = 255; k >= 0; k=k-2) {
    r = (k/256.0)*red;
    g = (k/256.0)*green;
    b = (k/256.0)*blue;
    setAll(r,g,b);
    showStrip();
  }
}

void Strobe(byte red, byte green, byte blue, int StrobeCount, int FlashDelay, int EndPause){
  for(int j = 0; j < StrobeCount; j++) {
    setAll(red,green,blue);
    showStrip();
    delay(FlashDelay);
    setAll(0,0,0);
    showStrip();
    delay(FlashDelay);
  }

 delay(EndPause);
}

void HalloweenEyes(byte red, byte green, byte blue,
                   int EyeWidth, int EyeSpace,
                   boolean Fade, int Steps, int FadeDelay,
                   int EndPause){
  randomSeed(analogRead(0));

  int i;
  int StartPoint  = random( 0, NUM_LEDS - (2*EyeWidth) - EyeSpace );
  int Start2ndEye = StartPoint + EyeWidth + EyeSpace;

  for(i = 0; i < EyeWidth; i++) {
    setPixel(StartPoint + i, red, green, blue);
    setPixel(Start2ndEye + i, red, green, blue);
  }

  showStrip();

  if(Fade==true) {
    float r, g, b;

    for(int j = Steps; j >= 0; j--) {
      r = j*(red/Steps);
      g = j*(green/Steps);
      b = j*(blue/Steps);

      for(i = 0; i < EyeWidth; i++) {
        setPixel(StartPoint + i, r, g, b);
        setPixel(Start2ndEye + i, r, g, b);
      }

      showStrip();
      delay(FadeDelay);
    }
  }

  setAll(0,0,0); // Set all black

  delay(EndPause);
}

void CylonBounce(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay){

  for(int i = 0; i < NUM_LEDS-EyeSize-2; i++) {
    setAll(0,0,0);
    setPixel(i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(i+j, red, green, blue);
    }
    setPixel(i+EyeSize+1, red/10, green/10, blue/10);
    showStrip();
    delay(SpeedDelay);
  }

  delay(ReturnDelay);

  for(int i = NUM_LEDS-EyeSize-2; i > 0; i--) {
    setAll(0,0,0);
    setPixel(i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(i+j, red, green, blue);
    }
    setPixel(i+EyeSize+1, red/10, green/10, blue/10);
    showStrip();
    delay(SpeedDelay);
  }

  delay(ReturnDelay);
}

void NewKITT(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay){
  RightToLeft(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
  LeftToRight(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
  OutsideToCenter(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
  CenterToOutside(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
  LeftToRight(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
  RightToLeft(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
  OutsideToCenter(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
  CenterToOutside(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
}

// used by NewKITT
void CenterToOutside(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
  for(int i =((NUM_LEDS-EyeSize)/2); i>=0; i--) {
    setAll(0,0,0);

    setPixel(i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(i+j, red, green, blue);
    }
    setPixel(i+EyeSize+1, red/10, green/10, blue/10);

    setPixel(NUM_LEDS-i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(NUM_LEDS-i-j, red, green, blue);
    }
    setPixel(NUM_LEDS-i-EyeSize-1, red/10, green/10, blue/10);

    showStrip();
    delay(SpeedDelay);
  }
  delay(ReturnDelay);
}

// used by NewKITT
void OutsideToCenter(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
  for(int i = 0; i<=((NUM_LEDS-EyeSize)/2); i++) {
    setAll(0,0,0);

    setPixel(i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(i+j, red, green, blue);
    }
    setPixel(i+EyeSize+1, red/10, green/10, blue/10);

    setPixel(NUM_LEDS-i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(NUM_LEDS-i-j, red, green, blue);
    }
    setPixel(NUM_LEDS-i-EyeSize-1, red/10, green/10, blue/10);

    showStrip();
    delay(SpeedDelay);
  }
  delay(ReturnDelay);
}

// used by NewKITT
void LeftToRight(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
  for(int i = 0; i < NUM_LEDS-EyeSize-2; i++) {
    setAll(0,0,0);
    setPixel(i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(i+j, red, green, blue);
    }
    setPixel(i+EyeSize+1, red/10, green/10, blue/10);
    showStrip();
    delay(SpeedDelay);
  }
  delay(ReturnDelay);
}

// used by NewKITT
void RightToLeft(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
  for(int i = NUM_LEDS-EyeSize-2; i > 0; i--) {
    setAll(0,0,0);
    setPixel(i, red/10, green/10, blue/10);
    for(int j = 1; j <= EyeSize; j++) {
      setPixel(i+j, red, green, blue);
    }
    setPixel(i+EyeSize+1, red/10, green/10, blue/10);
    showStrip();
    delay(SpeedDelay);
  }
  delay(ReturnDelay);
}

void Twinkle(byte red, byte green, byte blue, int Count, int SpeedDelay, boolean OnlyOne) {
  setAll(0,0,0);

  for (int i=0; i<Count; i++) {
     setPixel(random(NUM_LEDS),red,green,blue);
     showStrip();
     delay(SpeedDelay);
     if(OnlyOne) {
       setAll(0,0,0);
     }
   }

  delay(SpeedDelay);
}

void TwinkleRandom(int Count, int SpeedDelay, boolean OnlyOne) {
  setAll(0,0,0);

  for (int i=0; i<Count; i++) {
     setPixel(random(NUM_LEDS),random(0,255),random(0,255),random(0,255));
     showStrip();
     delay(SpeedDelay);
     if(OnlyOne) {
       setAll(0,0,0);
     }
   }

  delay(SpeedDelay);
}

void Sparkle(byte red, byte green, byte blue, int SpeedDelay) {
  int Pixel = random(NUM_LEDS);
  setPixel(Pixel,red,green,blue);
  showStrip();
  delay(SpeedDelay);
  setPixel(Pixel,0,0,0);
}

void SnowSparkle(byte red, byte green, byte blue, int SparkleDelay, int SpeedDelay) {
  setAll(red,green,blue);

  int Pixel = random(NUM_LEDS);
  setPixel(Pixel,0xff,0xff,0xff);
  showStrip();
  delay(SparkleDelay);
  setPixel(Pixel,red,green,blue);
  showStrip();
  delay(SpeedDelay);
}

void RunningLights(byte red, byte green, byte blue, int WaveDelay) {
  int Position=0;

  for(int i=0; i<NUM_LEDS*2; i++)
  {
      Position++; // = 0; //Position + Rate;
      for(int i=0; i<NUM_LEDS; i++) {
        // sine wave, 3 offset waves make a rainbow!
        //float level = sin(i+Position) * 127 + 128;
        //setPixel(i,level,0,0);
        //float level = sin(i+Position) * 127 + 128;
        setPixel(i,((sin(i+Position) * 127 + 128)/255)*red,
                   ((sin(i+Position) * 127 + 128)/255)*green,
                   ((sin(i+Position) * 127 + 128)/255)*blue);
      }

      showStrip();
      delay(WaveDelay);
  }
}

void colorWipe(byte red, byte green, byte blue, int SpeedDelay) {
  for(uint16_t i=0; i<NUM_LEDS; i++) {
      setPixel(i, red, green, blue);
      showStrip();
      delay(SpeedDelay);
  }
}

void rainbowCycle(int SpeedDelay) {
  byte *c;
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< NUM_LEDS; i++) {
      c=Wheel(((i * 256 / NUM_LEDS) + j) & 255);
      setPixel(i, *c, *(c+1), *(c+2));
    }
    showStrip();
    delay(SpeedDelay);
  }
}

// used by rainbowCycle and theaterChaseRainbow
byte * Wheel(byte WheelPos) {
  static byte c[3];

  if(WheelPos < 85) {
   c[0]=WheelPos * 3;
   c[1]=255 - WheelPos * 3;
   c[2]=0;
  } else if(WheelPos < 170) {
   WheelPos -= 85;
   c[0]=255 - WheelPos * 3;
   c[1]=0;
   c[2]=WheelPos * 3;
  } else {
   WheelPos -= 170;
   c[0]=0;
   c[1]=WheelPos * 3;
   c[2]=255 - WheelPos * 3;
  }

  return c;
}

void theaterChase(byte red, byte green, byte blue, int SpeedDelay) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < NUM_LEDS; i=i+3) {
        setPixel(i+q, red, green, blue);    //turn every third pixel on
      }
      showStrip();

      delay(SpeedDelay);

      for (int i=0; i < NUM_LEDS; i=i+3) {
        setPixel(i+q, 0,0,0);        //turn every third pixel off
      }
    }
  }
}

void theaterChaseRainbow(int SpeedDelay) {
  byte *c;

  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
        for (int i=0; i < NUM_LEDS; i=i+3) {
          c = Wheel( (i+j) % 255);
          setPixel(i+q, *c, *(c+1), *(c+2));    //turn every third pixel on
        }
        showStrip();

        delay(SpeedDelay);

        for (int i=0; i < NUM_LEDS; i=i+3) {
          setPixel(i+q, 0,0,0);        //turn every third pixel off
        }
    }
  }
}

void Fire(int Cooling, int Sparking, int SpeedDelay) {
  static byte heat[NUM_LEDS];
  int cooldown;

  // Step 1.  Cool down every cell a little
  for( int i = 0; i < NUM_LEDS; i++) {
    cooldown = random(0, ((Cooling * 10) / NUM_LEDS) + 2);

    if(cooldown>heat[i]) {
      heat[i]=0;
    } else {
      heat[i]=heat[i]-cooldown;
    }
  }

  // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  for( int k= NUM_LEDS - 1; k >= 2; k--) {
    heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3;
  }

  // Step 3.  Randomly ignite new 'sparks' near the bottom
  if( random(255) < Sparking ) {
    int y = random(7);
    heat[y] = heat[y] + random(160,255);
    //heat[y] = random(160,255);
  }

  // Step 4.  Convert heat to LED colors
  for( int j = 0; j < NUM_LEDS; j++) {
    setPixelHeatColor(j, heat[j] );
  }

  showStrip();
  delay(SpeedDelay);
}

void setPixelHeatColor (int Pixel, byte temperature) {
  // Scale 'heat' down from 0-255 to 0-191
  byte t192 = round((temperature/255.0)*191);

  // calculate ramp up from
  byte heatramp = t192 & 0x3F; // 0..63
  heatramp <<= 2; // scale up to 0..252

  // figure out which third of the spectrum we're in:
  if( t192 > 0x80) {                     // hottest
    setPixel(Pixel, 255, 255, heatramp);
  } else if( t192 > 0x40 ) {             // middle
    setPixel(Pixel, 255, heatramp, 0);
  } else {                               // coolest
    setPixel(Pixel, heatramp, 0, 0);
  }
}

void BouncingColoredBalls(int BallCount, byte colors[][3], boolean continuous) {
  float Gravity = -9.81;
  int StartHeight = 1;

  float Height[BallCount];
  float ImpactVelocityStart = sqrt( -2 * Gravity * StartHeight );
  float ImpactVelocity[BallCount];
  float TimeSinceLastBounce[BallCount];
  int   Position[BallCount];
  long  ClockTimeSinceLastBounce[BallCount];
  float Dampening[BallCount];
  boolean ballBouncing[BallCount];
  boolean ballsStillBouncing = true;

  for (int i = 0 ; i < BallCount ; i++) {
    ClockTimeSinceLastBounce[i] = millis();
    Height[i] = StartHeight;
    Position[i] = 0;
    ImpactVelocity[i] = ImpactVelocityStart;
    TimeSinceLastBounce[i] = 0;
    Dampening[i] = 0.90 - float(i)/pow(BallCount,2);
    ballBouncing[i]=true;
  }

  while (ballsStillBouncing) {
    for (int i = 0 ; i < BallCount ; i++) {
      TimeSinceLastBounce[i] =  millis() - ClockTimeSinceLastBounce[i];
      Height[i] = 0.5 * Gravity * pow( TimeSinceLastBounce[i]/1000 , 2.0 ) + ImpactVelocity[i] * TimeSinceLastBounce[i]/1000;

      if ( Height[i] < 0 ) {
        Height[i] = 0;
        ImpactVelocity[i] = Dampening[i] * ImpactVelocity[i];
        ClockTimeSinceLastBounce[i] = millis();

        if ( ImpactVelocity[i] < 0.01 ) {
          if (continuous) {
            ImpactVelocity[i] = ImpactVelocityStart;
          } else {
            ballBouncing[i]=false;
          }
        }
      }
      Position[i] = round( Height[i] * (NUM_LEDS - 1) / StartHeight);
    }

    ballsStillBouncing = false; // assume no balls bouncing
    for (int i = 0 ; i < BallCount ; i++) {
      setPixel(Position[i],colors[i][0],colors[i][1],colors[i][2]);
      if ( ballBouncing[i] ) {
        ballsStillBouncing = true;
      }
    }

    showStrip();
    setAll(0,0,0);
  }
}

void meteorRain(byte red, byte green, byte blue, byte meteorSize, byte meteorTrailDecay, boolean meteorRandomDecay, int SpeedDelay) {
  setAll(0,0,0);

  for(int i = 0; i < NUM_LEDS+NUM_LEDS; i++) {

    // fade brightness all LEDs one step
    for(int j=0; j<NUM_LEDS; j++) {
      if( (!meteorRandomDecay) || (random(10)>5) ) {
        fadeToBlack(j, meteorTrailDecay );
      }
    }

    // draw meteor
    for(int j = 0; j < meteorSize; j++) {
      if( ( i-j <NUM_LEDS) && (i-j>=0) ) {
        setPixel(i-j, red, green, blue);
      }
    }

    showStrip();
    delay(SpeedDelay);
  }
}

// used by meteorrain
void fadeToBlack(int ledNo, byte fadeValue) {
 #ifdef ADAFRUIT_NEOPIXEL_H
    // NeoPixel
    uint32_t oldColor;
    uint8_t r, g, b;
    int value;

    oldColor = strip.getPixelColor(ledNo);
    r = (oldColor & 0x00ff0000UL) >> 16;
    g = (oldColor & 0x0000ff00UL) >> 8;
    b = (oldColor & 0x000000ffUL);

    r=(r<=10)? 0 : (int) r-(r*fadeValue/256);
    g=(g<=10)? 0 : (int) g-(g*fadeValue/256);
    b=(b<=10)? 0 : (int) b-(b*fadeValue/256);

    strip.setPixelColor(ledNo, r,g,b);
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   leds[ledNo].fadeToBlackBy( fadeValue );
 #endif
}

// *** REPLACE TO HERE ***

// ***************************************
// ** FastLed/NeoPixel Common Functions **
// ***************************************

// Apply LED color changes
void showStrip() {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.show();
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   FastLED.show();
 #endif
}

// Set a LED color (not yet visible)
void setPixel(int Pixel, byte red, byte green, byte blue) {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.setPixelColor(Pixel, strip.Color(red, green, blue));
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
 #endif
}

// Set all LEDs to a given color and apply it (visible)
void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  showStrip();
}

```

# Answer
use millis to check

```
static unsigned long lastChange = millis();
if(auto_changing && millis()-lastChange  > 10*1000){
    selectedEffect++;
    EEPROM.put(0,selectedEffect);
    lastChange = millis();
}

```

Put this before the `if(selectedEffect>18)` and it will cycle each effect for at least 10 seconds before going to the next effect.

---

BTW I suggest that you rejig your code like blinkWithoutDelay so you don't need to use interrupts the flash memory and `jmp 0` and can instead avoid that.

It'll require quite a bit of refactoring though but will allow you to fade from one effect to the next smoothly.
> 1 votes

---
Tags: timers, switch
---


# Question
Title: GSM cannot read SMS when Arduino is not reset for the first time after it is powered
I'm using a GSM Module with Arduino along with Node MCU. I have a supply of 9V, 2A in the DC jack of the Arduino and the GSM Shield. The Node MCU is powered from the 3.3V of the Arduino. I can receive messages fine in the GSM when the USB port of the Arduino (including the power supply I mentioned earlier) is connected to the laptop through and monitored using the serial monitor. However if I remove the USB port, the GSM cannot receive the messages anymore but when I press the reset button of the Arduino, it will start receiving messages again. Why does it only works when I reset the Arduino first after powering it up?

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

SoftwareSerial gsmSerial(2, 3);

char incomingByte;
String inputString;

// Pin configurations.

const int outlet1Pin = 4;
const int outlet2Pin = 5;
const int outlet3Pin = 6;

const int ping1Pin = 7;
const int ping2Pin = 8;
const int ping3Pin = 9;
const int ping4Pin = 10;
const int ping5Pin = 11;
const int ping6Pin = 12;
const int signalPin = 13;

const int pingWaitTime = 3000;

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

  pinMode(outlet1Pin, INPUT);
  pinMode(outlet2Pin, INPUT);
  pinMode(outlet3Pin, INPUT);

  pinMode(ping1Pin, OUTPUT);
  pinMode(ping2Pin, OUTPUT);
  pinMode(ping3Pin, OUTPUT);
  pinMode(ping4Pin, OUTPUT);
  pinMode(ping5Pin, OUTPUT);
  pinMode(ping6Pin, OUTPUT);
  pinMode(signalPin, OUTPUT);

  initGSM();
  //Serial.flush();
  //gsmSerial.flush();
  //sendSMS("Test send.");

}

void loop()
{
  if (gsmSerial.available())
  {
    digitalWrite(signalPin, HIGH);

    delay(500);

    //Serial.println("Serial available.");

    while (gsmSerial.available())
    {
      incomingByte = gsmSerial.read();
      inputString += incomingByte;
    }

    inputString.toUpperCase();

    checkCommandAction(inputString);

    if (inputString.indexOf("OK") == -1)
    {
      gsmSerial.println("AT+CMGDA=\"DEL ALL\"");
      delay(1000);
    }

    inputString = "";
    gsmSerial.flush();

  }
  digitalWrite(signalPin, LOW);

}

void sendSMS(String text)
{
  Serial.println("Sending Text...");

  gsmSerial.println("AT+CMGF=1");
  delay(1000);

  gsmSerial.print("AT+CMGS=\"+numberhere\"\r");

  delay(1000);

  gsmSerial.print(text);
  delay(1000);

  gsmSerial.print((char)26);
  delay(1000);

  gsmSerial.println();
  Serial.println("Message sent!");
  delay(1000);
}

void initGSM()
{
  gsmSerial.println("ATE0");
  while (!gsmSerial.available())
  {
    gsmSerial.println("AT");
    delay(500);
    Serial.println("Connecting...");
  }

  Serial.println("Connected!");

  gsmSerial.println("AT+CMGF=1");
  delay(500);
  gsmSerial.println("AT+CNMI=1,2,0,0,0");
  delay(500);
  gsmSerial.println("AT+CMGL=\"REC UNREAD\"");
  delay(500);
  gsmSerial.println("AT+CMGDA=\"DEL ALL\"");
  delay(500);

  Serial.println("All messages deleted!");

  Serial.println("Sending Text...");

  gsmSerial.println("AT+CMGF=1");
  delay(500);

  gsmSerial.print("AT+CMGS=\"+639776811077\"\r");

  delay(500);

  gsmSerial.print("Device Initialized!");
  delay(500);

  gsmSerial.print((char)26);
  delay(500);

  gsmSerial.println();

  Serial.println("Message sent!");
  delay(500);
}

void checkCommandAction(String command)
{

  //Serial.println("Check Command.");

  if (command.indexOf("O1ON") > -1)
  {

    digitalWrite(ping1Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping1Pin, !HIGH);
    Serial.println("O1ON Enter");
    sendSMS("Outlet 1 Turned ON by text.");

  }
  else if (command.indexOf("O1OFF") > -1)
  {
    digitalWrite(ping4Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping4Pin, !HIGH);
    Serial.println("O1OFF");
    sendSMS("Outlet 1 Turned OFF by text.");
  }
  else if (command.indexOf("O2ON") > -1)
  {
    digitalWrite(ping2Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping2Pin, !HIGH);
    Serial.println("O2ON");
    sendSMS("Outlet 2 Turned ON by text.");
  }
  else if (command.indexOf("O2OFF") > -1)
  {
    digitalWrite(ping5Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping5Pin, !HIGH);
    Serial.println("O2OFF");
    sendSMS("Outlet 2 Turned OFF by text.");
  }
  else if (command.indexOf("O3ON") > -1)
  {
    digitalWrite(ping3Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping3Pin, !HIGH);
    Serial.println("O3ON");
    sendSMS("Outlet 3 Turned ON by text.");

  }
  else if (command.indexOf("O3OFF") > -1)
  {
    digitalWrite(ping6Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping6Pin, !HIGH);
    Serial.println("O1OFF");
    sendSMS("Outlet 3 Turned OFF by text.");
  }
  else if (command.indexOf("CHECKSTATE") > -1)
  {
    int state1 = !digitalRead(outlet1Pin);
    int state2 = !digitalRead(outlet2Pin);
    int state3 = !digitalRead(outlet3Pin);

    String toSend = "";
    toSend += "Outlet 1: ";
    toSend += String((state1) ? ("ON") : ("OFF"));
    toSend += "Outlet 2: ";
    toSend += String((state2) ? ("ON") : ("OFF"));
    toSend += "Outlet 3: ";
    toSend += String((state3) ? ("ON") : ("OFF"));

    sendSMS(toSend);
  }
}

void turnPingsOn()
{
  // The pins where the pings are connected are
  // configures as INPUT_PULL up, so we need to high
  // it by default.

  digitalWrite(ping1Pin, HIGH);
  digitalWrite(ping2Pin, HIGH);
  digitalWrite(ping3Pin, HIGH);
  digitalWrite(ping4Pin, HIGH);
  digitalWrite(ping5Pin, HIGH);
  digitalWrite(ping6Pin, HIGH);
}

```

# Answer
In theory you shouldn't rely on the 3.3V supply of the Arduino to power the NodeMCU board, it doesn't have enough power particularly when WIFI data is being transmitted.

Are you removing the USB while the system is live? If so you are probably spiking various bits that don't like being spiked and that's why it breaks.

If you are removing the USB and THEN powering up the system, what happened when you power down you system and power it back up again after 10 seconds? My guess is that it won't receive messages. So there is a difference between applying power and resetting the board, which implies that you are very marginal on your power supply.

If you are using the SIM800 (?) module they need 2Amps to transmit, so if you are only supplying 2A it might not have enough power to cold start, but when reset it does. So if you can try more power that might help.

Another thought might be you haven't got a proper ground (wall warts aren't normally grounded) so your USB connection is acting as a ground. If this is the case then it should work when you PC is turned off.

Sorry this is a bit vague, but your question needs model names and part number for people to be a bit more specific.
> 1 votes

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


# Question
Title: Can i use a range in a switchcase like in pascal?
in pascal's case statement i can use this:

```
Var i : integer;
...
Case i of
 1..5 : DoSomething;
end;

```

i was wondering if there is a way in can do this with c/c++ in the arduino compiler using:

```
switch (var) {
   case 1..5:
     // statements
     break;

```

or is this only possible using if/else?

# Answer
Short answer: No

Longer answer: Each case in a switch statement must be a discrete value (which is why floats and doubles won't work either) but there are way around it. In order of preference:

A) Utilise the "drop through" feature

```
switch (value)
{
  case 1: // Deliberate drop through
  case 2: // Deliberate drop through
  case 3: // Deliberate drop through
  case 4: // Deliberate drop through
  case 5:
    DoThingA();
    break;
  case 6:
    DoThingB();
    break;
}

```

B) Change the logic so the range is the default (not nice, but if you have no other option):

```
switch (value)
{
  case 6:
    DoThingB();
    break;
  default:
    DoThingA();
    break;
}

```

C) Use a helper function (Really ugly, but...). There would have to be a good reason not to call the DoThing() from the helper function.

```
enum DoOptions {EOptionA, EOptionB};
DoOptions DoWhat (int value)
{
  if (value < 6) return EOptionA;
  return EOptionB;
}
switch (DoWhat(value))
{
  case EOptionA:
    DoThingA();
    break;
  case EOptionB:
    DoThingB();
    break;
}

```
> 2 votes

# Answer
There are some GNU extensions available in the avr-gcc/avr-g++ compilers (used in Arduino IDE for AVR based Arduino boards). One of them is suport of `...` for the `case`:

```
  switch (i)
  {
    case  10 ... 100:  Serial.println(F("First"));           break;
    case 101 ... 1000: Serial.println(F("Second"));          break;
    default:           Serial.println(F("Everything else")); break;
  }

```

But, it's not the part of C/C++ standard, it's just compiler extension, so there is possibility it fails to compile on different platforms (mainly different compiler). So it's better to avoid it in portable code.
> 4 votes

---
Tags: c++, c, switch
---


title: won't verify a simple code

text:
# Question
Title: won't verify a simple code
When I tried to verify a simple “Hello world” program I get the following message:

```
class hardwareSerial has no member named printin.

```

What does it mean?

# Answer
Try using `println` instead of `printin`. It stands for **print** **l**i**n**e.
> 5 votes

---
Tags: c++
---


# Question
Title: What does it take to compile Linux on Arduino, if at all possible?
Is it possible to run Linux on Arduino? If yes, what steps and limitations need to be considered? If not, what are the limitations that prevent this?

# Answer
Linux is a very complex operating system, but it may be able to fit on an Arduino. Things to consider:

* There is no current AVR port of the source code.
* You would have no graphics, instead access the terminal over UART.
* The filesystem driver would have to be rewritten to access internal flash or an external SD card.
* It would be *extremely* slow! The ATmega328 would run at 16 MHz, or about 20 MHz max (overclocked). Most Linux machines run at a minimum of 400 MHz, and more with graphics.
* You would probably need some extra RAM, probably a good idea to use an ATmega2650 (the one in the Mega), which has 16 times the RAM of the Uno. You could also use a Due (6x as fast as the Uno, more RAM).
* You may have to write special USB drivers for OTG (on the Due) or MAX3421EE (Mega ADK, USB host shield).

In short, it would take *a lot* of time and effort, and probably would be too slow for everyday use. If you really want Arduino Linux, check out the Yún.
> 22 votes

# Answer
It just doesn't have enough RAM. You'd also need to teach it to boot from flash memory, which would involve rewriting the bootloader.

You can instead use an Arduino Yun or a PCDuino; while not "standard" Arduinos these support Arduino shields and run Linux.

Or there's always the Raspberry Pi.
> 18 votes

# Answer
The short answer is no.

Basically, you would need LOTS more ram then even the biggest ATmega has natively.

It *is* theoretically possible to add external hardware, and program the ATmega to emulate a more powerful CPU, and run linux on that. However, on a plain arduino, it is not possible.

It would be much more realistic to run linux on a Arduino Due, which is basically a AT91SAM3X8E CPU. However, you'd still need to add some additional SRAM and storage.

There are things like the Arduino Yun, but that is really a entirely separate linux module on the same PCB as a ATmega32U4, so I don't know if you can really count it as an arduino.

---

Possibly relevant: What does it take to run embedded linux?
> 6 votes

# Answer
There is a board called the pcDuino that can run multiple variants of Linux such as Debian, Ubuntu, Open WRT, LEDE, Raspian PIXEL (just to mention a few). This board is not a native Arduino, rather Arduino AtHeart, and is made by LinkSprite.

Arduino have a couple of boards that support running a variant of Linux called Linino:

* The Arduino Yún is a microcontroller board based on the ATmega32u4 and the Atheros AR9331. The Atheros processor supports a Linux distribution based on OpenWrt named Linino OS. The board has built-in Ethernet and WiFi support, a USB-A port, micro-SD card slot, 20 digital input/output pins (7 of them can be used as PWM outputs and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP header, and 3 reset buttons.
* The new Arduino Tian board is powered by Atmel’s SAMD21 MCU, featuring a 32-bit ARM Cortex® M0+ core and a Qualcomm Atheros AR9342, which is an highly integrated MIPS processor operating at up to 533MHz and feature-rich IEEE802.11n 2x2 2.4/5 GHz dual-band WiFi module. Qualcomm Atheros MIPS supports a Linux distribution, based on OpenWRT named Linino. The Arduino Tian has also a build in 4GB eMMC memory that will can be helpful to build your projects. It is possible to Switch ON/OFF the Linux port from the MCU to reduce the power consumption.
* Arduino Industrial 101 is an Evaluation board for Arduino 101 LGA module. The ATmega32u4 microcontroller is integrated in the baseboard. The module supports a Linux distribution based on OpenWRT named LininoOS. The board has built-in WiFi (IEEE 802.11b/g/n operations up to 150Mbps 1x1 2.4 GHz), 3 GPIOs (of which 2 can be used as PWM Outputs), 4 Analog Inputs, 1 USB, 1 Ethernet signal on pin headers and a built-in DC/DC converter. Check out the assembling guide and simply connect your board to a computer with a micro USB cable to get started.
> 2 votes

# Answer
This is several years old, but maybe more pertinent as Arduinos get more RAM and 32 bit ATMega AVRs, etc. There's an obvious problem notably not in the most popular answer here. The Arduino uses an AVR ***MICROCONTROLLER***, not a MICROPROCESSOR. This is a major reason why there is no port of linux. Microcontrollers are designed to perform a specific task, applications where the relationship of input and output is well defined. Microprocessors are designed to run a variety of apps on operating systems. Remember, from the beginning, Linux needed a memory management unit and could not run on 8088 or 286 PCs. Then there was μClinux, which originally targeted the Motorola DragonBall family of embedded 68k processors, for Palm Pilots. It was never particularly successful. You might have more success porting FreeDOS or even Minix than Linux, maybe something in assembler, but compiling an OS on a microcontroller is very impractical. Perhaps it's a challenging academic problem, but specifically counter to the purpose of using a microcontroller instead of a microprocessor.
> 0 votes

---
Tags: linux
---


# Question
Title: CH340 Nano avrdude: stk500_getsync() not in sync resp=0xa4
I'm trying to upload some code to an non-arduino nano with the CH340G chip, and the avrdude refuses to let me upload. The error I'm getting is:

```
Using Port                    : COM4
Using Programmer              : arduino
Overriding Baud Rate          : 115200

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

avrdude done.  Thank you.

```

I've tried installing the drivers for the CH340 chip following this guide but have had no luck. I've also tried uploading to my arduino uno and my arduino micro (both are arduino brand) with no problems. I'm running Windows 10, Arduino IDE 1.8.5

Any ideas?

# Answer
> 17 votes
Arduino has recently changed to using a different bootloader on their official Nano boards that communicates at 115200 baud rather than the previous 57600 baud. Support for these new boards was added in Arduino AVR Boards 1.6.21. The new Nano board definition is not compatible with old Nanos and likely most 3rd party Nanos so backwards compatibility is provided via the **Tools \> Processor \> ATmega328P (Old Bootloader)** menu selection.

---
Tags: uploading, windows, ch340
---


# Question
Title: Arduino or Raspberry? Self Balancing robot
Here's another one, as you probably have seen before.

I'm finishing college, and I'd like, base of my subscription to be a self balancing robot that can send data to a screen. What kind of data? I am in the brain-storming zone with this question and so far I have:

* Distance to other objects
* Time, temperature, direction N-S-W-E, pressure (as in a car where you measure oil temp, tire pressure etc)
* State of balance (as on y axix, a point going from -y to y where 0 is the balance point)
* Any othet possible inte-\[deleted\]-resting thing you could get as a response from a little two-wheels robot
* Remote control via wireless preferably

Now, the big question. Is arduino the best choice, or should I consider Raspberry Pi?

Thanks in advance!

# Answer
This depends on the type of screen you want to interface. An Arduino UNO can with big effort interface a VGA signal with very low resolution and only few colors. Better are little screens (like small OLED screens or small LCD displays with integrated controller). Using a more capable Arduino (like the Mega) can extent the capabilities of your project. The RaspberryPi has of course big display capabilities (like 1080p over HDMI).

There is also another side to the problem: A self balancing robot needs to control its motors very fast (changing the direction fastly depending in sensor input). A RaspberryPi is in principle a computer, not a microcontroller. Programs in it don't have a garanteed time of execution, so especially under high load the program might have to wait for its turn, effectively destabilizing the robot. For these real time fast applications a simple microcontroller is fitted better.

Since you also want wireless control you might be interested in using an ESP (WLAN) as a microcontroller.

All in all you should use a microcontroller for driving the balancing logic and motor control. Depending in your needs you can either use only this microcontroller to do all the other things too or connect another board as a master (eg over I2C vor SPI) which tells the microcontroller what to do. For this a raspberryPi is good.

If you provide more information about the concrete target capabilities you might get a better answer. The scope of your project is too open for clear answers.
> 1 votes

---
Tags: arduino-uno, sensors, robotics, raspberrypi
---


# Question
Title: Arduino Nano - programmer is not responding
I cannot seem to upload the simple blink program to my Arduino Nano. I keep getting the message:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

```

What I have tried already with a lot of suggestions on Google. **I have tried it on both a Windows 7 & 8 machine and with 2 different Nano's:**

* Set my Board to Arduino Nano
* Set my Processor to ATmega168
* Set my port to COM1
* On windows 8 turned off driver signature
* Installed the FTDI Driver
* Checked my drivers in control panel
    + USB controllers says USB Serial Converter
    + USB Serial port says USB Serial Port (COM1)
* Rebooted a Lot!

When I plugin the nano to the USB it starts blinking the L led 180 times a minute. When I start uploading, L blinks at about 80-100 times a minute, blinks the rx and then start blinking the L led fast again.

# Answer
> 7 votes
For me the problem was the selected "processor" type.

I had to change it to `328p (old bootloader)`.

Also, raise the IDE's verbosity, in order to have a nice progress bar when loading the sketch.

My specs:

* OS: Linux Mint 18.3
* Linux kernel: 4.13.0-37-generic
* Arduino IDE: v1.8.5
* board: the cheap and common Nano Chinese clone
* USB to serial chip: CH340

# Answer
> 1 votes
If it's a new nano is probably the new version which has the 328 processor. Try switching to that.

Also does your computer make the windows "I just plugged something in" sound when you connect? Is the driver recognized?

Try this instead:

Set Board to Arduino Nano Set Processor to ATmega328 Set port to COM2 or any other device if recognized. Test to see if the Com1 stays if you unplug it. Try other usb ports as well.

---
Tags: arduino-nano, programmer
---


# Question
Title: Arduino Switching Between Loops IR Remote
I've been working on an LED strip project. However, I've come to a stand still at the moment. Within the program I am wanting to assign different lighting effects to each button on my IR remote. I am wanting the program to work on the basis that each lighting effect will run, until another button is pressed, to start another effect.

Currently with my code I have made it so each effect will run, once, when the corresponding button on the IR remote is pressed.

I am fairly new to C++ / Arduino but from my understanding I need to have a variable which would hold the current value of the IR remote. I am unsure on how to actually implement this. I will post my code below and if anyone could give me tips or even amendments to my code it would be to a great help.

Thank you in advanced.

```
#include "IRremote.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(20, PIN, NEO_GRB + NEO_KHZ800);

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
int Remote = 0;

/*-----( Function )-----*/
void translateIR() // takes action based on IR code received

// describing Remote IR codes

{
  switch(results.value)
  {
  case 0xFFA25D: Serial.println("POWER");
  ArrowRight(strip.Color(25, 0, 0), 100); //Red
  ArrowRight(strip.Color(0, 0, 25), 100); //Blue
  break;

  case 0xFFE21D: Serial.println("FUNC/STOP");
  ArrowLeft(strip.Color(25, 0, 0), 100); // Red
  ArrowLeft(strip.Color(0, 0, 25), 100); // Blue
  break;

  default:
  Serial.println(" other button   ");

  }// End Case

  delay(0); // Do not get immediate repeat

} //END translateIR
void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  strip.begin();
  strip.show();
  Remote = 0;

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}/* --(end main loop )-- */

void ArrowRight(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 1; j++) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(50);
    }
    for (uint16_t i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(50);
  }
}

void ArrowLeft(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 1; j++) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2-1; i + 1 > 0 ; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(50);
    }
    for (uint16_t i = strip.numPixels(); i + 1 > 0 ; i--) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(50);
  }
}

```

# Answer
> 3 votes
`delay(0)` apparently\[\*\] acts like `delay(2^32)` or about 10^10 milliseconds. That may not be what you had in mind ... :)

Try reducing the delay to 1 or use `delayMicroseconds()` to get something shorter. That should at least get you some repeatable results.

(10^10 mSec is ~ 16.5 weeks, for those without a calculator handy).

\[\*\] I didn't read the code, nor wait for the call to expire. I tried it and saw that the Uno froze. I'm guessing a zero-argument to delay() isn't rejected but just gets decremented as usual, until it hits zero.

# Answer
> 0 votes
> I need to have a variable which would hold the current value of the IR remote.

You already have one. It's called results and is of type decode\_results.

```
decode_results results;

```

You read the IR results into that variable. Then you clear it to look for another one. What you need is a way to store the last good code that you got. Your best bet is to just use an int and store a certain number for each code, store a 1 when you get 0xFFA25D and a 2 when you get 0xFFE21D or something like that. Then use that int instead of the results variable to decide what to do in the rest of the code.

---
Tags: adafruit, ir, remote-control, neopixel, loop
---


title: How to run Arduino code on Linux?

text:
# Question
Title: How to run Arduino code on Linux?
I want to use an MFRC522 module as explained in this video.

But is it possible to get around with Arduino and use a TTL to USB converter to connect RC522 directly to my PC running Ubuntu?

Using the RC222's UART interface, should I rewrite Arduino libraries from scratch for PC or is there a way to easily port the libraries?

# Answer
Arduino libraries rely on the Arduino API to operate (usually). Things like the Serial object are expected to be defined.

Linux doesn't have any of that stuff, so you would have to implement it all yourself.

There is the "Wiring Pi" project for (obviously) the Raspberry Pi that implements the majority of the Arudino API, but whether that could be made to run on Linux on a PC is anyone's guess.

It may be simpler to just examine the existing library (and datasheet) and implement it yourself in your chosen language.
> 1 votes

---
Tags: serial, rfid, uart, linux
---


title: ISP with 115200 baud

text:
# Question
Title: ISP with 115200 baud
I have a serial ISP programmer of protocol type "stk500v1" which expects 115200 baud data rate. I have used it successfully with Atmel Studio by calling avrdude manually (custom tool) in the past. This just involves the avrdude option

> -b 115200

But recently I wanted to do use the Arduino software instead of Atmel Studio for a quick mockup. But everytime I try to "Upload with Programmer", the avrdude commandline includes the option

> -b 19200

and so the programming fails.

I can make it work by changing the hard wired serial rate in the programmer from 115200 to 19200, but then of course the programming is dead slow, which I don't want.

I have also looked for a baudrate entry for stk500v1 in "avrdude.conf", but didn't find any. How can I change the baud rate for "Upload with programmer" in the Arduino software?

# Answer
You have to edit the `programmers.txt` file. (The one in `~/.arduino15/packages/arduino/hardware/avr/1.6.21/`, *not* the one in `arduino-1.8.x/hardware/arduino/avr/`)

```
avrisp.name=AVR ISP
avrisp.communication=serial
avrisp.protocol=stk500v1
avrisp.program.protocol=stk500v1
avrisp.program.speed=115200
avrisp.program.tool=avrdude
avrisp.program.extra_params=-P{serial.port} -b{program.speed}

```

Add a `avrisp.program.speed` option, and pass this option as one of the `extra_params` to the command line call of avrdude.
It is then used on line 112 of `platform.txt`:

```
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} {program.verify} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

```

You could of course also make a copy of that avrisp entry, and add your own programmer, just give it a different name.
> 2 votes

---
Tags: isp
---


# Question
Title: Digital output from one nano to digital input of another.
Can I connect the digital out of one arduino to a digital input of another? To detect a high/low state... One powered in one room on USB. The other in another room separate psu (connecting the grounds). I know I can use tx/rx serial. But if the other way would work, less programming and 1 wire less..

# Answer
Yes, you can. As you noted, you do need to connect the grounds of both Arduinos.

For some extra protection you could put a resistor between the output and the input. For example a 1kOhm. That way, if you accidentally set both pins as outputs, or plug the wire in the incorrect pin, you won’t get a dead-short.
> 1 votes

---
Tags: hardware
---


# Question
Title: how to know the channel i receive information from when i use nRF24L01 to connect between 3 of them
i am using nRF24L01 to connect between 3 of them ( 1 is master and the others are slaves) and i am using nRF24 library , my problem is that when the master receive something from the other slaves and do not know from which channel the infromation come so is there is a way to know from which channel

//master channel code: const byte addresses\[\]\[6\] = {"00001", "00002","00003"}; radio.openWritingPipe(addresses\[1\]); // mastr radio.openReadingPipe(2, addresses\[0\]); // carwl radio.openReadingPipe(2, addresses\[2\]); // carwl2

//slave 1 channel code : const byte addresses\[\]\[6\] = {"00001", "00002","00003"}; radio.openWritingPipe(addresses\[0\]); // carw1 radio.openReadingPipe(2, addresses\[1\]); // mastr

//slave 2 channel code: const byte addresses\[\]\[6\] = {"00001", "00002","00003"}; radio.openWritingPipe(addresses\[0\]); // 00003 radio.openReadingPipe(2, addresses\[2\]); // 00002

library i use: https://github.com/nRF24/RF24

# Answer
You can pass the`RF24.available` function a pointer to a variable. The available function will write the pipe-number of the message to that variable.

An example can be found in the documentation
> 0 votes

# Answer
The nRF24 is highly versatile and can be programmed for a number of different network topologies. It appears you want either

1. One-to-many network - where the master node sends data to the slave nodes
2. Many-to-one network - where the master receives data from many slaves.

Both networks are achieved with the same radio channel (`RF_CH`) on all nodes.

For a one-to-many network you need to have a different RX address for each slave node. Set the master TX address to the RX address of the corresponding slave that you want to receive the data. Done.

For a many-to-one network you are limited to 6 slave nodes. On the master radio you will need to set the addresses of data pipes 0-5 to the slave TX addresses. The master will be listening for data on all pipes and signal an interrupt whenever data is received on any of them.

To achieve bi-directional communication with a (practically) unlimited number of slave nodes, your best bet is to use the in-built ACK PAYLOAD feature of nRF24. In addition to configuring a one-to-many network, you need to enable ACK payload on each radio node. The procedure to follow is given in the nRF24L01 data sheet. I can't recommend strongly enough how important that is to read and learn from. You will be able to send a message from the master to one slave, and get data back from that node in the same radio transmission, auto-retransmit etc included in the bargain. This way you also know which node the data are coming from - without needed to encode the identity of the slave node in the message. It's incredible what these little radios will let you achieve!
> 0 votes

---
Tags: arduino-uno, nrf24l01+
---


# Question
Title: How to store an RFID tag number in a string
I want to send RFID tag number to PHP page. So far I have sent a fixed string to php and it worked, now I am not getting data in string when i scan rfid tag. I want to store every RFID tag number in a string when it is scanned, so that I can send it to php page.

```
if (rfid.isCard()) {

    String rfid_uid = "";
    if (rfid.readCardSerial()) {
        String rfid_uid = "";
        for (int i = 0; i < 4; i++) {
            Serial.print(rfid.serNum[i], HEX);
            rfid_uid = rfid.serNum[i];
        }

        Serial.println();
    }
    //delay(7000);
    Serial.print("User ID \n");
    Serial.println(rfid_uid);
    make_request(rfid_uid);
}

```

This is the path to php page

```
         String method = "GET /ethernet/data.php?rfid_uid=";

```

# Answer
```
String rfid_uid = "";
if (rfid.readCardSerial()) {
    String rfid_uid = "";
    for (int i = 0; i < 4; i++) {
        Serial.print(rfid.serNum[i], HEX);
        rfid_uid = rfid.serNum[i];
    }

    Serial.println();
}

```

This code has multiple problems:

* the variable `rfid_uid` is defined twice, they are overshadowing each other. The inner part only assigns a value to the `rfid_uid` delcared in the inside of the `if` statement, the outer `rfid_uid` will remain empty
* As you can see with `Serial.print(rfid.serNum[i], HEX);`, the element `rfid.serNum[i]` is an integer, which is printed as hex. (e.g. 123 = `7B`), in `rfid_uid = rfid.serNum[i];` you however assign the direct numerical value, without converting it to hex

You can try the following, if you want the serial number as a 4 byte hex string:

```
String rfid_uid = "";
if (rfid.readCardSerial()) {
    for (int i = 0; i < 4; i++) {
        String uid_part = String(rfid.serNum[i], HEX);
        Serial.print(uid_part);
        rfid_uid += uid_part;
    }

    Serial.println();
}
//rest as before

```

This should construct a `String` object from the integer in `HEX` format and append (using the `+=` operator it to the `rfid_uid` string). Thus, after 4 iterations, the `String` value is built up and can be used in the request.
> 2 votes

# Answer
do not use String

```
char url[64];
sprintf(url, "GET /ethernet/data.php?rfid_uid=%02x%02x%02x%02x", rfid[0], rfid[1], rfid[2], rfid[3]);

```
> 0 votes

---
Tags: ethernet, cpp
---


# Question
Title: How to send int[][] as a byte array through Serial
I have `int arr[50][2];` and I need to send it through Serial. But I don't know how to do it. is it possible?

# Answer
In the comment you write that the receiving end is an Arduino too. Then you can send the data in binary form.

To send the array:

```
Serial.write((byte*) arr, sizeof(arr));

```
* `(byte*)` is cast of the memory location of arr to a byte array
* `sizeof` returns the size of the array in bytes

To receive the binary data you must know the size. Here we read 100 16-bit integers:

```
Serial.readBytes((byte*) arr, 100 * sizeof(short));

```

Function readBytes is one of the 'timed' functions of Stream. It waits for the next byte (until timeout).

If one Arduino is 8-bit and the second is 32-bit, then use the type `short` instead of int, because the size of type int is different, but the type short is 16 bit long on all Arduinos.
> 1 votes

---
Tags: serial, arduino-nano, array
---


# Question
Title: Is there any library for use Arduino Uno with esp8266-01 module?
I have a Arduino Uno and the esp8266 module,(NOT THE SHIELD).

I was looking for some library that I could use to connect to Wifi and set a webserver, but I can't find anything. I just found for Arduino Wifi Shield which uses SPI.

It is possible to use arduino lets say to read a LM35 and then send that data to the ESP8266 module and serve it in a page as webserver?

I know that I can use AT commands with ESP8266 to connect to wifi and to create a server, but I cannot find any function to set the data to be served.

https://www.espressif.com/sites/default/files/documentation/4a-esp8266\_at\_instruction\_set\_en.pdf

# Answer
For a webserver, program the ESP8266 directly. This allows you to make use of the internal SPI flash memory to store your webpages. You can't do this with AT commands.

The Arduino UNO does not have enough processing power and/or memory for advanced internet stuff. If you want a webserver over AT commands, the Arduino has to do all the hard work, the ESP8266 is just a dumb slave that establishes a TCP connection.
The ESP8266 is much faster, and has many times more memory, so it makes sense to let it do all the heavy lifting.

Take a look at this guide: ESP8266 temperature logger

You can copy pretty much all code, but instead of measuring the temperature from an actual sensor, read it from the `Serial` input.

Then just connect the Arduino to the ESP8266 over Serial (or SPI or I²C or SoftwareSerial, whatever you prefer), and have it send the temperature to the ESP8266, for example every second.

To program the ESP8266, you can use the USB-to-Serial adapter of one of your Arduinos.

---

In this case, where you just want to read a single LM35, you could even use only the ESP8266. It is true that the LM35 requires at least 4V, but this is not a problem, since most ESP8266 dev boards also provide a 5V supply. The analog input range of 0-1.0V would allow for a temperature up to 100°C.
> 1 votes

# Answer
Why involve the UNO at all. The ESP88266 could be programmed with the Arduino IDE to read the sensor and deal with the internet all by itself. It doesn't need the UNO to do what you want.
> 0 votes

# Answer
You didn't google hard enaugh.

There are plenty of examples serving your environment.

This instructables is just one of it.

> The main aim of this instructable is to show how you can create a simple web server using Arduino and Wi-Fi module which displays the sensor data in the webpage.
> 0 votes

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