# Question
Title: How many sensors can be supported by a single Arduino unit?
I am a beginner in the Arduino world. I made some basic projects of the book that comes with the starter kit (it's was borrowed by a friend of mine) and also I used a humidity, a temperature sensors and a LCD display.

I want to buy an Arduino Uno for measure **room temperature, humidity, carbon monoxide, carbon dioxin and maybe a couple more variables. I will to use 4 sensors, 1 buzzer, 1 LCD display and 1 ESP8266 serial WIFI wireless module**.

After this work I will add for functionalities but as I have a lot of components I am not sure if the Arduino Uno can supports them because it has a limited quantity of pins.

Do I need an Arduino with more pins? what if I use all these pins and I need more? Can the Arduino Uno be expanded with more pins?

As the Arduino Uno is a very small computer, can its processor support all these components and their operations?

# Answer
An Uno has more than enough pins for the devices you described.

* A DHT22 Relative Humidity and Temperature sensor needs only one digital pin for both variables.
* An MQ-7 Carbon Monoxide sensor needs one analog pin.
* An MG-811 Carbon Dioxide sensor needs one analog pin (and an amplifier).
* A Piezo buzzer needs one PWM pin.
* The LCD with a Hitachi interface needs four digital pins.
* The ESP module needs two digital pins.

That's 7 digital pins, one of which needs to be a PWM pin, and 2 analog pins. I did not make any choices about best or cheapest devices, just ones I either knew about or could find quickly by searching. But with this pin requirement doesn't come close to exhausting the available pins on an Uno so there's plenty of capacity left unassigned for you to make other choices that might require different interfaces or more pins.
> 3 votes

# Answer
I think you want to know how many sensors 1 Arduino can support. But just in case, I am answering both interpretations of the title of your question:

1. How many different types of sensors can an Arduino support?:

With the correct software and hardware, the Aruidno can interface with almost any kind of sensor. The exceptions include but are not limited to sensors which produce more data than an Arduino can process (such as a video camera) or sensors that require fast responses (such a time of flight laser distance sensors (LIDAR)).

2. How many sensors can an Arduino support at the same time?:

This depends on what processor resources are needed. If the sensor needs the ADC there 6 channels on most Arduinos. If you need more, there are hardware solutions. But many here have suggested to simply add a 2nd Arduino.

To specifically address your laundry list:

> room temperature

Thermistor connected to ADC. But most are not linear, so you will have to create a look up table.

> humidity

I think there is a SPI module on the market to do this.

> carbon monoxide

These sensors usually require an amplifier. And change with age & temperature. So a lot of software here as well as hardware.

> carbon dioxin

Not sure about this one.

> buzzer

Self osculating? Then you only need a logic output.

> 1 LCD display

Alpha & numeric? Most have 4 or 8 pin Hitachi interfaces. But you can look for a SPI or serial port LCD so as to conserve on Arduino pins.

> ESP8266

This is just a serial device. You will need the Ardino's serial port.

I'll leave it up to you to make a detailed assessment of the necessary processor resources. Because you need to first pick out the specific hardware you will be using.

That's half the battle. The other half is verifying the libraries for all these sensors and communication devices will not interfere with one another. That I will leave up to you as it is not an easy task to wade through all the code for all the different libraries you will be using. And, again, until you pick out exactly what sensors and devices you will be using it is impossible to even start analyzing as we wouldn't know which libraries to look at.
> 1 votes

# Answer
The question itself is a bit broad, but I'll try and provide some insight here.

The number of sensors that can be supported, and the number of pins they require, will depend on what sort of interface they use.

* If your sensor has an **analog** interface, you will need an analog input pin for each sensor.
* If your sensor has an **I2C** interface, you can have multiple devices sharing the same pins (a bus) provided that they have different I2C addresses (often configurable with jumpers on the device).
* If your sensor has an **SPI** interface, you can have multiple devices using the same pins (a bus), except that each will need a *chip select* PIN connected to a digital I/O pin on your Arduino so that it can 'select' each device.
* If your sensor has a **serial** interface, you can generally only have one device.

To add complexity to the problem, you can get expansion modules for the Arduino that will give you extra analog pins or other communication interfaces.

With the long list of sensors you have above, you may also be hard-pressed for program space, as most sensors will need code and/or libraries to interface with them. The Arduinos with more pins (such as the MEGA) also have more program space.

I would encourage you to do some further research on the sensors you want to use, and finding out what interface they use, and what Arduino libraries are available for them. This way, you can fully understand the requirements and limitations of any parts you want to use.

Further reading:
> 1 votes

# Answer
Look at the MUX Shield, I just used one to add 48 Inputs to a MEGA making it capable of having 98 Inputs or Outputs
> 1 votes

---
Tags: arduino-uno, sensors, pins, components
---


title: Serial.print query

text:
# Question
Title: Serial.print query
is it even possible to print a variable output with 4 digits before and one digit after decimal in serial monitor?

my pot reading is shown in the above output

```
value   -   1.2
value   -   51.5
value   -   61.8
value   -   546.6
value   -   255.0
value   -   1235.9

```

to this

```
value   -   0001.2
value   -   0051.5
value   -   0061.8
value   -   0546.6
value   -   0255.0
value   -   1235.9

```

# Answer
> 3 votes
You basiscally want a format string which includes `%f`. However on Arduino, that only returns a `?` (not included to to space reasons). Refer to https://stackoverflow.com/q/27651012/5296568.

However the alternative is `dtostrf` (double-to-string-formatted). The function takes the `double` / `float` value, the total wanted width of the string and the decimal places you want to have.

However it fills the string with spaces to the left until the total width is met. You need an additional pass to replace it with `0`.

```
#include <Arduino.h>

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

    const float vals[] = {
            1.2, 51.5, 61.8,
            546.6, 255.0,
            1235.9
    };

    //allocate 8 byte buffer
    //biggest string is "-9999.9\0" (with NUL)
    char buf[8];

    int numVals = (int) (sizeof(vals) / sizeof(*vals));

    for(int i=0; i < numVals; i++) {
        //format correctly
        dtostrf(vals[i], 4+1+1, 1, buf);

        //convert left-appended spaces to zeroes
        for(size_t j=0; j < sizeof(buf); j++){
            if(buf[j] == ' ')
                buf[j] = '0';
        }

        //print buffer
        Serial.println(buf);
    }
}

void loop() {
}

```

Prints

```
0001.2
0051.5
0061.8
0546.6
0255.0
1235.9

```

Edit: You can also offload it into a function and then feed it with the ADC values.

Example:

```
#include <Arduino.h>

void printValueFormatted(float value, int numDecimalPlaces, int totalWidth) {
    //format correctly
    char buf[16];
    //prevent buffer overflow
    if(totalWidth >= (int) sizeof(buf))
         return;
    dtostrf(value, totalWidth, numDecimalPlaces, buf);

    //convert left-appended spaces to zeroes
    for(size_t j=0; j < sizeof(buf); j++){
        if(buf[j] == ' ')
            buf[j] = '0';
    }

    //print buffer without newline
    Serial.print(buf);
}

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

void loop() {
    float val = analogRead(0);
    Serial.print("ADC Count: ");
    Serial.print(val);
    Serial.print("  -- Voltage: ");
    val = val * 5.0f / 1023.0f;
    printValueFormatted(val, 1, 4+1+1);
    //print newline
    Serial.println();
    delay(100);
}

```

Prints

```
ADC Count: 719.00  -- Voltage: 0003.5
ADC Count: 718.00  -- Voltage: 0003.5

```

# Answer
> 2 votes
```
if(val < 1000){Serial.print('0');}
if(val < 100){Serial.print('0');}
if(val < 10){Serial.print('0');}
Serial.println(val, 1);

```

---
Tags: arduino-uno
---


# Question
Title: Float magnet switch interrupts atmega328p and RN2483 sends data
It was so easy to my mind but it is really not. I have a float switch which goes high when water is floating. So I connect the switch to INT0 pin of MCU. So when water is not floating everything is OK. When the water is floating I send data. I declare the interrupt as follows:

```
attachInterrupt (digitalPinToInterrupt (switch), float, RISING);

```

Where float is

```
void float()
{
detachInterrupt(0);
digitalWrite (LED, HIGH);
txReturn = myRN.txCnf("1");
}

```

And my main loop is

```
attachInterrupt (digitalPinToInterrupt (BUTTON), switchPressed, RISING);
digitalWrite (LED, LOW);
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

```

I can't understand why my led is not going LOW and why I interrupt is useless after the first successful time. I am aware that I must keep interrupts routines short and by `txReturn.txCnf("1");` I don't but I can not understand where my logic is wrong.

# Answer
> 2 votes
`float` is already defined for floating point number, so you cannot use it for your function that detects when the sensor is floating on water. Try calling it something else.

Also, instead of detaching and reattaching the interrupt, use a state machine. When the interrupt is triggered, you will be able to run different code in the main loop.

```
unsigned int state;
void setup(){
  state=1;
  attachInterrupt(0,changestate,RISING);
}
void loop(){

switch (state) {
case 1: // do something
// add code here
break;

case 2: // do something else
// add code here
break;
}
}

void changestate(){
if(state==1){state=2;} // interrupt changes state
}

```

---
Tags: interrupt, atmega328
---


# Question
Title: DMX on the Arduino without additional driver chip
I recently saw this video where the creator controlled a DMX light via the Arduino. There he used the pins 3 and 4 for the data on the Arduino Duemilanove. As DMX library he used DmxSimple.

Based on my research DMX is RS-485 and for this there's a driver chip required.

So I have three questions about this:

1. Why do all sources I found say that there's a driver chip required when it seems to work without?
2. I got a Arduino Leonardo compatible device (Devduino). Is it possible to control DMX like stated above on this platform?

# Answer
> 1 votes
The physical layer of a DMX interface is based on differential signaling over an RS485 link. This is exactly what is said here on the DMX Arduino.cc page.

A differential signal (like RS485 or USB) can travel greater distances than signals which reference ground (like RS232, I2C or SPI). This is because noise, which affect both sides of a differential signal, can be canceled out at the far end when one of the signals is inverted then added to the other by the differential receiver.

Connecting one side of a differential receiver to ground and driving the other side with logic level voltage is not recommended. Even if it worked and did not cause harm to the transmitting processor nor the differential receiver the signal will likely be susceptible to undesirable noise.

RS485 is a ubiquitous standard and likely several easily sourced designs exist for the Arduino.

# Answer
> 0 votes
It might be possible, actually. A differential signal **can** be produced via a standard Arduino, though there's still the 5V logic level to be concerned about. I am guessing that his lamp was capable of a 5V-swing signal (10V, all told), but this is not a guarantee, especially if the standard does not normally support this. In that sort of case, you trust that the manufacturer made the device sufficiently hardened/overengineered so that the higher voltages do not cause damage.

From watching the linked video, the signal wires are **both** attached to *GPIO pins* of the Arduino board. If one is pulled HIGH (5v) and the other LOW (Gnd), you produce a signal. The other differential signal is provided by swapping which pins are LOW and HIGH.

EDIT: That's a Duemilanove, NOT an Uno, so the outputs might be different. (Still, one of the newer 3v3 boards would probably be safer, if you are testing this). Further, if the wires are long enough, there might even be something of a voltage drop that makes it safe(er).

The end result then uses bit-banging to emulate a transceiver using this jury-rigged differential transmitter.

# Answer
> 0 votes
RS485 or RS422 and consequently DMX use differential drivers at 5 volts. This means that both lines are 0 to 5V nominally, with a (usually, depending on the cable used) 120 ohm resistor as a terminator on both ends. A 3.3V signal might work, but barely.

perhaps sending the signal on one line and just 0V on the other might work sort-of, but I've never tried or even heard of that.

My guess would be that in this case they are using a bit-banged serial port modified to also control the other pin, but inverted. Perhaps something could be done with a standard serial port on one pin, setting up an interrupt on that pin changing level, and using the ISR to check the level on the 'serial pin and invert it and set the other pin. I think that would probably incur too much of a delay between the two pins, but perhaps not. Strictly speaking, the delay between the two pins changing if it was bit-banged is probably out of spec for RS422/485, but might work anyway unless the baud rate was higher.

If you are going to use DMX, spend the $0.30 and buy a driver chip or a bit more and get a DMX shield. I've seen DMX get screwed up by a whole lot less than the differential line being a bit out of sync.

---
Tags: arduino-leonardo, rs485, arduino-duemilanove
---


# Question
Title: "Does not name a type" error with Serial.print
I am getting an error that I have never seen before and don't know how to fix. Basically I am trying to print a string (stored in `thermistor`) to the serial monitor. When I run the code I get an error message that says: exit status 1 'Serial' does not name a type.

What can I do fix this error?

```
void setup() {
Serial.begin(9600);
pinMode(4, OUTPUT);
pinMode(6, OUTPUT);
pinMode(8, OUTPUT);

}

void loop() {

} <==== ERROR: loop() ENDS TOO EARLY
String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
  <==== ERROR: MISSING RETURN STATEMENT
}

```

# Answer
> 1 votes
If you move this code into loop(), the sketch will compile.

```
String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

```

EDIT:

The sketch should look like this:

```
void setup() {
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
  String lilyPad = codeWrite(6, HIGH, LOW, LOW);
  String thermistor = codeWrite(8, HIGH, HIGH, LOW);
  Serial.println(thermistor);
  delay(1000);
}

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
}

```

The issue is the code can not be outside of a function.

---
Tags: compilation-errors
---


title: Multiple #ifndef vs. single one #endif

text:
# Question
Title: Multiple #ifndef vs. single one #endif
My question is connected with the issue as linked: Is there any good working MODBUS TCP master library available for Arduino?

An example of Modbus TCP master library as suggested in the post above. A part of ModbusTCP.h file:

```
#ifndef Modbus_TCPIP_h
#define Modbus_TCPIP_h

#ifndef WIZNET_W5100
#define WIZNET_W5100  0       /**< define 1 if  WIZNET W5100 IC is used, otherwise 0 */
#ifndef ENC28J60
#define ENC28J60      1       /**< define 1 if  ENC28J60 IC is used, otherwise 0     */
#ifndef ESP8266
#define ESP8266       0

//...The entire code of the header

#endif // Just a single one occurence of the #endif in the last line of the header code! 8-|

```

When I've run the compilation of it in my Arduino IDE, I've got an error as follows: unterminated #ifndef. Mentioned error has a four ocurrences in the error log and it is linked to: Modbus\_TCPIP\_h, WIZNET\_W5100 and ENC28J60.

What should be modified in the header file?

# Answer
> 0 votes
The code is missing "#endif". Should look something like this:

```
#ifndef WIZNET_W5100
#define WIZNET_W5100  0       /**< define 1 if  WIZNET W5100 IC is used, otherwise 0 */
#endif
#ifndef ENC28J60
#define ENC28J60      1       /**< define 1 if  ENC28J60 IC is used, otherwise 0     */
#endif
#ifndef ESP8266
#define ESP8266       0
#endif

```

Cheers!

---
Tags: library, tcpip, modbus
---


title: TimerOne Library - Response time

text:
# Question
Title: TimerOne Library - Response time
I'm trying to write a library for (rather slow) communication with visible light and have recently tried to include the TimerOne library as a timer. I want to send bits at 2kHz, so with a period of 500µs. I'm initializing the `Timer1` with 500(µs) like this and then attach an interrupt to it to call my transmit function:

```
Timer1.initialize(500);
Timer1.attachInterrupt(transmitBit);

```

However, when I try to measure the period with a logic analyzer, it tells me that there is actually a period of 2,000µs. Could this be due to some overhead created by the library? Where else could the problem be?

If you need any other information just let me know and I'll try to provide it.

Thanks in advance for your feedback.

**EDIT:** I've just tried adding the period as a parameter to the `attachInterrupt` like so:

```
Timer1.attachInterrupt(transmitBit, 500);

```

And now I'm measuring a period of 30µs for whatever reason? Can anyone explain me what's going on?

**EDIT:** This is the rest of my (relevant) code:

```
Transmitter::Transmitter()
{
  [...]
  Timer1.initialize(500);
}

Transmitter* Transmitter::_instance;

void Transmitter::start() {
  _instance = this;
  Timer1.attachInterrupt(_transmitBit, 500);
  _active = true;
}

static void Transmitter::_transmitBit() {
  _instance->transmitBit();
}

void Transmitter::transmitBit() {
  if(_active) {
    //Preperation
    if(!_manHalf) { //only change the state when the manchester bit is completely transmitted.
      if(_busy) {
        //Serial.println("Transmitting!");
        /** if there is currently a transmission running
          * read the next bit from the frame
          */
        _state = *(_frame + _pos);
        if(_pos >= _frameSize) {
          _busy = false;
          _state = 0;
          _pos = 0;
        }
        _pos++;
      } else { //else transmit the idle pattern
        _state = 0;
      }
    }
    //Transmission
    if (!_manHalf) {
      digitalWrite(_pin, !_state);
    } else {
      digitalWrite(_pin, _state);
    }
    _manHalf = !_manHalf;
  } else {
    digitalWrite(_pin, HIGH);
  }
}

```

# Answer
> 1 votes
Before using libraries, try to see whether you can manipulate the timer registers directly to achieve what you want. You may find it is easier!

In the following example I assume you are using an ATmega328 chip. The code may be slightly different for other microcontrollers. In that case you can read the data sheets for both microcontrollers and work out what you need to change.

I also assume the data you want to transmit is stored in a byte array. Initialize the data how you prefer.

e.g: `byte my_data[10] = {0,0,0,0,0,0,0,0,0,0};`

Next, you want to initialize timer1 in the main loop

```
TCCR1A=0;
TCCR1B=0;

```

To send data at 2000 bits per second, the following settings can be used

```
ICR1=124; // Timer counter resets to 0 after reaching 124
OCR1A=125;
OCR1B=125; // other counter match registers must be higher than ICR1
TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags

```

This will set the timer1 match register bit `ICF1` every 500 us. There are several ways of using the timer to send the data. My preference would be to poll the match flag. The timing precision is about as good as you can get - a couple of clock cycles:

```
loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1=ICR1
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
// switch digital output high or low depending on data bit to be sent

```

One way is to run a state machine loop like this:

```
unsigned int state;

void setup(){
state=0;
}

void loop(){
switch (state){
case 0: // idle or receiving data to be sent
TCCR1A=0;
TCCR1B=0;
// insert other code here
// conditional function, when message data received, set state=1;
break;

case 1: // setup timer
ICR1=124; // Timer counter resets to 0 after reaching 124
OCR1A=125;
OCR1B=125; // other counter match registers must be higher than ICR1
TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
break;

case 2:
loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1==ICR1
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
// switch digital output high or low depending on data bit to be sent

// add conditional function so that when you are finished sending data, reset to state=0;
break;

}
}

```

As always, please upvote if you find this helpful.

---
Tags: arduino-uno, interrupt, timers
---


# Question
Title: Arduino how to get amount of elements in an array?
Hello have an array of strings that loads strings from a txt file on an sd card. The txt file on the SD card can change from time to time(not while the Arduino is running).I want to be able to get the amount of elements in the array after the txt file has been loaded into the array. The txt file has lines of txt in it. Each line in the file is put into a string in the array. I want to be able to get the amount of elements in the array how can I do this?

# Answer
> 6 votes
You can't. That concept does not exist in C.

An array has a fixed size - as such you know how many elements are in it, since that is the number of elements you created it with.

```
String myStrings[4];

```

That is an array of 4 String objects. It has 4 elements. It will always have 4 elements.

# Answer
> 10 votes
numElements = (sizeof(array) / sizeof(array\[0\]));

---
Tags: arduino-uno
---


title: 4WD Arduino sketch problem

text:
# Question
Title: 4WD Arduino sketch problem
Here is the code:

```
/**  * @file         Arduino UNO Autonomous Robot  * @author       Calin Dragos for intorobotics.com  * @version      V1.0  * @date
      13.10.2016  * @description  This is an Arduino sketch for an autonomous robot able to detect and avoid obstacles  */
#include <AFMotor.h>
#include <Servo.h>
#include <NewPing.h>
Servo myservo;
int ENABLE_A = 6;
int PIN_A1 = 3;
int PIN_A2 = 2;
int ENABLE_B = 11;
int PIN_B1 = 5;
int PIN_B2 = 4;
int SENSOR_DISTANCE;
int LEFT_SENSOR_DISTANCE;
int RIGHT_SENSOR_DISTANCE;
int SNZ_DISTANCE_L;
int SNZ_DISTANCE_R;
int LFT_SNZ_DIS;
int RGT_SNZ_DIS;
#define TRIG_PIN 7
#define ECHO_PIN 8
#define MIN_DISTANCE 40
#define MAX_DISTANCE 200
#define INTERVAL 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  //pin mode for the DC motors
  pinMode (ENABLE_A, OUTPUT);
  pinMode (PIN_A1, OUTPUT);
  pinMode (PIN_A2, OUTPUT);
  pinMode  (ENABLE_B, OUTPUT);
  pinMode (PIN_B1, OUTPUT);
  pinMode (PIN_B2, OUTPUT);
  //pin mode for the ultrasonic sensor
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  //for servo motor
  myservo.attach(9);
  //set the ultrasonic sensor to center
  sensorCenter();
  //stop the motors
  stopMotors();
}

void loop() {
  SENSOR_DISTANCE = sensorDistance();
  Serial.print("Front sensor distance is: ");
  Serial.println(SENSOR_DISTANCE);
  if (SENSOR_DISTANCE >= MIN_DISTANCE || SENSOR_DISTANCE == 0) {
    goForward();
    Serial.println("Go forward");
  }
  else {
    //stop the motors
    stopMotors();
    LFT_SNZ_DIS = toTheLeft();
    RGT_SNZ_DIS = toTheRight();
    if (LFT_SNZ_DIS >= MIN_DISTANCE && LFT_SNZ_DIS >= RGT_SNZ_DIS)
    {
      int NEW_SNZ_DIS_LFT;
      //try three times to escape
      for (int i = 1; i <= 3; i++) {
        goLeft();
        Serial.println("Go left");
        delay(300);
        //stop the motors
        stopMotors();
        NEW_SNZ_DIS_LFT = sensorDistance();
        if (NEW_SNZ_DIS_LFT >= MIN_DISTANCE)
        {
          break;
        }
      }
      sensorCenter();
    }
    else if (RGT_SNZ_DIS >= MIN_DISTANCE && RGT_SNZ_DIS >= LFT_SNZ_DIS)
    {
      int NEW_SNZ_DIS_RGT;
      //try three times to escape
      for (int j = 1; j <= 3; j++) {
        goRight();
        Serial.println("Go right");
        delay(300);
        //stop the motors
        stopMotors();
        NEW_SNZ_DIS_RGT = sensorDistance();
        if (NEW_SNZ_DIS_RGT >= MIN_DISTANCE)
        {
          break;
        }

      }
      sensorCenter();
    }
    else
    {
      goBackward();
      Serial.println("Go backward");
      delay(500);
      //stop the motors
      stopMotors();
      sensorCenter();
    }
  }
}

void stopMotors() {
  analogWrite (ENABLE_A, 0);
  analogWrite (ENABLE_B, 0);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, LOW);
  digitalWrite (PIN_B1, LOW);
  digitalWrite (PIN_B2, LOW);
}

int sensorDistance() {
  int distance;
  int uS = sonar.ping();
  distance = uS / US_ROUNDTRIP_CM;
  if (distance != 0) {
    return distance;
    delay(300);
  }
}

void goForward() {
  analogWrite (ENABLE_A, 255);
  digitalWrite (PIN_A1, HIGH);
  digitalWrite (PIN_A2, LOW);
  analogWrite (ENABLE_B, 255);
  digitalWrite (PIN_B1, HIGH);
  digitalWrite (PIN_B2, LOW);
}

void goBackward() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, HIGH);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1, LOW);
  digitalWrite (PIN_B2, HIGH);
}

void goLeft() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, HIGH);
  digitalWrite  (PIN_A2, LOW);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1,  LOW);
  digitalWrite (PIN_B2, HIGH);
}

void goRight() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, HIGH);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1, HIGH);
  digitalWrite (PIN_B2, LOW);
}

void sensorCenter() {
  myservo.write(90);
  delay(500);
}

void turnSensorLeft() {
  myservo.write(120);
  delay(500);
}

void turnSensorRight() {
  myservo.write(60);
  delay(500);
}

int leftSensorDistance() {
  int LEFT_SENSOR_DISTANCE;
  LEFT_SENSOR_DISTANCE = sensorDistance();
  return LEFT_SENSOR_DISTANCE;
}

int rightSensorDistance() {
  int RIGHT_SENSOR_DISTANCE;
  RIGHT_SENSOR_DISTANCE = sensorDistance();
  return RIGHT_SENSOR_DISTANCE;
}

int toTheLeft() {
  int LEFT_SENSOR_DISTANCE;
  turnSensorLeft();
  LEFT_SENSOR_DISTANCE = leftSensorDistance();
  Serial.print("Left sensor distance is: ");
  Serial.println(LEFT_SENSOR_DISTANCE);
  return LEFT_SENSOR_DISTANCE;
}

int toTheRight() {
  int RIGHT_SENSOR_DISTANCE;
  turnSensorRight();
  RIGHT_SENSOR_DISTANCE = rightSensorDistance();
  Serial.print("Right sensor distance is: ");
  Serial.println(RIGHT_SENSOR_DISTANCE);
  return RIGHT_SENSOR_DISTANCE;
}

```

Here is the error that I am getting:

```
Arduino: 1.8.6 Hourly Build 2018/05/28 09:33 (Windows 8.1), Board: "Arduino/Genuino Uno"
In file included from C:\arduino-nightly\hardware\arduino\avr\cores\arduino/Arduino.h:257:0,
                 from sketch\intorobotics.ino.cpp:1: C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
error: expected unqualified-id before numeric constant
#define PIN_A1 (15)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
note: in expansion of macro 'PIN_A1'
int PIN_A1 = 3;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
error: expected ')' before numeric constant
#define PIN_A1   (15)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
note: in expansion of macro 'PIN_A1'
int PIN_A1 = 3;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
error: expected unqualified-id before numeric constant
#define PIN_A2 (16)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
note: in expansion of macro 'PIN_A2'
int PIN_A2 = 2;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
error: expected ')' before numeric constant
#define PIN_A2   (16)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
note: in expansion of macro 'PIN_A2'
int PIN_A2 = 2;
     ^ exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with "Show verbose output
during compilation" option enabled in File -> Preferences.

```

# Answer
> 0 votes
It looks like you've chosen names for your variables that are being used by the core. Pick different names for those variables.

---
Tags: arduino-uno
---


title: Minimizing Digital input code

text:
# Question
Title: Minimizing Digital input code
I am making a device which can multiply the analog input signal with respect to the selected gain from the digital inputs. Here I have used two digital inputs(from which I can have four selections) but I am planing to add two inputs more(then I can have 16 selections). I made the code with if else statements is there any shorter way to do that? or else the code is getting huge.

here is the code:

```
#define sensor A0
#define resetPin 3
#define measurePin 2
#define k1 3
#define k2 4

float A = 0;
float J = 0;
int resetstatus = 0;
int measurestatus = 0;

void setup() {
  Serial.begin(9600);
  pinMode(sensor,INPUT);
  pinMode(resetPin,INPUT_PULLUP);
  pinMode(measurePin,INPUT_PULLUP);
  pinMode(k1,INPUT_PULLUP);
  pinMode(k2,INPUT_PULLUP);
  Serial.println("INITIALAIZING");
  delay(3000);
  Serial.println("Ready to begin");
  delay(200);
  }

void loop()
{
  resetstatus = digitalRead(resetPin);
  measurestatus = digitalRead(measurePin);
  if(resetstatus == LOW)
  {
    reset();
    delay(200);
  }
  if(measurestatus == LOW)
  {
    if(digitalRead(k1 == LOW) && digitalRead(k2 == LOW))
    {
    J = 1.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == LOW) && digitalRead(k2 == HIGH))
    {
    J = 2.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == HIGH) && digitalRead(k2 == LOW))
    {
    J = 3.0;
    measure();
    delay(50);
    }
    if(digitalRead(k1 == HIGH) && digitalRead(k2 == HIGH))
    {
    J = 4.0;
    measure();
    delay(50);
    }
  }
}
void measure()
{
  A = analogRead(sensor);
  float sumA = A * J;
  Serial.println(sumA);
}
void reset()
{
  Serial.println("reset");
}

```

I am having a problem with the output from this code (I am using a potentiometer to feed the arduino an analog value)

I dont know why the output is showing 993 and 3972 at each cycle. can someone explain?

# Answer
> I made the code with if else statements is there any shorter way to do that?

```
j = 1 + (digitalRead(k1) | (digitalRead(k2) << 1) | (digitalRead(k3) << 2) | (digitalRead(k3) << 3));

```

or

```
j = 1 + digitalRead(k1) + 2*digitalRead(k2) + 4*digitalRead(k3) + 8*digitalRead(k4)

```

> dont know why the output is showing 993 and 3972 at each cycle. can someone explain?

the printed values are off because of the error addressed in Nick's answer
> 2 votes

# Answer
This is wrong:

```
if(digitalRead(k1 == LOW)

```

You mean:

```
if(digitalRead(k1) == LOW

```

Ditto for a lot of other places in your code.
> 3 votes

# Answer
> I made the code with if else statements is there any shorter way to do that? or else the code is getting huge.

Yes, there is a way of simplification. As @Juraj already noted, it can in this special case even be expressed as a binary representation:

```
if(digitalRead(k1) == LOW && digitalRead(k2) == LOW)
{
J = 1.0;
measure();
delay(50);
}
else if(digitalRead(k1) == LOW && digitalRead(k2) == HIGH)
{
J = 2.0;
measure();
delay(50);
}
else if(digitalRead(k1) == HIGH && digitalRead(k2) == LOW)
{
J = 3.0;
measure();
delay(50);
}
if(digitalRead(k1) == HIGH && digitalRead(k2) == HIGH)
{
J = 4.0;
measure();
delay(50);
}

```

What you are doing here is the following pattern:

* read the state of the buttons
* depending on which combinations of buttons is pressed, assign a different value to `J`

We can generalize this concept of "get the J value for a certain button combination" by doing the following:

* aggregate the entire "button states" into a single, unique number
* search for the associated `J` value

If we name the input button states "k1" and "k2", we see that you have the following logic:

```
| k1 | k2 | J   |
| 0  | 0  | 1.0 |
| 0  | 1  | 2.0 |
| 1  | 0  | 3.0 |
| 1  | 1  | 4.0 |

```

We simply concatenate the button inputs to a signle bitstring "k1|k2" and we see

```
| (k1,k2) | J   |
| 00      | 1.0 |
| 01      | 2.0 |
| 10      | 3.0 |
| 11      | 4.0 |

```

If we re-write the binary indices to decimal numbers:

```
| (k1,k2) | J   |
| 0       | 1.0 |
| 1       | 2.0 |
| 2       | 3.0 |
| 3       | 4.0 |

```

So we see that we can use this (k1,k2) number as an index from 0 to 3 to get us a J value as such:

```
//Aggregate all button inputs to single number
//using bitshifts
int index = (digitalRead(k2) << 1) | digitalRead(k1);

//All used J values in the right order
const float J_values[] = {
        1.0f, 2.0f, 3.0f, 4.0f
};

//get the right J value
J = J_values[index];

//measure and delay
measure();
delay(50);

```

This replaces all your 4 `if-else` statements and does exactly the same.

Now if you were to add more inputs, you can simply expand the way you construct the index number and your `J_values` array. Write down the "function table" for your wanted `J` values as above, construct the bit strings, order the indices in ascending order and write down the array values accordingly.

Referenecs:
> 2 votes

# Answer
Put all 4 pins on one port then do a port read. Say you used D2,3,4,5 Then switches = (PIND && 0b00111100) \>\> 2;

then switches = 0 to 15 and you can do a branch on that.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Assigning Pointers to arrays - incorrect results?
I'm trying to build a transmission frame for a workshop library for the Arduino Uno. I have the byte frame inside an array, give it to another function that builds a bit frame and then want to transmit that bit frame.

When I try to print out the arrays using the serial monitor, I get the correct results for the entire byte array and correct results for the bit array up to a certain point. However, since my output (that I'm checking using a logic analyzer) had also more incorrect values when trying to print the values, I suspect it might have to do with timing issues from my transmission and `Serial.print`.

I thus tried to make another pointer (in the code below `frameCheck`) to print that out *after* I'm done transmitting my frame, which still leaves me with results that are different from what my logic analyzer tells me from a certain point onwards.

My byte array is as follows:

```
10100101  // Preamble
10000000  // First line of my image
00100000
00010000
01000000
00000000
00000000
00000000
00000000  // Last (8th) line of my image
11110000  // Checksum

```

These values are also represented in the bit array (before assignment to what in my code be called `_frame` as well as after that). However, when I read the values from the logic analyzer, the checksum is transmitted as `11111111` instead of `11110000`.

Here is my code in the .cpp file:

```
Transmitter::Transmitter()
{
  [...]
  _frame = new uint8_t[90];
  frameCheck = _frame;
  [...]
}

[...]

int Transmitter::prepFrame(LEDBitmap image) {
  if(_busy) return -1; //no Data can be sent right now since the transmitter is already busy
  if(!_pin) return -2;
  /** construct the frame that is to be transmitted
    *
    * frame structure is
    * 1 byte preamble (0xA5) | 8 byte payload | checksum
    *
    * the image will be transmitted in rows
    * with one row being one byte
    *  1  2  3  4  5  6  7  8   <-- 1st byte
    *  9 10 11 12 13 14 15 16   <-- 2nd byte
    * 17 18 19 20 21 22 23 24   <-- 3rd byte
    * ...                           ...
    */
  uint8_t size = 10;
  uint8_t frame[size];
  uint8_t checksum = 0x00;

    for(uint8_t h = 0; h < image.getHeight(); h++) {
      uint8_t value = image.getBitmap()[h];
      checksum = (checksum + value) % 255;
      frame[h+1] = value;
    }

    for(uint8_t h = image.getHeight(); h < 8; h++) {
      frame[h+1] = 0x00;
    }

  // building the frame
  frame[0] = PREAMBLE;
  frame[size-1] = checksum;

//The byte frame "frame" is correct at this point

  _frame = buildBitFrame(frame, size);

//The frame built by this function (see below) as well as the bit frame "_frame" have the correct checksum

  frameCheck = _frame;  // <-- This is the checkFrame which I print in my .ino which gives me false results.

  // set the transmitter into busy mode so the idle pattern will no longer
  // be transmitted but instead the frame will be sent out.
  _busy = true;
  _pos = 0;

  return 1; //preperation was successful
}

uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
  _frameSize = size*8;
  uint8_t bitFrame[_frameSize];
  int pos = 0;
    for (size_t byte = 0; byte < size; byte++) {
      for (size_t bit = 0; bit < 8; bit++) {
        bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
        pos++;
      }
    }

  return bitFrame; // <-- This frame is correct as well.
}

void Transmitter::transmitBit() {
  if(_active) {
    // Preperation
    // only change the state when the manchester bit is completely transmitted.
    if(!_manHalf) {
      if(_busy) {
        // if there is currently a transmission running
        // read the next bit from the frame
        _state = _frame[_pos];
        if(_pos >= _frameSize) {
          _busy = false;
          _state = 0;
          _pos = 0;
        }
        _pos++;
      } else { // else transmit the idle pattern
        _state = 0;
      }
    }
    // Transmission
    if (!_manHalf) {
      digitalWrite(_pin, !_state);
    } else {
      digitalWrite(_pin, _state);
    }
    _manHalf = !_manHalf;
  } else {
    digitalWrite(_pin, HIGH);
  }
}

[...]

```

The corresponding, relevant lines in the header file are as follows:

```
[...]

class Transmitter
{
  public:
    Transmitter();

  public: //methods
    int sendData(LEDBitmap image);
    void transmitBit();
    [...]
    uint8_t* frameCheck;

  private: //members
    uint8_t _state;
    uint8_t* _frame;
    [...]

    int prepFrame(LEDBitmap image);
    uint8_t* buildBitFrame(uint8_t* frame, uint16_t size);
    [...]

};

[...]

```

The function `transmitBit()` is called every 1ms via a ISR.

Last but not least, here is my arduino sketch:

```
[...]

Transmitter transmitter;

[...]

int smallData[] = {1, 0, 0, 0,
                   0, 0, 1, 0,
                   0, 0, 0, 1,
                   0, 1, 0, 0};

LEDBitmap small(4, 4, smallData);

void setup() {
  Serial.begin(2000000);
  transmitter.setPin(4);
  transmitter.start();
  delay(200);
  pinMode(5, OUTPUT);
  digitalWrite(5, HIGH);
  transmitter.sendData(small);
  delay(1000);
  for(int a = 0; a < 88; a++) {
    Serial.println(transmitter.frameCheck[a]);
  }
}

```

The loop is currently empty.

Now onto the weird results I'm getting from printing checkFrame (which I have also already gotten when trying to print the full arrays inside my cpp). This is what it printed (already grouped in bytes):

```
1 0 1 0 0 1 0 1
1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0        // Up to here everything is fine.
0 0 0 0 0 2 149 0      // On the logic analyzer this line reads 0x00 as it should
221 5 15 0 2 149 0 1   // On the logic analyzer this line reads 0xff instead
1 222 0 98 2 149 8 218 // This line is irrelevant as it is only a buffer I added to see if the problem lies within my array not having enough space

```

Now onto my questions!

Do you have an idea what could cause this? Did I do the array assignment wrong? Could this just be an issue with the timing of the `Serial.print`s and my transmitter going off every 1ms? But why does my logic analyzer say that the last line is `0xff` then? Do you have any idea how to fix this?

I'd be super glad if you responded as quickly as possible. Thanks in advance!

**EDIT:** After increasing the initial value of `a` in my sketch to 64, I found out that the 8th byte is still `00000000` as it says on the logic analyzer. However, the checksum still was a mess. This did also not improve a lot after increasing it to 72. It then was `1 1 2 149 8 218 5 15`. These last few values did also not change when I increased `a` again to 74.

# Answer
```
uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
  _frameSize = size*8;
  uint8_t bitFrame[_frameSize];
  int pos = 0;
    for (size_t byte = 0; byte < size; byte++) {
      for (size_t bit = 0; bit < 8; bit++) {
        bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
        pos++;
      }
    }

  return bitFrame; // <-- This frame is correct as well.
}

```

You are returning a pointer to a function-local array which was allocated on the stack. After the function exists the stack for that function gets de-allocated and the array becomes invalid.

It may be valid for a short time after the function exists, but as soon as new functions are called and variables are allocated on the stack, this gets overwritten.

See https://www.fayewilliams.com/2015/06/30/a-challenge-discussion-returning-pointers-to-local-variables/

In cases like these (especially with a constant maximum frame length), you should re-write your memory management to use statically allocated buffers within your class.

For example:

```
uint8_t* _frame;

```

to

```
#define SOME_MAX_SIZE 128
uint8_t _frame[SOME_MAX_SIZE];

```

And then re-write functions to write into these buffers instead of allocating new memory every time.

Dynamic memory allocation in general should be avoided at all costs on a microcontroller due to heap fragmentation.

If you really want to keep doing it you could also allocate a `new` frame of the required length **and** make sure to **delete** it after usage!

```
uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
  _frameSize = size*8;
  uint8_t* bitFrame = new uint8_t[_frameSize];
  int pos = 0;
    for (size_t byte = 0; byte < size; byte++) {
      for (size_t bit = 0; bit < 8; bit++) {
        bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
        pos++;
      }
    }

  return bitFrame; //return pointer to malloced array, okay now.
}

```
> 1 votes

---
Tags: arduino-uno, serial, array, pointer
---


# Question
Title: IR receiver starts giving nonsense readings in LED colour change setting
First of all, I'm very new to this so sorry if it's a dumb question.

I have an IR module which I'm using to control an LED strip. I have set buttons 1–3 on the remote to select three basic static colours and up and down to adjust brightness. So far so good.

I have set button 4 to gradually shift through different colours. Once I activate this code, the IR receiver appears to stop working, and Serial.print shows that it's now reporting random values whatever button I press on the remote.

I have tried Vishay TSOP4838 and KY-022 type receivers, and tried varying combinations of resistors and capacitors on the receiver power supply. I've tried powering it from 3.3V and 5V.

The code that I'm using is only changing numerical values to adjust the colour, so short of there being 'noise' somewhere in the hardware I'm at a loss as to why only this code breaks it. The LED is powered by a 12V adaptor. The IR receiver is the only thing powered by the Arduino.

My full code is as follows, I know it's untidy. I am a noob:

Thank you

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

//To change the LED/IR reciever pins, you just need to change these values
#define PIN 13 //LED strip
int receiver = 10; //IR receiver

unsigned long debouncing = 0;
unsigned long rotatedelay = 6;
unsigned long fadegap = 5;
byte state = 0; //maintains function based on last button press
byte red = 0;
byte blue = 0;
byte green = 0;
byte brightness = 250;
byte rotate = 0; //used for cycling through colours in state 4

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

//Declare IR objects
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

//Setup IR buttons with names
void translateIR() // takes action based on IR code received

// Naming remote IR codes and assigning a 'state'

{

  switch(results.value)

  {
  case 0xFFA25D: state = 10; Serial.println("POWER"); break;
  case 0xFF629D: state = 11; Serial.println("VOL+"); break;
  case 0xFFE21D: state = 12; Serial.println("FUNC/STOP"); break;
  case 0xFF22DD: state = 13; Serial.println("FAST BACK");    break;
  case 0xFF02FD: state = 14; Serial.println("PLAY/PAUSE");    break;
  case 0xFFC23D: state = 15; Serial.println("FAST FORWARD");   break;
  case 0xFFE01F: Serial.println("DOWN");    break;
  case 0xFFA857: state = 17; Serial.println("VOL-");    break;
  case 0xFF906F: Serial.println("UP");    break;
  case 0xFF9867: state = 19; Serial.println("EQ");    break;
  case 0xFFB04F: state = 20; Serial.println("ST/REPT");    break;
  case 0xFF6897: state = 0; Serial.println("0");    break;
  case 0xFF30CF: state = 1; Serial.println("1");    break;
  case 0xFF18E7: state = 2; Serial.println("2");    break;
  case 0xFF7A85: state = 3; Serial.println("3");    break;
  case 0xFF10EF: state = 4; Serial.println("4");    break;
  case 0xFF38C7: state = 5; Serial.println("5");    break;
  case 0xFF5AA5: state = 6; Serial.println("6");    break;
  case 0xFF42BD: state = 7; Serial.println("7");    break;
  case 0xFF4AB5: state = 8; Serial.println("8");    break;
  case 0xFF52AD: state = 9; Serial.println("9");    break;
  case 0xFFFFFFFF: Serial.println("REPEAT");break;

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

  }// End Case

} //END translateIR

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the IR receiver
  strip.begin();
  colorBlock(strip.Color(0, 0, 0));
  strip.show(); // Initialize all pixels to 'off'

//Fades LED strip light in at startup
for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, 255 * b/255, 255 * b/255, 255 * b/255);
     }

     strip.show();
     delay(5); //speed of fade in (20 x 255 = total time)
  };
}

