title: Arduino or XBee unique identifier?

text:
# Question
Title: Arduino or XBee unique identifier?
Is there anything built into the Arduino Uno or the XBee Pro 2 radio module that I can poll within my Arduino script to act as a unique identifier? Mac address or otherwise? If anyone has a code snippet that can do this it'd be extremely appreciated.

Currently my Arduino nodes are broadcasting only to my node.js server, but my server is broadcasting to all the nodes, so if they're all waiting to be assigned an identifier number through the handshake function I wrote, they all receive the same one. If I stagger powering them up this is avoided and they each get a unique ID, but I hope there exists a cleaner solution.

# Answer
> 1 votes
When programming the Uno's, you could write identifying values into particular EEPROM bytes. To automate the process, write a development-system program to produce serial-numbered HEX files, with the serial number counting up each time the program runs.

For example, if you store IDs into byte 0x1E of EEPROM, the serial number file would look as follows when the serial number is 0x23:

```
:01001E0023BE
:00000001FF

```

The first line in the above file says 01 bytes of payload, stored at address 001E, record type 00 (data), payload byte 23, checksum BE. See wikipedia's Intel HEX article for further explanation of HEX file format. In brief, each time the serial number byte goes up by one, the checksum byte goes down by one.

To program a serial number byte into EEPROM from a file called `SNfile.hex`, issue a command like the following.

```
avrdude -p atmega328p -c arduino -P /dev/ttyUSB1 -b57600 -U eeprom:w:SNfile.hex:i

```

See the `avrdude` manpage for explanation.

In your sketch, use EEPROM.read(address) to read a unit's serial number. For example:

```
#include <EEPROM.h>
byte mySN = EEPROM.read(0x1E);

```

\[Note, regarding your question about “anything built in... to act as a unique identifier”, I once spent quite a while looking for such a thing on Uno, Nano, and Mega2560 Arduinos, and found nothing. I haven't looked at XBee radio modules for such data.\]

---
Tags: arduino-uno, communication, xbee, mac-os
---


# Question
Title: How do I turn off a 12V 3A RGB LED strip?
I'm trying to understand how to control an RGB LED strip, I set up all the `TIP120` (because I could get my hands on an n-channel mosfet), if I power everything in this way I can change colours and everything:

but now I'm facing a dilemma now, whats the correct way to manage to switch my power strip ON/OFF based on an input from a pir sensor? I mean, how can I handle 12V 3A (requested by my led strip), how do I correctly wire my Arduino up in order to make it switch the LED strip ON/OFF?

# Answer
> 5 votes
That's pretty simple: when you turn off all the colours you are actually turning off the entire strip with very minimum leakage current in each of the three FETs.

---
Tags: power, voltage-level, rgb-led
---


# Question
Title: Connect an Arduino directly to RGB LED strip
I am totally new in this area. I have an Arduino mega 2560 and I have this LED RGB Strips. I would like to know if there is any way of connecting the Strips directly to the arduino. The strip has already solded 4 cables:

* one cable on 12V
* one cable on G
* one cable or R
* one cable on B

I don't have additional equipment. Also, I can't find anything online which uses the same type of strips as mine. Many thanks.

# Answer
Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain. The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.

You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).

Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).

As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.
> 1 votes

# Answer
https://www.amazon.com/Channels-DMX-512-Decoder-Converter-Light/dp/B0083RBGJG or 3 power FETs and https://www.amazon.com/Power-Adapter-Transformers-Supply-Output/dp/B00DKSI0S8/ref=pd\_lpo\_328\_bs\_t\_2?ie=UTF8&psc=1&refRID=SF0CXGBQYRBBRAQT2FN1

You can use the logic level ports to drive Logic level power MoSFET switches or use a RS85 IC to communicate to a DMX-512 interface special effects driver to RGB.

Other options include Use 5A PWM 3channel dimmer purchased on line with 12V- 14.5Vmax PSU \>40W per 5m reel string .

e.g. Laptop universal 65W charger ($30) with 14V -16V setting. and long AWG18 wire with 1-2V drop

(comments)

* You start by improving your question with details on what you want to do with the interface.
* if you want guidance shopping for a LED driver , just say so or ask for details, it's not hard
> 1 votes

# Answer
No. Two reasons:

1. The Arduino can only supply about 40 mA per pin max. Your LEDs will require about 1000 mA or so per channel (based on the 3 A PSU supplied with the unit).
2. The LEDs are individually addressed and codes have to be transmitted to them. This requires code to be written for the micro and an interface to the data line.

*Figure 1. The IR controller.*

The IR controller supplied with the kit interfaces the power and provides the data signal to the strip.

The simplest way to control from your micro is to fit it with an IR (infra-red) LED and transmit the codes to the IR controller. This method also makes it almost impossible for you to damage your micro or the LED strip as the only connection between them will be by infra-red light.

Someone has probably figured this out already and you may find the complete code for an Arduino in a web search.
> 0 votes

# Answer
No. there is no way to connect those directly.

You can use Solid state relays (SSR) for this. I did it before and was able to make different colors.

Connect an external 12v directly 12V pin in srips.

Use SSR to connect from GPIO to LED R G and B pins
> 0 votes

# Answer
You can use a couple of relays on the arduino outputs, and control it from there.
> -1 votes

---
Tags: rgb-led
---


# Question
Title: Is the used clock for the Baudrate generator adjustable on an arduino due?
I hope to find some answers or pointers to a boggling task of mine:

Having an Arduino DUE that I want to push to its serial limits, I came up with the idea of hooking it up to my rPi via serial at least at 921600 baud.

Technically both seem capable of that. A loopback test with the rPi was successful up to 921600 and I've managed to get a "good" quality transmission up to 576000 bps already (error-rate should be around 1,3%), but anything higher gets problematic.

Problems:

* DebugConsole, CuteCom and minicom don't have support for any speeds in-between, so either 921600 works or it doesn't
* minicom supports 1.000.000 baud, but this would still mean a ~5% error-rate, which is according to my calculations and tests, but they are in question here as well ...

---

From the Atmel Doc I've got

```
BaudRate = MCK ⁄ CD × 16

```

From that I've derived that with the 84MHz Due a baudrate of 1.050.000 would be the actual rate I should aim for, as CD must(?) be an INT.

```
1050000 = 84000000 / 5 * 16

```

Questions:

* Is my assumption of an optimal 1.050.000 baudrate right?
* Is it possible to use a different clock for the baudrate generator than the 84MHz?

Remarks:

A Clock of 14,7456MHz should be optimal as it is equal to 921600 * 16.

I am using TXD/RXD1 on the Due.

The Due is transmitting on 921600 but the data is scrambled due to the errors.

In case somebody is wondering, my hope is that it is easier to adjust the arduino to 921600 baud than it is to setup a tool and configure the rPi to support 1050000 baud - but I am working both ways, only that with the rPi I know what to do ..

# Answer
The clock of the transmitter and receiver have to be matched.

**In theory**, the worst case error tolerable is 1/2 bit per byte. For the 10 bit byte (1 start, 8 data, 1 stop) that leads to a +/- 5% clock error tolerance that you will find reported. Note that this actually depends on the specific UART implementation, either chip or internal. There are various methods of sampling that make some UART's better than others. It is common to sample in the middle, but some chips have methods to improve noise rejection.

For the receiver side, do not rely on what the terminal program is showing you. Few applications would manipulate the clock directly; they commonly just call an API with an enumerator for the speed. You need to know exactly what hardware the receiver side has and its clock.

**In practice**, the theoretical limit is not going to work. At high data rates, the noise on the cable will eat away at that safe margin. More common recommendations will say +/- 1% which allows for noise on the edges of the bit transitions.

The noise on the signal is important at these data rates. You indicate you are using TXD/RXD which is just logic level. You cannot connect logic level any significant distance. If the two are directly next to each other with excellent attention to wiring, you might have a chance. Adding transceivers will help your chances significantly.

Also, note that changing to 7 bits helps. Do you need 8 bit data?

So in summary: \- The receiver is more important than the transmitter, but they both have to match. If you can't find a match of clocks to 1%, you will have data errors. \- At these speeds, the cabling and connection is critical.

This article at Maxim is a good starter Maxim "Determining Clock Accuracy Requirements for UART Communications.
> 2 votes