void loop() {

//IR detection code
//if (irrecv.decode(&results) && millis() - debouncing > 1000) // have we     received an IR signal? ignores button press if less than a second after previous
if (irrecv.decode(&results)) // have we received an IR signal?
{
    translateIR();
    irrecv.resume(); // receive the next value
    Serial.println(results.value, HEX);

if (state == 1){
  rotate = 0;
  red = 0; blue = 255; green = 0;
colorBlock(strip.Color(red, blue, green));
}

if (state == 2){
  rotate = 0;
  red = 0; blue = 0; green = 255;
colorBlock(strip.Color(red, blue, green));
}

if (state == 3){
  rotate = 0;
  red = 255; blue = 0; green = 255;
colorBlock(strip.Color(red, blue, green));
}

//brightness
if (results.value == 16769055 && brightness > 0){
  brightness = brightness - 10;
  strip.setBrightness(brightness); strip.show();
  Serial.println(brightness);
}

if (results.value == 16748655 && brightness < 241){
  brightness = brightness + 10;
  strip.setBrightness(brightness); colorBlock(strip.Color(red, blue, green));     strip.show();
  Serial.println(brightness);
}
}

//rotating colours
if (state == 4){
  //Serial.println (state);
  //Serial.println (rotate);
  //Serial.print ("red"); Serial.print (red); Serial.print ("blue"); Serial.print (blue); Serial.print ("green"); Serial.println (green);
  //Serial.println (rotatedelay);
}

if (state == 4 && rotate == 0 && red < 255 && millis() - rotatedelay > 1){
  red = red + fadegap;
  if (blue >= 1){
    blue = blue - fadegap;}
  if (green >= 1){
    green = green - fadegap;}
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 0 && green > 0 && millis() - rotatedelay > 1){
  green = green - fadegap;
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 0 && red == 255 && green == 0 && blue == 0 &&         millis() - rotatedelay > 1){
  rotate = 1;
}

if (state == 4 && rotate == 1 && blue < 255 && millis() - rotatedelay > 1){
  blue = blue + fadegap;
  if (red >= 1){
    red = red - fadegap;}
  if (green >= 1){
    green = green - fadegap;}
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 1 && red == 0 && green == 0 && blue == 255 &&     millis() - rotatedelay > 1){
  rotate = 2;
}

if (state == 4 && rotate == 2 && green < 255 && millis() - rotatedelay > 1){
  green = green + fadegap;
  if (red >= 1){
    red = red - fadegap;}
  if (blue >= 1){
    blue = blue - fadegap;}
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 2 && blue == 0 && red == 0 && green == 255 &&     millis() - rotatedelay > 1){
  rotate = 0;
}
}

//Solid colour
 void colorBlock(uint32_t c) { //This seems to be the way to colour the whole strip
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    }
 }

```

# Answer
> 1 votes
Before the lines

```
//rotating colours
if (state == 4){

```

You have an extra closing brace. IF that is in you real code, I'm not sure how it is compiling.

Assuming it isn't that then you might want to change you code to make it more readable. This is just part of you code from the same place mentioned before:

```
if (state == 4)
{
    if (millis() - rotatedelay > 1)
    {
        if (rotate == 0)
        {
            checkFadeGap (red, blue, green);

            if (green > 0)
            {
                green -= fadegap;
                colorBlock(strip.Color(red, blue, green));
                rotatedelay = millis();
            }//if (green > 0)
            if (red == 255  && green == 0 && blue == 0)
            {
                rotate = 1;
            }//if (red == 255)
        }
        if (rotate == 1)
        {
            checkFadeGap (blue, red, green);
            if (red == 0 && green == 0 && blue == 255)
            {
                rotate = 2;
            }//if (blue == 255)
        }
        if (rotate == 2)
        {
            checkFadeGap (green, reb, blue);
            if (red == 0  && green == 255 && blue == 0)
            {
                rotate = 0;
            }//if (green == 255)
        }
    }//if (millis() - rotatedelay > 1)
}    // end of if (state == 4)

```

This function removes some of the complexity in the code above.

```
void checkFadeGap (byte& inc, byte& dec1, byte& dec2)
{
    if (inc < 255)
    {
        inc += fadegap;
        if (dec1 > 0)
            dec1 -= fadegap;
        if  (dec2 > 0);
            dec2 -= fadegap;
        colorBlock(strip.Color(red, blue, green));
        rotatedelay = millis();
    }
}

```

---
Tags: arduino-uno, led, ir
---


# Question
Title: Can not find the download Zip button in the GitHub Page
I want to download a zip file for the following code from the GitHub. I am pretty new in the GitHub. Can anyone help me how to download the Zip folder for the following code from the GitHub library? I need the folder named StopWatch.Zip to include in the Arduino Zero library.

```
 #ifndef StopWatch_h
#define StopWatch_h
//
//    FILE: StopWatch.h
//  AUTHOR: Rob Tillaart
// PURPOSE: Simple StopWatch library for Arduino
// HISTORY: See StopWatch.cpp
//     URL: http://playground.arduino.cc/Code/StopWatchClass
//
// Released to the public domain
//

#define STOPWATCH_LIB_VERSION "0.1.5"

#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

class StopWatch
{
public:
  enum State      { RESET, RUNNING, STOPPED };
  enum Resolution { MILLIS, MICROS, SECONDS };

  explicit StopWatch(const enum Resolution res = MILLIS);
  void start();
  void stop();
  void reset();

  uint32_t value();
  uint32_t elapsed()            { return value(); };

  bool isRunning()              { return _state == StopWatch::RUNNING; };
  enum State state()            { return _state; };
  enum Resolution resolution()  { return _res; };

private:
  enum State _state;
  enum Resolution _res;

  uint32_t _starttime;
  uint32_t _stoptime;

  uint32_t (*_gettime)(void);
  static uint32_t seconds()          { return millis() / 1000; };
};

#endif
// END OF FILE

```

In case, I have attached the link for this Code below.

Link for the StopWatch.h file

# Answer
go to https://github.com/RobTillaart/Arduino and click the "Clone or download" button.

The repository contains many small libraries, not only the StopWatch library.
> -1 votes

---
Tags: arduino-zero
---


title: Arduino does not see data from nodemcu

text:
# Question
Title: Arduino does not see data from nodemcu
I’m trying to send data from a NodeMCU to an Arduino nano.

If I try to send data with one second delay - all working fine.

But if I try to send without delay or with a delay less than one second, then arduino sees data but nothing not does.

Arduino nano sketch:

```
#include <Servo.h>

Servo servo1;

int servo = 6;
int engine = 5;

void setup() {
Serial.begin(9600);
analogWrite(servo, 67);
servo1.attach(8);
}

void loop() {
if (Serial.available()) {
String model = Serial.readStringUntil(':');
i

f (model.equals("engine")){
String value = Serial.readStringUntil('c');
int power = value.toInt();
analogWrite(engine, power);
}
if (model.equals("servo")){
String value_servo = Serial.readStringUntil('c');
int power_servo = value_servo.toInt();
servo1.write(power_servo);
}
}
}

```

NodeMCU sketch:

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "my_wifi_ssid";
const char* password = "my_wifi_password";

ESP8266WebServer server(80);

void get_vars(){
if (server.argName(0) == "engine"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("engine:"+server.arg(0)+"c");
}
if (server.argName(0) == "servo"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("servo:"+server.arg(0)+"c");
}
}

void setup(void){
main_stuff();
}

void loop(void){
server.handleClient();
}

void main_stuff(){
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}

server.onNotFound(get_vars);

server.begin();
Serial.println("HTTP server started");

}

```

# Answer
> 1 votes
the newline characters from println (\r\n) stay in the serial input buffer and you read them with `Serial.readStringUntil(':');`. then the string is not "servo" but "\r\nservo"

if you wait one second with sending, the the \r\n are discarded because the readStringUntil times out one second after reading them

---
Tags: arduino-nano, nodemcu
---


title: How can I handle the millis() rollover?

text:
# Question
Title: How can I handle the millis() rollover?
I need to read a sensor every five minutes, but since my sketch also has other tasks to do, I cannot just `delay()` between the readings. There is the Blink without delay tutorial suggesting I code along these lines:

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

    // Read the sensor when needed.
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        readSensor();
    }

    // Do other stuff...
}