# Answer
Yes you can set the Master clock slightly slower and use Serial.begin(921600) and it will come out close enough to work with a HC05 bluetooth module set to 921600. // multiplier 0x25 , divider 0x3 REG\_CKGR\_PLLAR=0x20253F03;// works at 921600 this will throw all other timings off but you can always compensate by changing the master clock definition in the Due ? .h file. if you want to print out of Serial0 port this will need to be set to 921600 also and you can monitor it with something like realterm that can do higher baud rates.

Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A.pdf
> 0 votes

---
Tags: serial, arduino-due, uart
---


title: Ramping a stepper motor

text:
# Question
Title: Ramping a stepper motor
I at the moment trying smoothly move a stepper motor. The problem with the stepper motor, is that it makes a high pitch noise while it moves, or sometime a crackling noise from the motor.

So i tried ramping up the frequency of the step signal, which seemed to help a bit but not perfect. Then I tried micro stepping rather than full stepping, which also helped a bit but still, the noise is very clear.

The motor I am using is a PK244-01A And the driver it is connected to is this one

I am not at all sure if the ramping I do is either too steep, or completely incorrect, but here is the code that controls the motor.

```
void stepper_motor::step_pwm()
{

    digitalWrite(en_pin,HIGH);

    delay(0.005);

    digitalWrite(dir_pin,HIGH);
    //LOW  - Move towards the sensor
    //HIGH -  Move away from the sensor

    delay(0.005);
    int increment = 0;
    int step_count = 0;
    while(step_count <= max_step)
    {
      digitalWrite(step_pin,LOW);
      delayMicroseconds(2000);
      digitalWrite(step_pin,HIGH);
      delayMicroseconds(2000-increment);
      step_count++;

      if(step_count >= 1)
      {
        increment++;
        step_count = 0;
      }
    }

}

```

Anything I could do to make the noise of the motor less significant?

# Answer
I had a similar issue once before. It actually matters a lot to properly ramp up your stepper motor. Especially under load if you ramp up too steep you can loose steps.

Since you are already using the arduino environment I suggest you could use the AccelStepper library.

I lets you set the acceleration and max. speed parameters nicely and uses a properly calculated ramp.
> 2 votes

# Answer
You need to be using the adjusted delay for both the high and the low part of the signal. Also, what happens when the variable "increment" is larger than 2000? Nothing good, for certain. I'd personally like to be able to delay by a negative number and undo some things that are already done, but I don't think yoz can turn back time using an Arduino.
> 1 votes

---
Tags: stepper-motor
---


title: Make a stepper motor move

text:
# Question
Title: Make a stepper motor move
I am at the moment trying to make a bipolar stepper motor move. I am interfacing it through a control board, which takes the input `Step`, `Dir`, `En`, and 5V.

I am providing those input signal via an Arduino, but can't get the damn thing to move. all it does it move a step forward and backwards, like it being stuck or and tries to wiggle out of something.. What could the reason be..

Here is the Code:

```
#include "stepper_motor.h"
int max_step = 200;
stepper_motor::stepper_motor()
{
  pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin,OUTPUT);
  pinMode(dir_pin,OUTPUT);
  pinMode(en_pin,OUTPUT);

  alive_bool = true;
  position_bool = false;
  step_count = 0;
}

void stepper_motor::step_pwm()
{

  if(position_bool==true)
  {
    //Dir pin low
    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,LOW);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    int step = 0;
    while(step < max_step)
    {
      digitalWrite(step_pin,HIGH);
      delay(1);
      digitalWrite(step_pin,LOW);
      delay(1);
    }

    //digitalWrite(en_pin,LOW);
    //position_bool = false;
  }
  else
  {
    //Dir pin high
    delay(1000);
    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,LOW);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,HIGH);

    int step = 0;
    while(step < max_step)
    {
      digitalWrite(step_pin,HIGH);
      delay(1);
      digitalWrite(step_pin,LOW);
      delay(1);
    }

    //digitalWrite(en_pin,LOW);
    //position_bool = true;
  }

}

```

Updated step\_pwm():

```
void stepper_motor::step_pwm()
{
    //Start -  En Low , DIR HIGH, STEP high
    //init configuration!
    digitalWrite(step_pin, HIGH);
    digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,LOW); // Previous LOW

    delay(0.005);

    //T1-  En HIGH , DIR HIGH, STEP HIGH
    //Enable high
    //digitalWrite(step_pin, HIGH);
    //digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    //T2-  En HIGH , DIR low, STEP HIGH
    //Direction choosen
    //digitalWrite(step_pin, HIGH);
    digitalWrite(dir_pin,LOW);
    //digitalWrite(en_pin,HIGH);

    delay(0.005);
    //T2-  En HIGH , DIR low, STEP HIGH
    //STEP  step between low and high with 2.5µs between

    while(1)
    {
      digitalWrite(step_pin,LOW);
      delay(2.5);
      digitalWrite(step_pin,HIGH);
      delay(2.5);
    }

}

```

The control board i am using is a ST330-v3 The motor i am using is this one here is a little block diagram of how things are connected.

# Answer
> 2 votes
You must set EN BEFORE you set DIR. The datasheet says EN must be high for at least 5 microseconds before you set DIR. You should probably just set EN high when your program starts, then not fool with it until your program ends.

The next thing is that I don't see you incrementing the variable "step" anywhere. So, if you did get the stepper to turn, it wouldn't stop.

---

The updated code looks like it ought to work.

You should use DelayMicroseconds instead of Delay(0.005) though. Delay takes an integer instead of a decimal value, so you won't get what you expect. Curse the Arduino IDE for not throwing a fit when pass a float for an int.

---

It looks like anything working properly is purely luck. The board you are using(NOT an Arduino) uses 3.3V logic levels. The ST330 says a high must be at least 4V, so if it reacts to your control signals at all it is just luck.

The 8266 outputs are rated for 12mA, the ST330 inputs need about 20mA, so you are over doing it. The 8266 might put up with, and might just die on you.

You might be able to drive the ST330 by switching the mode of the pins.

Low would be "set pin to mode output and set low."

A high would be "set mode input."

Input mode leaves the pin floating, which the ST330 will interpret as a high.

Other than that, you could use NPN transistors to drive the ST330 inputs, then invert your output signals.

The NPN would invert your signal (a high becomes a low) so you would have to set an output to low to get a high going into the ST330.

---

You can use NPN transistors like this to drive the ST330:

simulate this circuit – Schematic created using CircuitLab

Setting the GPIO from the ESP8266 to high would cause a low on the ST330 input.

Setting the GPIO pin to low would cause a high on the ST330 input.

This is the solution I would prefer if I needed to use the ESP8266 with the ST330.

---

If you'd like to try a purely software solution, then do this:

1. To send a low to the ST330 input, set the GPIO to pin mode output and set the output to low. (pinMode(step\_pin,INPUT) then DigitalWrite(step\_pin,LOW))
2. To send a high to the ST330 input, set the pin mode to INPUT (pinMode(step\_pin,INPUT)

When the GPIO pin is in input mode, it floats. It doesn't have a voltage level of its own - it acts like it is disconnected.

If that works, I'd still prefer to use the transistors.

---

You can avoid all of this using the UNO. It has 5V logic levels on the outputs.

# Answer
> 0 votes
This is problematic:

```
 delay(0.005);

```

The Arduino delay() function takes an `unsigned long` as an input, which is an integer rather than floating point type. As a result, the argument you pass to it will be treated as zero. Depending on how delay() is implemented this will result in either no delay (beyond overhead), or a minimum that may be longer than you intended.

Of course you now seem to only be running this code once, and then going into an unending loop which uses a 2.5 ms delay that will, for the same reason, be more of a 2ms delay.

---
Tags: stepper
---


# Question
Title: How to properly understand verbose compiler error text? For beginner level
I'm an Arduino newbie, no background in C/C++, needing help to understand Arduino IDE verbose output about compiler errors. My searching failed to find suitable info - have I missed a relevant guide?

Below example of compiler errors produced when I try to compile Example sketch (TestRTC) from a downloaded library. I assume this Example code is valid. Guessing that my errors relate to missing components. The library was one of two recommended in answer to question. I used IDE Manage Libraries to install from downloaded zip files. Windows file manager shows both library folders are present.

In example below: Which components did the compiler find/not find? Where did compiler search for needed components? What other useful info could be gleaned from this error output?

Would be very grateful for general advice on interpreting error text as well as this particular example. Many thanks.

```
Arduino: 1.6.11 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino
Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\Wire.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility\twi.c" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master\DS3232RTC.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino10/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp.o"
In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

     static void read(tmElements_t &tm);

                      ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:83:23: error: 'tmElements_t' has not been declared

     static void write(tmElements_t &tm);

                       ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:84:27: error: 'tmElements_t' has not been declared

     static void writeTime(tmElements_t &tm);

                           ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:85:27: error: 'tmElements_t' has not been declared

     static void writeDate(tmElements_t &tm);

                           ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:61: error: 'tmElements_t' has not been declared

     static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                                                             ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:88:61: error: 'tmElements_t' has not been declared

     static void writeAlarm(uint8_t alarm, alarmMode_t mode, tmElements_t tm);

                                                             ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:110:24: error: 'tmElements_t' has not been declared

     static void _wTime(tmElements_t &tm);

                        ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:111:24: error: 'tmElements_t' has not been declared

     static void _wDate(tmElements_t &tm);

                        ^

TestRTC:79: error: 'tmElements_t' does not name a type

 inline uint8_t monthLength(const tmElements_t *date)

                           ^

TestRTC:297: error: 'tmElements_t' does not name a type

 void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                              ^

TestRTC:79: error: 'tmElements_t' does not name a type

 inline uint8_t monthLength(const tmElements_t *date)

                                  ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'uint8_t monthLength(const int*)':

TestRTC:81: error: request for member 'Month' in '* date', which is of non-class type 'const int'

     if (date->Month != 2 || !isLeapYear(date->Year))

               ^

TestRTC:81: error: request for member 'Year' in '* date', which is of non-class type 'const int'

     if (date->Month != 2 || !isLeapYear(date->Year))

                                               ^

TestRTC:82: error: request for member 'Month' in '* date', which is of non-class type 'const int'

         return monthLengths[date->Month - 1];

                                   ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdTime(const char*)':

TestRTC:213: error: 'tmElements_t' was not declared in this scope

     tmElements_t tm;

     ^

TestRTC:218: error: expected unqualified-id before '.' token

         tm.Hour = readField(args, posn, 23);

           ^

TestRTC:219: error: expected unqualified-id before '.' token

         tm.Minute = readField(args, posn, 59);

           ^

TestRTC:221: error: expected unqualified-id before '.' token

             tm.Second = readField(args, posn, 59);

               ^

TestRTC:223: error: expected unqualified-id before '.' token

             tm.Second = 0;

               ^

TestRTC:224: error: expected primary-expression before '.' token

         if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

               ^

TestRTC:224: error: expected primary-expression before '.' token

         if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                ^

TestRTC:224: error: expected primary-expression before '.' token

         if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                                   ^

TestRTC:228: error: expected primary-expression before ')' token

         RTC.writeTime(tm);

                         ^

TestRTC:233: error: expected primary-expression before ')' token

     RTC.read(tm);

                ^

TestRTC:234: error: expected primary-expression before '.' token

     printDec2(tm.Hour);

                 ^

TestRTC:236: error: expected primary-expression before '.' token

     printDec2(tm.Minute);

                 ^

TestRTC:238: error: expected primary-expression before '.' token

     printDec2(tm.Second);

                 ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdDate(const char*)':

TestRTC:245: error: 'tmElements_t' was not declared in this scope

     tmElements_t tm;

     ^

TestRTC:256: error: expected unqualified-id before '.' token

         tm.Day = (byte)(value % 100);

           ^

TestRTC:257: error: expected unqualified-id before '.' token

         tm.Month = (byte)((value / 100) % 100);

           ^

TestRTC:258: error: expected unqualified-id before '.' token

         tm.Year = CalendarYrToTm( (unsigned int)(value / 10000) );

           ^

TestRTC:259: error: expected primary-expression before '.' token

         if (tm.Month < 1 || tm.Month > 12) {

               ^

TestRTC:259: error: expected primary-expression before '.' token

         if (tm.Month < 1 || tm.Month > 12) {

                               ^

TestRTC:263: error: expected primary-expression before ')' token

         uint8_t len = monthLength(&tm);

                                      ^

TestRTC:264: error: expected primary-expression before '.' token

         if (tm.Day < 1 || tm.Day > len) {

               ^

TestRTC:264: error: expected primary-expression before '.' token

         if (tm.Day < 1 || tm.Day > len) {

                             ^

TestRTC:269: error: expected primary-expression before ')' token

         RTC.writeDate(tm);

                         ^

TestRTC:274: error: expected primary-expression before ')' token

     RTC.read(tm);

                ^

TestRTC:275: error: expected primary-expression before '.' token

     if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

           ^

TestRTC:275: error: expected primary-expression before '.' token

     if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

                                          ^

TestRTC:276: error: expected primary-expression before '.' token

     Serial.print(tm.Day, DEC);

                    ^

TestRTC:277: error: expected primary-expression before '.' token

     Serial.print(months[tm.Month - 1]);

                           ^

TestRTC:278: error: expected primary-expression before '.' token

     Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                       ^

TestRTC:278: error: 'tmYearToCalendar' was not declared in this scope

     Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                            ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: At global scope:

TestRTC:297: error: 'tmElements_t' does not name a type

 void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                              ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void printAlarm(byte, alarmMode_t, int)':

TestRTC:324: error: request for member 'Second' in 'time', which is of non-class type 'const int'

             printDec2(time.Second);

                            ^

TestRTC:328: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

             printDec2(time.Minute);

                            ^

TestRTC:330: error: request for member 'Second' in 'time', which is of non-class type 'const int'

             printDec2(time.Second);

                            ^

TestRTC:336: error: request for member 'Day' in 'time', which is of non-class type 'const int'

               Serial.print(time.Day);

                                 ^

TestRTC:340: error: request for member 'Wday' in 'time', which is of non-class type 'const int'

               Serial.print(days[time.Wday - 1]);

                                      ^

TestRTC:343: error: request for member 'Hour' in 'time', which is of non-class type 'const int'

             printDec2(time.Hour);

                            ^

TestRTC:345: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

             printDec2(time.Minute);

                            ^

TestRTC:347: error: request for member 'Second' in 'time', which is of non-class type 'const int'

             printDec2(time.Second);

                            ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarms(const char*)':

TestRTC:359: error: 'tmElements_t' was not declared in this scope

     tmElements_t time;

     ^

TestRTC:362: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

         RTC.readAlarm(alarmNum, mode, time);

                                           ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:362:43: note: candidate is:

In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

     static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                 ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarm(const char*)':

TestRTC:373: error: 'tmElements_t' was not declared in this scope

     tmElements_t time;

     ^

TestRTC:391: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             time.Hour = readField(args, posn, 23);

                  ^

TestRTC:392: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             time.Minute = readField(args, posn, 59);

                  ^

TestRTC:393: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             if (time.Hour == 99 || time.Minute == 99) {

                      ^

TestRTC:393: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             if (time.Hour == 99 || time.Minute == 99) {

                                         ^

TestRTC:417: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

     RTC.readAlarm(alarmNum, mode, time);

                                       ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:417:39: note: candidate is:

In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

     static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                 ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

Multiple libraries were found for "DS3232RTC.h"
 Used: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master
 Not used: C:\Program Files (x86)\Arduino\libraries\RTC
Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
Using library DS3232RTC-master in folder: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master (legacy)
exit status 1
'tmElements_t' does not name a type

```

# Answer
As @st2000 said, it's best to start with the first error shown as that error may be causing other errors that will go away once you fix the first one. You should be aware of the difference between warnings and errors. Warnings may or may not be related to the error preventing your code from compiling so I'd just focus on the error at first. So scroll the console window all the way up and then start reading down until you find the first error. If the output is very long you may find it useful to copy the output and paste into a text editor then do a search for the word error, starting from the beginning of the file.

In your compiler output the first error listed is:

```
C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

     static void read(tmElements_t &tm);

                      ^

```

The first thing we can learn from this is the file where the error occurred:

```
C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h

```

The next part of the error message is:

```
:82:22

```

This means that the error occurred at line 82, column 22 of the file DS3232RTC.h. This makes it easy for you to find that code in the file. Any decent text editor will show the current line number and column at the cursor.

The next part of the error message is a description of the problem:

```
error: 'tmElements_t' has not been declared

```

Often you may not understand exactly what it means. This is where your favorite search engine comes in handy. You can try searching for "'tmElements\_t' has not been declared". The 'tmElements\_t' part is very specific to this code so you will get less results but they may lead you to others who have had the same problem and the solutions they found.

Searching for the general error "has not been declared" will give you a broader description of what the compiler is trying to tell you.

Finally is the actual code line:

```
 static void read(tmElements_t &tm);

                  ^

```

The carat shows the column number of the error.

Unfortunately the actual bug may often be in previous code so this isn't as simple as it may seem.

Now lets talk about your specific issue. A search for "'tmElements\_t' has not been declared" does yield some results from others having similar problems but you will probably find after going through their solutions that none of them fix the error. This is because the error is caused by a recent update to a new version of avr-libc in Arduino IDE 1.6.10/Arduino AVR Boards 1.6.12 and later. This version of avr-libc contains a file named time.h. On a case insensitive operating system such as Windows this will cause

```
#include <Time.h>

```

to include the wrong file, time.h which causes the error since indeed that file doesn't declare tmElements\_t. This problem is known to the author of the Time library and he has moved the code to a file named TimeLib.h as a workaround. The file Time.h was left for backwards compatibility. So the solution is to change:

```
#include <Time.h>

```

to:

```
#include <TimeLib.h>

```

I was able to get the TestRTC sketch to compile by just making this change in TestRTC.ino but you may also need to change line 25 of DS3232RTC.h.

I have submitted a pull request to fix this issue to the DS3232RTC repository: https://github.com/Tecsmith/DS3232RTC/pull/9

EDIT: My pull request has now been merged so the issue can also be solved by installing the updated Tecsmith/DS3232RTC library.

If this solves your problem please also update your other question so that the people trying to help you there will know it's fixed.
> 5 votes

# Answer
Consider the Arduino paradigm as a collection of well established (very) sophisticated computing tools. Arguably, the C compiler is the most complex of these tools. So understanding the compilers output can be challenging at times.

That said, the normal way to approach compiler problems is to solve the 1st error the compiler finds then recompile. More often then not solving the 1st error will resolve many other errors.

A guess, in this particular case, is that an include file has been omitted. Find where the type "tmElements\_t" is defined and check to see if the include file (a.k.a. header file) where it is defined needs to be included into the source code file where the 1st errors shows up.

Added later...

Ug, the 1st error is not even your code! It is in the DS323RTC library you downloaded. We can probably assume this library is working and compiles. So that leaves the burden on us to find the reason why your code does not compile. Besides, you can't go back to GitHub saying there is a bug in the library with out trying to solve the problem first.

The 1st stop is to read any readme.txt file at GitHub or the copy of it you downloaded with the library. We find in the 1st few dozen lines this:

```
To use the DS3232RTC library, the Time and Wire libraries must also be included. For brevity, these includes are not repeated in the examples below:

#include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
#include <Time.h>         //http://www.arduino.cc/playground/Code/Time
#include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

```

So right away we see we need to include Time.h. If you look in the Time library (another library you need to download if you have not already) you will find that it is where tmElements\_t is defined. It does bother me that Time.h is included after DS323RTC.h. If you are still having problems try including Time.h first.
> 0 votes

---
Tags: compile
---


# Question
Title: Does serial speed affect performance of other tasks?
I have explored Google and the Arduino site and this site and cannot find a mention of this, so my guess is that serial is handled by a separate component to the core processing and so different serial communication rates will not affect code performance.

Is this correct?

Where can I find information about how serial passing is handled? For instance, when I call Serial.prinlnt("test"), how does that get to the serial line?

# Answer
> 6 votes
It depends. Serial data is received into, or sent from, buffers (one for sending and one for receiving). If you have a processor with 1024 bytes of RAM or more, then the buffer size is 64 bytes, otherwise it is 16 bytes. (See the HardwareSerial.h file in your distribution).

If the buffer fills up when sending, it will *block* (that is, the code will wait for the buffer to empty). If it fill up when receiving the extra bytes will be discarded.

If the buffer does not fill up, then the baud rate will not affect performance. That is because data is sent, or received, by an interrupt service routine, in the background.

As a rule of thumb, you can expect data to be sent or received at the baud rate divided by 10. That is because each byte is 8 bits, plus a start and a stop bit (10 bits in total).

So, for example, at 9600 baud you can send 960 characters per second. If you are sending something simple, like a temperature which is 20 bytes, every second, then the baud rate won't affect performance at all. If you are trying to send thousands of bytes per second, it *will* affect performance, because the `Serial.println` will probably block once the buffer fills up.

---

> For instance, when I call Serial.prinlnt("test"), how does that get to the serial line?

If the buffer is not full, then "t" "e" "s" "t" are copied into the buffer, and the code returns immediately. If the buffer *is* full then it waits for it to become not-full.

As an efficiency measure, if you are sending a single byte, and the buffer is empty, then the byte is placed in the hardware register immediately (saving a small amount of time). In this case, if the buffer was empty, "t" would be sent immediately, and "est" would be sent afterwards, as a "byte has been sent" interrupt is raised.1

This is described in the code comments:

```
size_t HardwareSerial::write(uint8_t c)
{
  _written = true;
  // If the buffer and the data register is empty, just write the byte
  // to the data register and be done. This shortcut helps
  // significantly improve the effective datarate at high (>
  // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
  if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
    *_udr = c;
    sbi(*_ucsra, TXC0);
    return 1;
  }
  tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  while (i == _tx_buffer_tail) {
    if (bit_is_clear(SREG, SREG_I)) {
      // Interrupts are disabled, so we'll have to poll the data
      // register empty flag ourselves. If it is set, pretend an
      // interrupt has happened and call the handler to free up
      // space for us.
      if(bit_is_set(*_ucsra, UDRE0))
    _tx_udr_empty_irq();
    } else {
      // nop, the interrupt handler will free up space for us
    }
  }

  _tx_buffer[_tx_buffer_head] = c;
  _tx_buffer_head = i;

  sbi(*_ucsrb, UDRIE0);

  return 1;
}

```

Notice that the byte is not placed in the buffer at all if it is empty, and nothing is being sent.

---

For more information see my question and answer about serial processing.

---

1. Strictly speaking, after discussing this in the comments with Majenko, the interrupt that is raised is really that the hardware "send" buffer is empty. When the send buffer empties then the interrupt is called so that the interrupt code can put a new byte into it.

# Answer
> 1 votes
No, it affects code performance always. For how much is dependent on used data types, baudrate, tx buffer size.

**Data types:**

* AVR doesn't have hardware floating point operation support. Software support is super slow, so if you want to print some floats, it will be affecting performance a lot (but it's same as just using it).
* There is no integer division either (except for bit shifts/rotates which is division by powers of two). So printing bytes, integers, longs in DEC base takes some performance.