```

The problem is that `millis()` is going to roll over back to zero after roughly 49.7 days. Since my sketch is intended to run for longer than that, I need to make sure the rollover does not make my sketch fail. I can easily detect the rollover condition (`currentMillis < previousMillis`), but I am not sure what to do then.

Thus my question: what would be the proper/simplest way to handle the `millis()` rollover?

# Answer
> 178 votes
Short answer: do not try to “handle” the millis rollover, write rollover-safe code instead. Your example code from the tutorial is fine. If you try to detect the rollover in order to implement corrective measures, chances are you are doing something wrong. Most Arduino programs only have to manage events that span relatively short durations, like debouncing a button for 50 ms, or turning a heater on for 12 hours... Then, and even if the program is meant to run for years at a time, the millis rollover should not be a concern.

The correct way to manage (or rather, avoid having to manage) the rollover problem is to think of the `unsigned long` number returned by `millis()` in terms of modular arithmetics. For the mathematically inclined, some familiarity with this concept is very useful when programming. You can see the math in action in Nick Gammon's article millis() overflow ... a bad thing?. For the problem at hand, what's important to know is that in modular arithmetics the numbers “wrap around” when reaching a certain value – the modulus – so that 1 − modulus is not a negative number but 1 (think of a 12 hour clock where the modulus is 12: here 1 − 12 = 1).

For those who do not want to go through the computational details, I offer here an alternative (hopefully simpler) way of thinking about it. It is based on the simple distinction between *instants* and *durations*. As long as your tests only involve comparing durations, you should be fine.

**Note on micros()**: Everything said here about `millis()` applies equally to `micros()`, except for the fact that `micros()` rolls over every 71.6 minutes, and the `setMillis()` function provided below does not affect `micros()`.

## Instants, timestamps and durations

When dealing with time, we have to make the distinction between at least two different concepts: *instants* and *durations*. An instant is a point on the time axis. A duration is the length of a time interval, i.e. the distance in time between the instants that define the start and the end of the interval. The distinction between these concepts is not always very sharp in everyday language. For example, if I say “*I will be back in five minutes*”, then “*five minutes*” is the estimated *duration* of my absence, whereas “*in five minutes*” is the *instant* of my predicted coming back. Keeping the distinction in mind is important, because it is the simplest way to entirely avoid the rollover problem.

The return value of `millis()` could be interpreted as a duration: the time elapsed from the start of the program until now. This interpretation, however, breaks down as soon as millis overflows. It is generally far more useful to think of `millis()` as returning a *timestamp*, i.e. a “label” identifying a particular instant. It could be argued that this interpretation suffers from these labels being ambiguous, as they are reused every 49.7 days. This is, however, seldom a problem: in most embedded applications, anything that happened 49.7 days ago is ancient history we do not care about. Thus, recycling the old labels should not be an issue.

## Do not compare timestamps

Trying to find out which among two timestamps is greater than the other does not make sense. Example:

```
unsigned long t1 = millis();
delay(3000);
unsigned long t2 = millis();
if (t2 > t1) { ... }

```

Naively, one would expect the condition of the `if ()` to be always true. But it will actually be false if millis overflows during `delay(3000)`. Thinking of t1 and t2 as recyclable labels is the simplest way to avoid the error: the label t1 has clearly been assigned to an instant prior to t2, but in 49.7 days it will be reassigned to a future instant. Thus, t1 happens both *before* and *after* t2. This should make clear that the expression `t2 > t1` makes no sense.

But, if these are mere labels, the obvious question is: how can we do any useful time calculations with them? The answer is: by restricting ourselves to the only two calculations that make sense for timestamps:

1. `later_timestamp - earlier_timestamp` yields a duration, namely the amount of time elapsed between the earlier instant and the later instant. This is the most useful arithmetic operation involving timestamps.
2. `timestamp ± duration` yields a timestamp which is some time after (if using +) or before (if −) the initial timestamp. Not as useful as it sounds, since the resulting timestamp can be used in only two kinds of calculations...

Thanks to modular arithmetics, both of these are guaranteed to work fine across the millis rollover, at least as long as the delays involved are shorter than 49.7 days.

## Comparing durations is fine

A duration is just the amount of milliseconds elapsed during some time interval. As long as we do not need to handle durations longer than 49.7 days, any operation that physically makes sense should also make sense computationally. We can, for example, multiply a duration by a frequency to get a number of periods. Or we can compare two durations to know which one is longer. For example, here are two alternative implementations of `delay()`. First, the buggy one:

```
void myDelay(unsigned long ms) {          // ms: duration
    unsigned long start = millis();       // start: timestamp
    unsigned long finished = start + ms;  // finished: timestamp
    for (;;) {
        unsigned long now = millis();     // now: timestamp
        if (now >= finished)              // comparing timestamps: BUG!
            return;
    }
}