**Baud rate settings and transmit buffer size:**

Sending data over `Serial` is limited by its speed (baud rate). So if you use common `9600` baud rate you'll be limited by this speed. If you're sending data at higher rate. Transmit buffer gets filled and next `write` into `Serial` will be blocked until another character from buffer is sent.

---
Tags: serial, performance
---


title: How to use millis()

text:
# Question
Title: How to use millis()
I'm trying to have a keypad do two one of three things when a key is pressed:

1. If the 1 is pressed I want LED 1 to blink twice then stay on
2. If either the 2 or the 3 is pressed I want LED 2 to blink forever
3. If the # key is pressed I want it to cancel whatever's going on with the other LEDs

How can I use `millis()` to blink forever? Or just blink twice then stay on? When in my blinking should I be checking for another keypress? What's frustrating me is that I know how to do all this with `delay()`, and I've written 70% of the code for it with delay, but if I use delay I don't think it'll be able to check for another key input, will it?

Thanks for any help.

# Answer
> 1 votes
> How can I use `millis()` to blink forever?

The algorithm is essentially as follows:

```
if (it_is_time_to_toggle_the_led()) {
    toggle_the_led();
}

```

The details are thoroughly covered in the Blink Without Delay Arduino tutorial. It is essential to understand this technique: as soon as you have more than one thing to do in your program (here: blink an LED and monitor button presses), `delay()` is toxic because it blocks *all* the program. You should really ban `delay()` from your vocabulary, except for the simpler single-task programs.