```

And here is the correct one:

```
void myDelay(unsigned long ms) {              // ms: duration
    unsigned long start = millis();           // start: timestamp
    for (;;) {
        unsigned long now = millis();         // now: timestamp
        unsigned long elapsed = now - start;  // elapsed: duration
        if (elapsed >= ms)                    // comparing durations: OK
            return;
    }
}

```

Most C programmers would write the above loops in a terser form, like

```
while (millis() < start + ms) ;  // BUGGY version

```

and

```
while (millis() - start < ms) ;  // CORRECT version

```

Although they look deceptively similar, the timestamp/duration distinction should make clear which one is buggy and which one is correct.

## What if I really need to compare timestamps?

Better try to avoid the situation. If it is unavoidable, there is still hope if it is known that the respective instants are close enough: closer than 24.85 days. Yes, our maximum manageable delay of 49.7 days just got cut in half.

The obvious solution is to convert our timestamp comparison problem into a duration comparison problem. Say we need to know whether instant t1 is before or after t2. We choose some reference instant in their common past, and compare the durations from this reference until both t1 and t2. The reference instant is obtained by subtracting a long enough duration from either t1 or t2:

```
unsigned long reference_instant = t2 - LONG_ENOUGH_DURATION;
unsigned long from_reference_until_t1 = t1 - reference_instant;
unsigned long from_reference_until_t2 = t2 - reference_instant;
if (from_reference_until_t1 < from_reference_until_t2)
    // t1 is before t2

```

This can be simplified as:

```
if (t1 - t2 + LONG_ENOUGH_DURATION < LONG_ENOUGH_DURATION)
    // t1 is before t2

```

It is tempting to simplify further into `if (t1 - t2 < 0)`. Obviously, this does not work, because `t1 - t2`, being computed as an unsigned number, cannot be negative. This, however, although not portable, does work:

```
if ((signed long)(t1 - t2) < 0)  // works with gcc
    // t1 is before t2

```

The keyword `signed` above is redundant (a plain `long` is always signed), but it helps make the intent clear. Converting to a signed long is equivalent to setting `LONG_ENOUGH_DURATION` equal to 24.85 days. The trick is not portable because, according to the C standard, the result is *implementation defined*. But since the gcc compiler promises to do the right thing, it works reliably on Arduino. If we wish to avoid implementation defined behavior, the above signed comparison is mathematically equivalent to this:

```
#include <limits.h>

if (t1 - t2 > LONG_MAX)  // too big to be believed
    // t1 is before t2

```

with the only problem that the comparison looks backwards. It is also equivalent, as long as longs are 32-bits, to this single-bit test:

```
if ((t1 - t2) & 0x80000000)  // test the "sign" bit
    // t1 is before t2

```

The last three tests are actually compiled by gcc into the exact same machine code.

## How do I test my sketch against the millis rollover

If you follow the precepts above, you should be all good. If you nevertheless want to test, add this function to your sketch:

```
#include <util/atomic.h>

void setMillis(unsigned long ms)
{
    extern unsigned long timer0_millis;
    ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        timer0_millis = ms;
    }
}

```

and you can now time-travel your program by calling `setMillis(destination)`. If you want it to go through the millis overflow over and over again, like Phil Connors reliving Groundhog Day, you can put this inside `loop()`:

```
// 6-second time loop starting at rollover - 3 seconds
if (millis() - (-3000) >= 6000)
    setMillis(-3000);

```

The negative timestamp above (-3000) is implicitly converted by the compiler to an unsigned long corresponding to 3000 milliseconds before the rollover (it is converted to 4294964296).

## What if I really need to track very long durations?

If you need to turn a relay on and turn it off three months later, then you really need to track the millis overflows. There are many ways to do so. The most straightforward solution may be to simply extend `millis()` to 64 bits:

```
uint64_t millis64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

```

This is essentially counting the rollover events, and using this count as the 32 most significant bits of a 64 bit millisecond count. For this counting to work properly, the function needs to be called at least once every 49.7 days. However, if it is only called once per 49.7 days, for some cases it is possible that the check `(new_low32 < low32)` fails and the code misses a count of `high32`. Using millis() to decide when to make the only call to this code in a single "wrap" of millis (a specific 49.7 day window) could be very hazardous, depending on how the time frames line up. For safety, if using millis() to determine when to make the only calls to millis64(), there should be at least two calls in every 49.7 day window.

Keep in mind, though, that 64 bit arithmetic is expensive on the Arduino. It may be worth to reduce the time resolution in order to stay at 32 bits.

# Answer
> 36 votes
**TL;DR** Short version:

An `unsigned long` is 0 to 4,294,967,295 (2^32 - 1).

So lets say `previousMillis` is 4,294,967,290 (5 ms before rollover), and `currentMillis` is 10 (10ms after rollover). Then `currentMillis - previousMillis` is actual 16 (not -4,294,967,280) since the result will be calculated as an **unsigned** long (which can't be negative, so itself will roll around). You can check this simply by:

`Serial.println( ( unsigned long ) ( 10 - 4294967290 ) ); // 16`

So the above code will work perfectly fine. The trick is to always calculate the time difference, and not compare the two time values.

# Answer
> 6 votes
I loved this question, and the great answers it generated. First a quick comment on a previous answer (I know, I know, but I don't have the rep to comment yet. :-).

Edgar Bonet's answer was amazing. I've been coding for 35 years, and I learned something new today. Thank you. That said, I believe the code for *"What if I really need to track very long durations?"* breaks unless you call millis64() at least once per rollover period. Really nitpicky, and unlikely to be an issue in a real-world implementation, but there you go.

Now, if you really did want timestamps covering any sane time range (64-bits of milliseconds is about half a billion years by my reckoning), it looks simple to extend the existing millis() implementation to 64 bits.

These changes to attinycore/wiring.c (I'm working with the ATTiny85) seem to work (I'm assuming the code for other AVRs is very similar). See the lines with the //BFB comments, and the new millis64() function. Clearly it's going to be both bigger (98 bytes of code, 4 bytes of data) and slower, and as Edgar pointed out, you almost certainly can accomplish your goals with just a better understanding of unsigned integer math, but it was an interesting exercise.

```
volatile unsigned long long timer0_millis = 0;      // BFB: need 64-bit resolution

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long long m = timer0_millis;       // BFB: need 64-bit resolution
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }

    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;
}

// BFB: 64-bit version
unsigned long long millis64()
{
    unsigned long long m;
    uint8_t oldSREG = SREG;

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;

    return m;
}

```

# Answer
> 1 votes
Wrap the `millis()` in a class!

Logic:

1. Use id's instead of `millis()` directly.
2. Compare reversals using id's. This is clean and rollover independent.
3. For specific applications, to calculate exact difference between two id's, keep track of reversals and stamps. Calculate the difference.

Keeping track of reversals:

1. Update a local stamp periodically faster than `millis()`. This will help you find out if `millis()` has overflown.
2. The period of the timer determines accuracy

```
class Timer {

public:
    static long last_stamp;
    static long *stamps;
    static int *reversals;
    static int count;
    static int reversal_count;

    static void setup_timer() {
        // Setup Timer2 overflow to fire every 8ms (125Hz)
        //   period [sec] = (1 / f_clock [sec]) * prescale * (255-count)
        //                  (1/16000000)  * 1024 * (255-130) = .008 sec

        TCCR2B = 0x00;        // Disable Timer2 while we set it up

        TCNT2  = 130;         // Reset Timer Count  (255-130) = execute ev 125-th T/C clock
        TIFR2  = 0x00;        // Timer2 INT Flag Reg: Clear Timer Overflow Flag
        TIMSK2 = 0x01;        // Timer2 INT Reg: Timer2 Overflow Interrupt Enable
        TCCR2A = 0x00;        // Timer2 Control Reg A: Wave Gen Mode normal
        TCCR2B = 0x07;        // Timer2 Control Reg B: Timer Prescaler set to 1024

        count = 0;
        stamps = new long[50];
        reversals = new int [10];
        reversal_count =0;
    }

    static long get_stamp () {
        stamps[count++] = millis();
        return count-1;
    }

    static bool compare_stamps_by_id(int s1, int s2) {
        return s1 > s2;
    }

    static long long get_stamp_difference(int s1, int s2) {
        int no_of_reversals = 0;
        for(int j=0; j < reversal_count; j++)
        if(reversals[j] < s2 && reversals[j] > s1)
            no_of_reversals++;
        return stamps[s2]-stamps[s1] + 49.7 * 86400 * 1000;
    }

};

long Timer::last_stamp;
long *Timer::stamps;
int *Timer::reversals;
int Timer::count;
int Timer::reversal_count;

ISR(TIMER2_OVF_vect) {

    long stamp = millis();
    if(stamp < Timer::last_stamp) // reversal
        Timer::reversals[Timer::reversal_count++] = Timer::count;
    else
        ; // no reversal
    Timer::last_stamp = stamp;
    TCNT2 = 130;     // reset timer ct to 130 out of 255
    TIFR2 = 0x00;    // timer2 int flag reg: clear timer overflow flag
};

// Usage

void setup () {
    Timer::setup_timer();

    long s1 = Timer::get_stamp();
    delay(3000);
    long s2 = Timer::get_stamp();

    Timer::compare_stamps_by_id(s1, s2); // true

    Timer::get_stamp_difference(s1, s2); // return true difference, taking into account reversals
}

```

Timer credits.

---
Tags: programming, time, millis
---


# Question
Title: Arduino Zero Compiling Issues for "Test-AnalogReadFast-SAM"
```
#include <Streaming.h>
#include "StopWatch.h"
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"

const byte adcPin = A1;

void setup(void)
{ Serial.begin(9600);
  while(!Serial);
  Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
  for(int i=0; i<10; i++) testAnalogRead();
}

void testAnalogRead()
{ static Stopwatch Stopwatch(micros);
  //delay(1000);

  stopwatch.start();
  int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
  stopwatch.stop(); int t1 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc2 = analogRead(adcPin); // 425us on SAMD21
  stopwatch.stop(); int t2 = stopwatch.interval;

  analogReadResolution(10);
  stopwatch.start();
  int adc3 = analogReadFast(adcPin); // 23us on SAMD21
  stopwatch.stop(); int t3 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc4 = analogReadFast(adcPin); // 24us on SAMD21
  stopwatch.stop(); int t4 = stopwatch.interval;

  Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
  analogReadResolution(10); // restore default
}

void loop(void)
{
}

```

Hi I have to run this code in the Arduino Zero. When I try to compile this code it throws the following error:

Error:

```
In file included from /Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino:2:0:
/Users/RAJU/Documents/Arduino/libraries/Streaming/Streaming.h:102:15: warning: unused parameter 'arg' [-Wunused-parameter]
 inline Print &operator <<(Print &obj, _EndLineCode arg)

               ^
/Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino: In function 'void testAnalogRead()':
Test_AnalogReadFast_SAM:17: error: 'Stopwatch' does not name a type
 { static Stopwatch Stopwatch(micros);
          ^
Test_AnalogReadFast_SAM:20: error: 'stopwatch' was not declared in this scope
   stopwatch.start();
   ^
exit status 1
'Stopwatch' does not name a type

```

Any helps are greatly appreciated

# Answer
> 0 votes
The compiler doesn't know the type `Stopwatch`. You have a typo there. A short look into the header file (`StopWatch.h`) shows you, that it is `StopWatch` and not `Stopwatch`. You need a big W there.

Next time first try to investigate yourself. Obviously you didn't do anything before asking here. Next time try it and then, if you cannot find the problem, then write in your question what you have tried.

---

I was able to compile the following program in my Arduino IDE for Arduino/Genuino Zero:

```
#include "StopWatch.h"

void setup() {
  static StopWatch Stopwatch(StopWatch::MICROS);
}

void loop() {
}

```

The `StopWatch` library comes from this Github page. It is the same, that you linked within your other language with the same code, so I assume, that you use it.

For future questions: It is better to directly provide links to all used libraries, that are not part of the Arduino IDE.

---
Tags: arduino-zero
---


# Question
Title: post data from node mcu to my sql database
```
#include <ESP8266WiFi.h>

const char* ssid = "xxxx";
const char* password = "xxxxxxxxxx";

const char* host = "192.168.43.18";
const int ldr = A0;
int val = 0;

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

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

void loop()
{
  val = analogRead(ldr);
  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /past.php HTTP/1.1");
    client.println("Host: 192.168.43.10");
    client.print(val);
    Serial.println(val);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

```

I have uploaded this code to node mcu but it get's working but the uploaded data in my database is not shown please any one help me out

# Answer
My corrected code working code:

```
#include <ESP8266WiFi.h>

const char* ssid = "vathsal";
const char* password = "1234567890";

const char* host = "wwwkprstaffcom.000webhostapp.com";
const int ldr = A0;
int val = 0;
String data;
void setup()
{
  Serial.begin(9600);
  Serial.println();

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

void loop()
{
  val = analogRead(ldr);
  data = "ldr=";

  data.concat(val);
  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /add.php HTTP/1.1");
    client.println("Host: wwwkprstaffcom.000webhostapp.com");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    Serial.println(val);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

```
> 1 votes

# Answer
You are using the WIFIClient to send data to a HTTP server. I don't think the WiFiClient knows how to format HTTP requests properly so you need to do that. I think there is a HTTPClient which may do more for you.

There is a blank line between the header and body of the message and a blank line at the end of the body. you need to have a line that say \`client.println();

Does the "SQL server" accept a message that just contains a number? How does it know what the number relates to? If you have some PHP site on the front if the DBS that handles all that then please ignore that question.

You might want to see if you can run Wireshark (or similar) on your PC and see what the MCU is sending, you might also want to look at the Chrome add ins, I believe there are some where you can create raw packets and send those to you server to ensure it responds as expected.

As a final resort you could probably knock up a very quick and dirty C# program using Visual Studio Community Edition (Free) and get that to send a packet to the server. Using this in combination with wireshark might be easier than using the MCU until you know what you should be doing.
> 0 votes

# Answer
You are not actually posting any data. After client.println("POST /past.php HTTP/1.1"); Add another line(s) like ... client.println("?myvar=65dcsagh&anothervar=ghsadjkj78");

Also the page on the server (past.php) needs to be able to get and process the sent data. If using PHP will be soemthing like.. $data = $\_GET\[myvar\]; And then the PHP code need to connect to your SQL database and insert it using mySQL
> 0 votes

---
Tags: nodemcu
---


# Question
Title: Error using SD card module: no matching function for call to
This code is just a test code to write a file to an SD card using an SD card module. When I run the code, I get this error message and I'm not sure what to do to fix the code: `no matching function for call to'SDLib::SDClass::exists(SDLib::File&)'`.

```
#include <SD.h>
#include <SPI.h>

int cs = 10;

File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {

  }
  Serial.println("Initializing SD card...");
  Serial.println();

  pinMode(cs, OUTPUT);
  pinMode(SS, OUTPUT);
  if (!SD.begin(cs)) {
    Serial.println("SD did not initiliaze");
    while (1) ;
  }
  Serial.println("SD initialized.");

  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);

     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
  else{
    myTest = SD.open(myTestName, FILE_WRITE);
    myTest.println("Another Line of Data");
    myTest.flush();

  }

  Serial.println("Done Writing");

}