> Or just blink twice then stay on?

For this and your other questions, the canonical answer is “implement a finite state machine”. I recommend the Finite State Machine tutorial\[\] by Majenko.

In this particular instance, I would probably implement *two* FSMs, one for each LED. The first one would have three states: (OFF, BLINKING, ON), and a counter for the number of blinks. The transition rules:

1. If button 1 is pressed and the state is not BLINKING go to the BLINKING state
2. If it is BLINKING and it's time for it to toggle, do it
3. If it is BLINKING and it is switching on for the third time, go to the ON state
4. If '#' has been pressed, go to the OFF state.

Or maybe you could split the state BLINKING into BLINKING\_ON and BLINKING\_OFF.

The second LED would be essentially the same, except for lacking the ON state and rule number 3.

I am not writing the code, but you may want to take a look at this code for automatic door\[\]. It is an answer to a seemingly unrelated question, but it gives a good example on how to combine `millis()`-based timing with a finite state machine. Your program could be written mostly along the same lines.

---
Tags: arduino-uno, programming, millis
---


# Question
Title: My computer dose not recognise my Arduino Uno
I had never used Arduino before. When I tried to interface my new Arduino Uno board to my computer, the computer failed to recognize the board.

Why isn't the board interfaced successfully? How should I troubleshoot that problem?

# Answer
> 1 votes
Majenko is probably right. If it is a clone Arduino board you will need to install some CH340 drivers. If it's an authentic board I would return it as it should work out of the box with the Arduino IDE.

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


# Question
Title: Problem with serial driver for CH340G board
I bought a `USB Nano V3.0 ATmega328 16M 5V Micro-controller CH340G board For Arduino` and tried it with Arduino 1.6.6 on my MacBook Pro running OS X 10.11.1

The USB serial could not be seen. I searched on the web and found a few posts about this board, and downloaded http://www.wch.cn/download/CH341SER\_MAC\_ZIP.html

Most of the instructions were in Chinese, but the driver `CH341SER_MAC.ZIP 资料类型：应用资料 资料大小：250KB 资料版本：1.1 更新时间：2013-12-25` seemed to install, but I cannot seem to find any `/dev/tty` and Arduino can't see any serial ports.

Has anyone had any success with this. (The seller has sold 18000 of these so someone may have got it working.)

# Answer
Using different search criteria I found http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

This indicated a newer driver for OSX 10.9 and above at:- http://kiguino.moos.io/downloads/CH34x\_Install.zip

It is now working OK.

PS This was probably a Mac question, but I will answer as it is mainly of interest to Arduino users.

PPS The board worked on my Raspberry Pi which had the driver installed.

WARNING

## The driver worked on `OS X 10.11` but after upgrading to `OS X 10.11.2` when I plug the USB cable into the Mac it causes a crash. This may or may not be related to the upgrade but after this happened twice I gave up.
> 6 votes

# Answer
The CH340 is a chip with notoriously iffy driver support, definitely for OS X, and reportedly also for Windows. Some driver authors are not very fond of it, as evidenced by this affectionate comment

```
/*
 * driver for WinChipHead CH341/340, the worst USB-serial chip in the world.
 */

```

On the upside, the chip costs an order of magnitude less than the commonly used FTDI chips.

I've seen drivers from 3 sources:

1. The manufacturer drivers work off and on. The ones on the official site are not signed, and at some point, they started causing kernel panics for me.
2. The Codebender team is including free CH340 drivers in their installer, and I've had some success running those, although I'm having some difficulties with the latest version. YMMV.
3. So far, the drivers developed by Repleo have been rock solid for me. These are commercial, but, at less than $10, a pretty good deal in my opinion.
> 3 votes

# Answer
On MacOS Sierra it kept crashing the OS, but version 1.3 works on MacOS Sierra.

Found here: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
> 3 votes

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


# Question
Title: Sending struct from Arduino to Raspberry Pi - wrong types
I'm using Raspberry Pi and Arduinos for my home automation project where Raspberry Pi is the controler of Arduino nodes. I use nRF24 wireless transceivers to communicate.

My problem is that when I was sending a structure like following

```
struct TempSensorData

```

{ uint32\_t result; uint32\_t temperature; uint32\_t humidity; };

From Raspberry to Raspberry everything went fine but now when I use Arduino as sender I get very strange results:

```
received: status: 335544320, temperature: 754974720 degrees, humidity: 0%

```

While on Raspberry it was

```
received: status: 0, temperature: 22 degrees, humidity: 44%

```

Can this be a problem with types? Or with different type of architecture (like different sizes on 3-2bit and 64-bit arch)?

EDIT:

Code on Raspberry:

```
if (radio.available())

```

{ // dump the payloads until we've got everything Message receivedData = {0}; radio.read(&receivedData, sizeof(Message)); TempSensorData data = receivedData.msgData.tempSensorData; std::cout \<\< "received: status: " \<\< data.result \<\< ", temperature: " \<\< data.temperature \<\< " degrees, humidity: " \<\< data.humidity \<\< "%" \<\< std::endl; //TODO here we have some strange numbers - check if we have proper types }

Before that I have:

```
radio.begin();
radio.setPALevel(RF24_PA_LOW);
radio.setChannel(0x4c);
radio.openReadingPipe(1, RASPI_READ_ADDR);
radio.openWritingPipe(RASPI_WRITE_ADDR);

radio.enableDynamicPayloads();
radio.setAutoAck(true);
radio.powerUp();
radio.startListening();

```

And on Arduino:

```
Header header = {thisNodeId, thisNodeType, 0, static_cast<uint8_t>(MsgType::TEMP_SENSOR_DATA), 12345, Status::ok};
TempSensorData dhtData;
dhtData.result = DHT.read11(DHT11_PIN);
dhtData.humidity = (int)DHT.humidity;
dhtData.temperature = (int)DHT.temperature;
Message message = {0};
message.header = header;
message.msgData.tempSensorData = (dhtData);
radio.stopListening();
radio.write(&message, sizeof(message));
radio.startListening();

```

I also use a common header with defined structures for both Arduino and Raspberry, which contains:

```
#define RASPI_WRITE_ADDR 0xF0F0F0F0F0LL
#define RASPI_READ_ADDR 0xF0F0F0F0E1LL

struct TempSensorData {
  uint32_t result;
  uint32_t temperature;
  uint32_t humidity;
};

enum class Status : uint8_t

```

{
ok, error, fail };

```
enum class MsgType : uint8_t {
    INITIALIZATION,
    RESET_REQUEST,
    ACK_NACK,
    TEMP_SENSOR_DATA,
};

struct Header {
  uint8_t nodeId;
  uint8_t nodeType;
  uint8_t location;
  uint8_t msgType;
  uint16_t checksum;
  Status status;
};

union MsgData {
  InitMsgData initMsgData;
  AckNack ackNack;
  TempSensorData tempSensorData;
};

struct Message {
    Header header;
    MsgData msgData;
};

```

`radio` is an item of RF24 class from https://github.com/TMRh20/RF24/

Unfortunately the RF24 repo is 64 commits ahead of what I use.

**EDIT2:**

Maybe the problem lays in that

```
enum class Status {};

```

which I use in both files.

I must add that I use g++-4.7 when compiling on Raspberry and when compiling on Arduino I use avr-g++-4.8.2

# Answer
> 0 votes
It is not a size problem: `uint32_t` is always 32 bits. Converting the numbers to hex gives:

* Raspberry to Raspberry: 0x00000000, 0x00000016, 0x0000002c
* Arduino to Raspberry: 0x14000000, 0x2d000000, 0x00000000

There seems to be an offset between the two. You may just have lost one byte when the Arduino is the sender. There *may* be also a byte order issue, but your test is not sufficient to say. You can, e.g., send a series of `0x12345678` to know for sure.

You need to devise a way of synchronizing the communication, i.e. to identify, in the byte stream, which is the first byte of the packet.

**Edit**: Let me illustrate how this can happen both with and without and endianness issue. I'll assume you are transmitting `{status: 0, temperature: 20, humidity: 45}` and the first byte(s) of the first packet are lost. On the receiving side, you combine the remaining bytes of the first packet with the first byte(s) of the second packet, and interpret the whole as a single packet. You get: `{status: 335544320, temperature: 754974720, humidity: 0}`.

In a little endian to little endian scenario, you only need to loose one byte:

```
original data:     0x00000000, 0x00000014, 0x0000002d
transmitted bytes: 00 00 00 00 14 00 00 00 2d 00 00 00
received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
received data:     0x14000000, 0x2d000000, 0x00000000

```

In a big endian to little endian scenario, you get the exact same result if you loose 4 bytes:

```
original data:     0x00000000, 0x00000014, 0x0000002d
transmitted bytes: 00 00 00 00 00 00 00 14 00 00 00 2d
received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
interpreted data:  0x14000000, 0x2d000000, 0x00000000

```

# Answer
> -1 votes
I believe this could be because the Raspberry pi is big endian and the arduino is little endian.

Learn about Endianness here!

# Answer
> -1 votes
You may have multiple problem. First of all the structure get align to be efficient on the specific architecture, to avoid those filling you have to tell the compiler to pack the structure. There are different way to pack depending on compiler used.

Then endianess is different, so the byte composing the value has to be swapped.

Finally there may be a desincronization or a bus error. In those case a sync message (normally 2 byte before each transmission) and a CRC are used to fix the issue.

---
Tags: arduino-pro-mini, data-type
---


# Question
Title: Difference between Wire.setClock() method and TWBR method for changing I2C Frequency
I want to change the `I2C` frequency of my Arduino Mega 2560. I did find two methods. One method is to change the `TWBR` variable after `Wire.begin()`. The other one is to use `Wire.setClock()` after `Wire.begin()`.

Whats the difference between the 2 methods? which one is better? Can I set any `I2C` frequency I want?

# Answer
> Whats the difference between the 2 methods?

The difference is that one is more portable than the other. The "direct register set" will not work very well on an Arduino Due.

There is no speed or foot-print advantage with the "direct register set" as this is often only done once in the setup of the sketch.

> Which one is better?

If better is portable, maintainable, readable, etc then the answer is simple - use the API and not "direct register set".

> Can I set any I2C frequency I want?

No - obviously there are some restrictions. First, the CPU frequency is scaled so it cannot generate all possible frequencies. Second, the I2C device(s) and bus will set restrictions on the maximum frequency. Longer wires and several devices will add capacity and require lower frequency. Also the device with the lowest frequency puts an upper limit. Always check the data sheets for the I2C devices.

Cheers!
> 4 votes

# Answer
They are both one and the same. One is easier to remember though (I'll let you work out which).

`Wire.setClock(frequency)` just (ultimately) does:

```
TWBR = ((F_CPU / frequency) - 16) / 2;

```

You can set any frequency that ends up with that formula generating an integer between 0 and 255.
> 5 votes

---
Tags: i2c, communication
---


# Question
Title: Unable to interface AD7705 (SPI) with Arduino
Code as shown below. I am unable to get the 16-bit data. Can someone help me identify my mistake?

```
byte spiTransfer(volatile byte data) {
  SPDR = data;
  while (!(SPSR & _BV(SPIF)));
  return SPDR;
}
#define DOUT      (50)
#define DIN       (51)
#define SCLK      (52)
#define CS_AD7705 (53)
#define DRDY (4)

void setup() {
  Serial.begin(9600);
  pinMode(DOUT, OUTPUT);
  pinM ode(DIN, INPUT);
  pinMode(SCLK,OUTPUT);
  pinMode(CS_AD7705,OUTPUT);
  pinMode(DRDY,INPUT);
  SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPOL) | _BV(CPHA) | _BV(SPI2X) | _BV(SPR1) | _BV(SPR0);
  delay(10);
  digitalWrite(CS_AD7705, LOW);
  spiTransfer(00010000); //setup register
  spiTransfer(01100110);
  spiTransfer(00100000); //clock register
  spiTransfer(00001000);
  digitalWrite(CS_AD7705, HIGH);
}

void loop() {
  unsigned int data=0;
  digitalWrite(CS_AD7705,LOW); // enable device
  while(!digitalRead(DRDY));
  data = spiTransfer(00111000);  // select ch1 and setup read 16-bit data register
  data = spiTransfer(0)<<8;
  // Get the most significant 8 bits
  Serial.println("data : "+data);
  data |= spiTransfer(0); // Get the least significant 8 bits
  digitalWrite(CS_AD7705, HIGH); // release device
  delay(1000);
  Serial.println(data, HEX);
}

```

# Answer
I think the main problem is the values you are passing to spiTransfer(). By the way they are written I think you think you are passing binary values, you aren't you are passing decimal values. So

```
data = spiTransfer(00111000);  // select ch1 and setup read 16bit data

```

should be

```
data = spiTransfer(B00111000);  // select ch1 and setup read 16bit data

```

The number needs prefixing with a B

Also passing a volatile parameter to this function looks wrong to me, especially when you only pass in constants.
> 1 votes

# Answer
I've been trying to get one of these working too. I think before you can read the data register, you have to tell the COMMs register your intention to do so.

```
// Select channel to read:
// write to comm reg selecting channel and
// setting up next op to be a read from data reg
SPI.transfer( DRDY_DONT_CARE | REG_DATA | STDBY_OFF | COMMS_READ | CHAN_AIN1 );
//  Do two 8-bit reads, MSByte first
highByte = SPI.transfer(0xff);
lowByte  = SPI.transfer(0xff);

adcValue0 = highByte << 8;
adcValue0 = adcValue0 | lowByte;

```

Still, I've had sketchy and intermittent success reading the ADC. The looping code seems to lose sync with the ADC; I've been speculating that reading ASAP following DRDY going True is important.

Have you verified that your SPI interface is working? You can read the 24-bit calibration data, which should match the documented values. Doing so verifies that the SPI reads and writes properly, unless the SPI interface behaves differently for different functions. Are you using genuine Analog Devices silicon, or one of the widely available knock-offs (TM7705, like mine)?
> 0 votes

---
Tags: arduino-mega, spi
---


# Question
Title: Wireless Communication Between Raspberry Pi 2 and multiple Arduinos
I have about 10 Arduinos that have sensors attached, which report information back around my house. I would like to have a RPi 2, because they have nice screen and GUI options, to collect the information and display it accordingly.

I am looking for success stories on what wireless parts you used to get these two working. The the wireless must be able to penetrate a brick wall about 120ft away.

Thanks for replying, I edited the response above.

# Answer
> 2 votes
There's many options you could use.

The simplest, though most expensive, would be to equip all your Arduinos with WiFi shields and connect a USB WiFi dongle to the Pi. The Pi could run in AP mode (investigate hostapd) so you don't have to connect them all to your internet router.

A cheaper option, though harder to work with on the Pi, would be to use the incredibly cheap but popular nRF24L01+ modules. There are libraries aplenty for the Arduino, but I am not aware of code for the Pi (though there probably is somewhere if you google for it).

And then there are options in between which vary in price and complexity.

Of course, you haven't mentioned range, only a brick wall. The right choice could well be affected by the range of communication you need - do you go for the bare nRF28L01+ with a range of maybe 10m, or the one with the power amplifier and SMA antenna with a range of many hundreds of meters? Is WiFi going to be long enough range? Would a 433mHz module be a better choice? All these questions and more need to be answered, and the best way is for you to describe your setup in detail, including what the longest range is you need to deal with, what amount of data you will be sending, do you need ultra low power to save batteries, etc.

# Answer
> 2 votes
I use the ESP8266 to get the data from my arduino to my webserver using wlan. You could easy install a webserver on your pi and connect it to your wifi, or just use a server online. So you can install on all places where you get WLAN. Also you could use a repeater if your wlan is not strong enough.

Thats how my projekt works (Water level messure)

1. Get range from ultrasonic sensor (every minute)
2. Send data to the ESP8266 using SoftwareSerial
3. Send getRequest with WLAN to my php page on the Server
4. Save Data to MySql Database
5. Show the Data Online with php and a javascript graph lib

My example is one way Arduino to Server, but you could easy communicate back to each of your arduinos.

good luck :)

# Answer
> 0 votes
You could use an xBee.

I have 2 of these and they are really easy to set up. Here is a link to the data sheet: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf

Link to site: https://www.digi.com/lp/xbee

These I believe can interface to the GPIO of the pi - as i seem to recall doing that myself. Either I did that or used an arduio to get the readings and had the arduino feed the readings to the pi GPIO pins - either way the modules make sending data wireless super easy.

---
Tags: wireless
---


# Question
Title: Sum values, store them and print the last value
I have a mass flow meter connected to an Arduino Uno board. I have managed to read the volume flow in L/hour, but now I'm struggling to implement a code that stores the values so that I see the number of Liters used.

For instance, I can see on my monitor this:

0 L/hour

0 L/hour

And if I have some water running through,

10 L/hour

20 L/hour

20 L/hour

Then when I stop the flow it goes back to 0.

0 L/hour

Is there any ways to sum up time instances, get the total number of liters and keep it printed during every instance?

Mathematically is not that difficult (Volume = Volume Flow in L/hour * time), but I don't know how to implement this. Can anyone help with this? It can be in seconds or ms or whatever.

Paul

# Answer
> 4 votes
What you want to do is *integrate* the flow rate vs time curve. You have to keep track of the current flow rate. You also need to choose some unit of time measurement; this depends on how often you're sampling the flow rate. For instance, if you sample it every second, then you should convert your L/hr flow rate to L/s. This means a flow rate of 10L/hr is equivalent to 10L/3600s = 0.002778 L/s. So, if you get a reading of 10 L/hr for 10 seconds, `0.002778 L/s * 10 s = 0.02778 L` of water flowed through your valve or whatever. An accumulating sum is what you need. You can try something like this:

```
#define INTERVAL 1000  // sampling interval in millisec
#define HR_TO_SEC 2.778E-4  // number of hours in a second

int curr_rate = 0;  // current flow rate in L/hr
unsigned long lastRead = 0;  // the last time the rate was sampled
float totalVolume = 0;

void loop(){
  if (millis() - lastRead >= INTERVAL){
    lastRead += INTERVAL;
    curr_rate = getFlowRate();   // or whatever function you call; should take << 1 sec
    totalVolume += curr_rate * HR_TO_SEC;  // update the volume
    Serial.println(totalVolume, 4);
  }
}

```

This rectangular method is reasonably accurate, depending on your application. If you want a better approximation, google "trapezoidal numerical integration" or "Simpson's method" if you want even better approximation.

# Answer
> 1 votes
This will be helpful.

reading is your flow meter value in L/Hour

```
float reading;//value of the flow meter
long startTime;
float total=0;

void setup() {
  Serial.begin(9600);
  startTime=millis();

}

void loop() {
//read your flow meter to reading variable.
 total+=reading*float((millis()-startTime))/3600000.0;
 Serial.println(total);

}

```

# Answer
> 1 votes
In a recent comment, you posted a link to a forum thread with the code for reading the sensor. You should have provided this information up front, because it completely changes the problem. It appears that the flow meter sends pulses at a frequency proportional to the volume flow, and the code uses an interrupt to count the pulses over a specified time.

TisteAndii's answer suggests you *integrate* the flow readings to get a volume. And that suggestion makes perfect sense given the limited information he had available at the time. Now that we know how the flow meter is read, it makes no sense anymore:

* the interrupt service routine counts a number of pulses that is proportional to the *total volume* that has gone through the meter
* the linked code *differentiates* that reading in order to get the flow
* you are now *integrating* that flow in order to get the total volume.

Instead of doing an integration on top of a differentiation, you could just convert the raw reading into a volume. Then you do not have to worry about any approximations done while differentiating or integrating.

In the forum thread it is stated:

> Pulse frequency (Hz) in Horizontal Test= 7.5Q, Q is flow rate in L/min.

Writing this in a more mathematically accurate form (i.e. with unit-correctness) gives:

> *f*/Hz = 7.5 *Q*/(L/min)

where *f* is the frequency and *Q* the volume flow.

Given that 7.5 Hz⋅min = 450 pulses, the above equation can be rewritten as

> *f* = 450 pulses/L × *Q*

or, in terms of integrated quantities:

> volume = (pulse count) / (450 pulses/L)

Here is an example code that just convert the pulse count to a volume:

```
// Calibration constant of the flow meter.
const float calibration = 1/450.0;  // 450 pulses per liter

// How often to print the measured volume.
const uint32_t print_interval = 1000;  // once per second

// Number of pulses counted so far.
volatile uint32_t pulse_count;

// Count the pulses inside an ISR.
void count_pulse() { pulse_count++; }

// Return volume reading, optinally resetting the count to zero.
float totalVolume(bool reset = false)
{
    noInterrupts();
    uint32_t pulse_count_copy = pulse_count;
    if (reset) pulse_count = 0;
    interrupts();
    return pulse_count_copy * calibration;
}

void setup()
{
    pinMode(2, INPUT_PULLUP);
    attachInterrupt(0, count_pulse, RISING);
    Serial.begin(9600);
}

void loop()
{
    static uint32_t last_print;
    if (millis() - last_print >= print_interval) {
        last_print += print_interval;
        Serial.println(totalVolume());
    }
}

```

Note that you may want to reset the count from time to time. I added an optional parameter to `totalVolume()` for this purpose. If you never reset the counter, it will overflow after approximately 9544 m3.

---
Tags: datalogging, signal-processing
---


title: FastLED and Neopixel Help

text:
# Question
Title: FastLED and Neopixel Help
I'm in the process of trying to create a "Aurora Glow" effect using a Particle Photon and a Neopixel ring.

I have the code fully working using a single Breadboard-friendly NeoPixel however when upgrading this to a NeoPixel Ring (16 LED) the code does not run as expected

The current working code for a single NeoPixel can be found here: http://pastebin.com/Yj1cywpx

It was my assumption that i could change Line 33 from one LED to Sixteen e.g.:

```
FastLED.addLeds<NEOPIXEL, 6>(&led, 1);

```

to

```
FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

```

However when I run this code rather than all NeoPixels cycling through the Aurora Colours, only the very Top LED does and rest are either off or a static colour (e.g. https://i.stack.imgur.com/6rY38.jpg)

Could someone please advise what i missing? Apologies if this is a "Noob" question but this is my 2nd Arduino project and I cannot understand why this would not work.

Thanks

# Answer
Never used neoPixels in arduino before so this is a complete guess based on reading the code but it looks like you are only setting the colour of the first LED.

Try creating 16 LED colours:

```
CRGB led[16];

```

and then setting them all:

```
for (int i = 0;i<15; i++) {
  int colourIndex = index + i;
  if (colourIndex > 15)
    colourIndex -= 15;
  led[i] = ColorFromPalette(auroraPalette, colourIndex , 255, LINEARBLEND);
}

```

edit - as @rDg indicates in his answer

```
FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

```

becomes

```
FastLED.addLeds<NEOPIXEL, 6>(led, 16);

```

since led is now an array not a single value

Finally I think paletteSize should only be 16 not 5\*16, you only have 16 colours in there.
> 1 votes

# Answer
In addition to the above, you need to tweak your addLeds line:

```
FastLED.addLeds<NEOPIXEL, 6>(led, 16);

```
> 0 votes

---
Tags: neopixel
---


# Question
Title: Can I power two 5V with Arduino powered with 9V power adapter?
I have a setup where I have a 5V IR receiver and 5V relay board and Arduino Uno.

I am currently powering the Arduino from the PC USB and both the IR receiver and the relay board from the Arduino. And it works fine.

Now I want to know how it would work when I power it with a 9 volts wall adapter. Will the voltage be enough for both the IR receiver and the relay board? And will Arduino work fine?

# Answer
> 7 votes
The voltage will be fine - as long as you plug it into the DC barrel jack, and don't try to wire directly to the 5V pins. The barrel jack has a voltage regulator on it that will convert 7-12V down to the required 5V.

But there's a second reading that you need to look at, not just voltage. The 9V adapter will also have a current rating expressed in milliamps (mA) or amps (A, which is 1,000 mA). The Arduino needs around 25 mA to do its thing, and your adapters add to the total current - maybe 20 mA each again. So if your adapter only provides 50 mA, it won't be able to provide enough current and the system won't work.

The USB port provides 5V, but it also provides up to 500 mA, which is more than enough for the job. If your wall adapter is 100 mA or above, that should be enough. And unlike voltage, a larger number for current is better - that's its maximum capacity of supply, rather than something that will burn out the equiment!

# Answer
> 0 votes
If you're connecting the 9V wall adapter to the Power socket of the arduino, then sure its going to work. It can supply both for the IR and relay boards.

---
Tags: arduino-uno, power, relay, ir
---


# Question
Title: Referencing local libraries from higher dir levels
How can I include libraries not contained in any direct subdirectories of a sketch, using the Arduino IDE?

I want my project structure to look like this:

```
Project
└> MCUa
   └> MCUa.ino
└> MCUb
   └> MCUb.ino
└> Libraries
   └> TimerLib
      └> TimerLib.cpp
      └> TimerLib.h

```

So in my project two sketches `MCUa` and `MCUb` share a resource, namely the library `TimerLib`.

I've tried to include the libraries like this:

```
#include "../Libraries/TimerLib/TimerLib.h"

```

or this:

```
#include "./../Libraries/TimerLib/TimerLib.h"

```

But none of them will compile - this is the error message:

```
fatal error: ./../Libraries/TimerLib/TimerLib.h: No such file or directory
 #include "./../Libraries/TimerLib/TimerLib.h"
                                              ^
compilation terminated.
exit status 1
Error compiling.

```

If I put the library directly in of the directories and reference it like this:

```
#include "./Libraries/TimerLib/TimerLib.h"

```

Everything goes well.

Using an absolute path like in this answer is not a possibility in this case, as it should compile out of the box for others, without modifying any absolute paths.

# Answer
The problem with a relative path for an include is that it has to be relative to one of the predefined list of existing include directories. This includes:

* Compiler include locations
* The Arduino core files
* The locations of other included libraries
* The build folder for the sketch

What it does not include is the location of the sketch, so you cannot specify a location relative to the sketch itself.

Further, even if you could, the compiler wouldn't know what library it was supposed to be referencing so, while the header would be found, any source files associated with it would be ignored and linking would fail miserably.

Instead you will have to place the library in a standard library location, such as the libraries folder in your sketch book.
> 3 votes

---
Tags: arduino-ide, library, compile
---


title: Cant connect to localhost

text:
# Question
Title: Cant connect to localhost
I have a project um Visual Studio with a GET method: http://localhost:4548/Arduino/request?id=12&user=username&pass=password
When I open it in my browser, it works fine
But I want http GET in my Arduino, using the WebClient exemple:

**EDIT**
I used solution number 1. of @Matt and it worked:
Get a full licensed copy of IIS.
And this is the code after all:

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

//Informacoes de endereco IP, gateway, mascara de rede
byte mac[] = { 0xA4, 0x28, 0x72, 0xCA, 0x55, 0x2F };
byte ip[] = { 192, 168, 1, 200 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[] = { 255, 255, 255, 0 };
byte server[] = { 192, 168, 1, 100 };

EthernetClient client;

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /myProject/request?id=12&user=username&pass=password HTTP/1.1");
    client.println("Host: 192.168.1.100");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

```

My Serial displays as connected, but the http GET does not work
Am I missing something?

# Answer
> 1 votes
Visual Studio's web server is restricted to only servicing clients on the machine it is running on.
To do what you want to do there are a number of things you can do.

1. Get a full licensed copy of IIS. (Please stop laughing)
2. Get a version of Apache (might affect your server code and will take a while to setup)
3. Write yourself a 'proxy server'. I think if you write a program to run on you PC that creates a socket that listens to port 8080 and forwards any messages on to the VS Web Server (use `"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE" /port:6666 /path:C:\WebServer\Root` to start it on a fixed port) and forward any replies back to you client.

---
Tags: visualstudio
---


# Question
Title: Control Arduino through ethernet. How to contact from outside network and securely
I'm new to Arduino so please bear with me if my question is too simple or broad (I did try and research it) or guide me if it belongs elsewhere (networking forum?)

I would like to be able to control my Arduino remotely. By remotely, I mean I would like to be able to access it over the internet. I've done some research and know about the Arduino Ethernet Sheild (see: How can I connect to an Arduino using WiFi?)

But I'm a newbie and it's not clear to me how I'm going to make my device "discoverable" from outside my local network. I gather it involves "opening a port on my router" Can someone expand on this or provide an example/tutorial? If I can do this, it would also be nice if there was some security so that not just anyone could control my robotic killer dog or whatever :). I would think these are both common desires, and there is probably tons of material (maybe even tutorials) but perhaps because I'm new to Arduino, I'm having a hard time finding material.

I thought a nice first step would be to have my Arduino Uno board connected to a single LED. If I could then have a simple webservice on it, I could connect via my phone from work with a http post request. Of course, I'd need someone at home to verify the led went on/off (or set up a camera for remote access).

Let me know if I can provide more detail or clarifications. And Thank you!

Dave

# Answer
The easiest way to do this is to use Blynk, an Internet Of Things (IoT) web service that includes an Arduino library, apps for iOS and Android, and a central server that the smartphone app and the Arduino both connect to. Since both connections are outgoing (and matched up by the Blynk server), each one works just fine from behind NAT routers without any ports needing forwarding. See Blynk's demo video for how to create a basic working app in 5 minutes (including your described LED controller and much more). Ok, I'll admit that starting from cold, it takes most of us a little longer than 5 minutes to get it going, especially if you like to read about and understand what you're doing as you do it. But it will still be minutes, not hours. This is the quickest, most painless way to get an IoT device up and running.

That basic app (which can read & write to ports, PWM, and A/D) is then extensible to work with your own code & hardware. The functions available lend themselves to just what you are looking to do, with the possible exception of uploading the images it takes. And the Arduino itself isn't really well suited to that task, given its memory constraints.

Update: I use the ESP8266 like the one you linked to. They're cheap and easy to use but with a gotcha: they are 3.3v only on both power & signal lines, which can be a challenge when working with a 5v MCU board. Here's how to wire one up for a 5v Arduino. Note the dedicated 3.3v regulator; the Arduino's on-board 3.3v supply isn't sufficient for an ESP8266:

For quick & dirty, you can wire this up on a breadboard. Ultimately you'll want something more stable (mechanically) than breadboard wiring. I made up a few 5v ESPs on strip-board (aka Vector board or Vero board), but that's another project:

--

\** (Disclaimer: I have no connection to the organization other than as a happy user/experimenter.)
> 0 votes

---
Tags: arduino-uno, ethernet, remote-control
---


# Question
Title: Errors seen whilst compiling with AdaFruit Motor Shield ("invalid library")
Whenever I compile a sketch, change the **Tools \> Board** selection, or open/close Boards Manager/Library Manager I get the following message in the console:

```
> WARNING: Spurious .github folder in 'Adafruit Motor Shield library' library
> WARNING: Spurious .github folder in 'Adafruit Motor Shield V2 Library' library
>
>
> Invalid library found in
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
> Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
> C:\arduino-1.6.8\libraries\robotarm Invalid library found in
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
> Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
> C:\arduino-1.6.8\libraries\robotarm

```

# Answer
> 1 votes
Arduino IDE 1.6.6 and higher are picky about what you have in your libraries folders. There are two general valid library formats, the old "pre-1.5" format and the newer 1.5 format, the specification of which is at https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification.

Any folder in any of the Arduino libraries folder that doesn't follow a valid library format will cause the "Invalid library" message. Common causes of this issue are:

* Putting a sketch folder in the libraries folder. Libraries may contain example sketches but a sketch by itself is not allowed.
* Libraries that are in a subfolder, rather than the library folder being in the root of the libraries folder as required.

Now lets look at your specific messages:

```
Invalid library found in C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master: C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master

```

By looking at the Adafruit-Motor-Shield-for-Arduino repository we see that it's not a library but the PCB design files for the shield and thus has no business being in the libraries folder. Please move it to a different location.

```
Invalid library found in C:\arduino-1.6.8\libraries\robotarm: C:\arduino-1.6.8\libraries\robotarm

```

Without being able to see what's in this folder I can't say exactly the problem. If you will provide a directory listing I could update this answer with specific directions. As it is now, that folder is doing you no good in the libraries folder.

---
Tags: adafruit, arduino-motor-shield
---