void loop()
{

}

```

# Answer
> 0 votes
The function is defined as

```
// Methods to determine if the requested file path exists.
boolean exists(char *filepath);

```

Source: https://github.com/adafruit/SD/blob/master/SD.h#L90

You call it with a `File` object, not the filename. You probably mixed up the variable names:

```
File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  //[...]
  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);
     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
//..

```

Just exchange `myTest` for `myTestName` in the `SD.exists()` call.

---
Tags: sd-card
---


# Question
Title: Understanding how to power objects with a relay (featherwing, feather huzzah)
I am trying to learn how to control a relay to power various household objects. I bought a power relay shield for an adafruit feather huzzah, and I have just set up the arduino blink sketch to provide conditional high / low to a control pin on the relay:

```
const int ledPin = 13;

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

void loop {
    digitalWrite(ledPin, LOW);
    delay(1000);
    digitalWrite(ledPin, HIGH);
    delay(2000);
}

```

If I connect a jumper from the `signal` pin hole on the board to the appropriate `ledPin` (13), I can hear the relay switching on and off. If I use a multimeter in continuity mode, it will register continuity at the appropriate times in the blink sketch (HIGH or LOW).

I might be confused on how the relay should be wired, but shouldn't attaching wires from two of the terminal blocks deliver power to something? If I use a multimeter on wires coming out of the blocks, I don't detect any current. I've tried powering a simple led, but I can't get it to light up. Here's my setup. Can anyone explain what I might be doing wrong? Does the LED need a separate power source apart from what's coming from the feather itself? (the feather is powered by a USB cable from my computer).

Thanks for any clarification anyone can provide.

BTW, here is a reference photo from Adafruit of how they have it wired.

# Answer
A relay is just a switch, that is controlled via a magnet force from coil. The power line to the relay breakout board is just used to drive enough current through this coil, since often the 20mA of a normal digital output pin aren't enough for that.

Relays are for switching big loads, that should not have contact with the microcontrollers circuit. You don't want the 230V (or 110V, depending on where you live) to find their way to the microcontroller. Also most boards can only provide a very limited amount of current. Big loads mostly need a lot of current and you don't want this big current flowing through the tiny copper traces on the board. You have to use an extra power supply for these.

So have to connect the relay like a normal switch, in series with the load you want to control with it. Also keep in mind the difference between the normally open and normally closed output of the relay. Here is a schematic, to explain further, what circuit you need:

simulate this circuit – Schematic created using CircuitLab

You provide power for the coil of the relay from the two power lines of the ESP (3.3V and GND). The digital pin, that you use for switching is just a signal. It only has to provide a very minimal amount of current. The board itself has a driver circuit to activate the coil. Here I used a simple MOSFET, but I actually don't know, what driver circuit is really used on that board.

If enough current is flowing through the coil, the switch inside the relay changes from NC (normally closed/connected) pin to NO (normally open) pin, closing the electrical circuit, that provide the big load (here a light bulb) with current from an external power supply (like a wall outlet). The two circuits are NOT electrically connected, so you won't have to deal with potential high voltage and current on the ESP side.

---

And in your sketch you don't ever turn the LED off. I assume this is just an error from copy/paste.
> 2 votes

# Answer
I don't see a current limit resistor in the LED circuit, 270 to 470 Ohms, must have. Also, there is no power supply for the LED, the relay is just a short circuit across the LED.
> 0 votes

---
Tags: esp8266, power, adafruit, relay
---


# Question
Title: Arduino Uno programed from a Nvidia Jetson tx2
I'm trying to program my Arduino Uno with a Jetson tx2 and get the error

```
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

```

The serial port is set to /dev/ttyS0

dmesg when the Arduino is plugged in returns

```
[78222.855639] usb 1-1: USB disconnect, device number 60
[78224.468387] usb 1-1: new full-speed USB device number 61 using xhci-tegra
[78224.605794] usb 1-1: feature bit otg_vbus_off set
[78224.610575] usb 1-1: New USB device found, idVendor=2341, idProduct=0043
[78224.617365] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[78224.624750] usb 1-1: Manufacturer: Arduino (www.arduino.cc)
[78224.630502] usb 1-1: SerialNumber: 55739323237351306122
[78224.636529] usb 1-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[78224.646057] xhci-tegra 3530000.xhci: tegra_xhci_mbox_work mailbox command 6

```

lsusb returns

```
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 054: ID 413c:2107 Dell Computer Corp.
Bus 001 Device 065: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

```

# Answer
> 1 votes
The version of the Arduino IDE contained in the Jetson repositories is buggy on the Jetson TX2 with Jetpack 3.2+ and the Arduino IDE in the repository is rather old. Instead, try the beta related to Github Issue #7302. This beta should work with the Jetson and other aarch64 platforms. Many thanks to the wonderful people working to support this platform.

## Steps

After downloading and unpackaging the build, perform the following steps:

```
#Install the OpenJDK Dependencies
sudo apt-get install openjdk-8-jre openjdk-8-jdk

#Remove the Packaged Java Folder
cd ${PATH}/arduino-PR-beta1.9-BUILD-69
sudo rm -r java

#Add armhf Architecture to Package Manager
sudo dpkg --add-architecture armhf
sudo apt-get update
sudo apt-get install libc6:armhf libstdc++6:armhf

#Install the Arduino IDE
sudo ./install.sh
sudo ./arduino-linux-setup.sh

#Reboot

```

## Notes

* The script `arduino-linux-setup.sh` handles the permissions for the IDE to talk to ttyACM0, updates the udev rules, and removes the pesky Modem Manger.
* The armhf packages are necessay to prevent ctags from crashing.
* If you are still having issues with CDC/ACM, install the module using the scripts from JetsonHacks

# Answer
> 0 votes
The device *should* be `/dev/ttyACM0`, *not* `/dev/ttyS0`.

Since it doesn't provide you with that device it rather looks like it doesn't have the CDC/ACM device drivers installed or loaded.

Depending on what distribution of Linux you're running on there you may need to install additional packages (you certainly do for OpenWRT, but I have no clue what that device is you're using or what it's running).

# Answer
> 0 votes
When you built your Jenson kernel, did you enable the CDC/ACM driver using menuconfig?

From Arduino Playground:

> If you configured your own kernel, the driver is either under "Device Drivers =\> USB Support =\> USB Serial Converter Support =\> USB FTDI Single Port Serial Driver" or "Device Drivers =\> USB Support =\> USB Modem (CDC ACM) support". Select \[Y\], to have it "built in" to the kernel or \[M\] to have it built as a module.

I'm not familiar with Arduino and whether it would show up as `/dev/ttyUSB0` or `/dev/ttyACM0` per @Majenko.

---
Tags: serial, programming
---


# Question
Title: Where can I find the code for Arduino's "attachInterrupt"?
Where can I find the code for Arduino's `attachInterrupt` function?

A search on the Arduino's Github repo yielded nothing.

I suspect it might be a wrapper for some avr-libc function but nothing in the avr-libc docs stands out to me...

# Answer
> 4 votes
It's in the core in WInterrupts.c

On my install it's at:

arduino-1.8.5/hardware/arduino/avr/cores/arduino/WInterrupts.c

---
Tags: programming, interrupt
---


# Question
Title: Why this code for ESP8266 goes into STA+AP mode?
I'm using Arduino IDE 1.6 nightly with Generic ESP8266 Board.

Why this code runs in mesh mode instead of simply connecting to my wifi? My goal is to test out MDNS, but so far I found this:

To my understanding such code should just connect to my wifi and I would then be able to navigate to http://esp8266-webupdate.local/update, am I missing something?

**output (note STA+AP)**

```
Booting Sketch...
......
Connected, IP address: 192.168.1.20
Mode: STA+AP
PHY mode: N
Channel: 10
AP id: 0
Status: 5
Auto connect: 1

```

**code**

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>

const char* host = "esp8266-webupdate";
const char* ssid = "myhomeap";
const char* password = "blabla";

ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

void setup(void){

  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

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

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  WiFi.printDiag(Serial);
  MDNS.begin(host);

  httpUpdater.setup(&httpServer);
  httpServer.begin();

  MDNS.addService("http", "tcp", 80);
  Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
}

void loop(void){
  httpServer.handleClient();
}

```

# Answer
It goes into STA+AP mode because your code is telling it to do that.

If you want it to just go into STA mode then your line:

`WiFi.mode(WIFI_AP_STA);`

should be

`WiFi.mode(WIFI_STA);`
> 3 votes

---
Tags: esp8266, wifi
---


# Question
Title: Timer frequency calculation for UNO/Atmega328
I must be overwrought or something... I just can't get the calculation of the timer frequency right. I have a 16 MHz crystal on the Atmega328. I want 1 kHz timer interrupt rate. So I chose prescaler = 64 and counter top = 249, that is

fTimer = fCPU/prescaler/(top+1) = 16 MHz/64/250 = 1 kHz

But my oscilloscope shows 2 kHz... !? Why?

I have read Timer2 Compare Interrupt not working as expected but the accepted answer doesn't make it better. There the frequency is half as high whereas mine is twice as high as expected.

Code:

```
const int signalLED = 1; //14;

void setup()
{
  pinMode(signalLED, OUTPUT);
  digitalWrite(signalLED, LOW);

  TCCR2A = 0; // set TCCR2A register to 0
  TCCR2B = 0; // set TCCR2B register to 0
  TCNT2  = 0; // reset counter
  OCR2A = 249; // top value in CTC mode
  TCCR2A |= (1 << WGM21); // enable timer2 CTC mode
  TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2
  TIMSK2 |= (1 << OCIE2A); // enable timer2 compare interrupt
  sei(); // allow interrupts
}

ISR(TIMER2_COMPA_vect)
{
  // generate peak
  digitalWrite(signalLED, HIGH);
  digitalWrite(signalLED, LOW);
}

void loop()
{
}

```

# Answer
> 1 votes
Your comment:

```
TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2

```

doesn't match the actual setting (= 1/32)

Also there are some issues with setting Timer2 CTC mode, it's better to set mode, then OCR2A + TCNT2 + interrupts and then Prescaler to start the timer. It behaves as there is OCR2A=0, so the frequency is much higher than expected.

---
Tags: interrupt, timers
---