# Question
Title: Native function name w/o parens -- expected behavior?
I wrote a sketch that used the `millis()` function in several places. I got odd behavior because I inadvertently used the plain `millis` in one line, without the parens. It evaluated to zero when running.

Why didn't the compiler flag this as an undeclared variable? I suspect it's because the name was already in the symbol table, but I still would have thought it'd be caught. Is this a quirk, or expected? If expected, what is the benefit?

C/C++ is not my main language so be gentle. (-:

Edit as requested to show some code. This is an incomplete sample, but shows the usage:

```
const unsigned long GATE_OPEN_TIMER = 7000;
const unsigned long GATE_CLOSE_TIMER = 12000;
...
unsigned long gateStopTime = 0;
...

  if (isGateCycling) {                 // if open/close cycle is running
    if (isGatePassive) {               // if we're not applying power
      if (millis() >= gateStopTime) {  // if current delay expired
        digitalWrite(GateCloseRelay, ACTIVE);
        gateStopTime = millis() + GATE_CLOSE_TIMER;
        isGatePassive = false;

```

... followed by similar logic for the reverse direction. If any use of `millis()` is replaced by `millis`, the code falls over but the compiler sees nothing wrong.

# Answer
I've made up a test case:

```
const unsigned long GATE_OPEN_TIMER = 7000;
const unsigned long GATE_CLOSE_TIMER = 12000;
unsigned long gateStopTime = 0;

void setup()
{
  if (millis >= gateStopTime) {  // if current delay expired
    gateStopTime = millis + GATE_CLOSE_TIMER;
  }
}
void loop()
{
}

```

Under IDE 1.6.9 I get these errors:

```
/tmp/arduino_modified_sketch_345879/sketch_oct27a.ino: In function 'void setup()':
sketch_oct27a:7: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
   if (millis >= gateStopTime) {  // if current delay expired
                 ^
/tmp/arduino_modified_sketch_345879/sketch_oct27a.ino:8:29: warning: pointer to a function used in arithmetic [-Wpointer-arith]
     gateStopTime = millis + GATE_CLOSE_TIMER;
                             ^
sketch_oct27a:8: error: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
     gateStopTime = millis + GATE_CLOSE_TIMER;
                           ^
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]

```

---

Under IDE 1.6.12 they are downgraded to warnings:

```
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino: In function 'void setup()':
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:9:21: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]
       if (millis >= gateStopTime) {  // if current delay expired
                     ^
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:33: warning: pointer to a function used in arithmetic [-Wpointer-arith]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                                 ^
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:31: warning: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                                   ^

Sketch uses 512 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 13 bytes (0%) of dynamic memory, leaving 2,035 bytes for local variables. Maximum is 2,048 bytes.

```

---

So, the compiler isn't totally letting you get away with it. You should check the warnings. But *why* are the warnings only warnings?

Checking the generated compile command (using verbose compiling) I see that 1.6.12 has an extra option: `-fpermissive`.

From the documentation:

> Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive allows some nonconforming code to compile.

So you have "nonconformant code" but you are getting away with it.

I don't know why the Arduino devs did that. The whole point of making things like that errors is so you fix them at compile time, rather than scratching your head about why things don't work at run time.

Clearly the symbol `millis` exists. But it is a function (or perhaps a pointer to a function) and thus shouldn't be just compared to a number or have a number added to it. That's what those errors were about in 1.6.9.

---

Just remember, in C, C++ and the ilk, to *call* a function you *always use parentheses*, even if you are passing no arguments.
> 2 votes

# Answer
In short, a function in an Arduino program that gets called without `()` will be considered as a plain variable. Try writing a small function in your program and call it without `()`. Nothing will happen.

The reason the compiler didn't flag it as an undeclared variable was because `millis` is a variable that is declared in a kind of pre-loaded library. Think of it as a library that is always there even if you didn't include it. That is why the compiler only saw it as a regular variable.
> 0 votes

---
Tags: c++, arduino-ide
---


title: What Arduino data type allows decimals?

text:
# Question
Title: What Arduino data type allows decimals?
This probably sounds dumb, but I am not getting any clear answer for this. What data type allows a reasonable amount of decimals?

# Answer
If you need to represent numbers that are not integers, the simplest solution is to use floating point variables, also known as “floats”. A float is declared with the `float` keyword. A numeric constant is automatically a float if it has a decimal point :

* `42` is an integer (`int` type)
* `42.0` is a float

If you combine an int and a float in an arithmetic operation, the int is implicitly promoted to float, and the result is a float.

A float gives you a precision of 24 *significant bits*. “Significant” means that we are counting both the bits *before* and *after* the binary point. Then, a small number will have many fractional bits, whereas a large number will have only a few, and any number larger than 223 = 8388608 will have *no* fractional bits at all.

This precision is almost always better that 7 significant decimals and worse than 8 significant decimals. For example, the following two numbers are consecutive: any computation that yields a result *in between* them will be rounded to either of them (usually the closest):

```
    binary (24 bits)          decimal
101010.000000000000000000  42.0
101010.000000000000000001  42.000003814697265625

```

The issue with floats is that they are expensive. Unlike a desktop computer, the Trinket has no hardware support for floats (it's an ATtiny: it doesn't even have a hardware multiplier!). Then every computation is done by software. Even the simplest things, like adding two numbers, can take quite a few CPU cycles and *a lot* of flash space. That's why on very small devices people sometimes prefer *fixed point* arithmetic. In a nutshell, fixed point is all about choosing appropriate units of measurement in order to achieve the required precision using only integers. For example, the ADC converter in the Trinket gives you the voltage readings in units of

```
5 V ÷ 1024 = 4.8828125 mV

```

That unit may seem unpractical, but it allows a reasonable precision using only integers. If you can avoid converting to volts, you will be able to write integer-only code which is smaller and faster.

I would suggest you first try using floats, as it's the simplest solution. If that leads to code with is either too large or too slow, then try to rewrite with fixed-point (i.e. integer only) arithmetic.
> 2 votes

# Answer
> At least 2 or 3 \[digits\], just the type smallest amount above this so I can save processing power on my Trinket board

Processors (computers) do not normally store values in Binary Coded Decimal (BCD) (as in base 10) because such storage wast valuable space. Rather, processors usually use Binary numbers (as in base 2).

Most processors deal with binary values in multiples of 8 bits. So, values are usually represented by 8 bits, 16 bits, 32 bits, ect. An 8 bit binary number can have 2^8 possible values or 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 or 256. That is to say, an 8 bit binary number can have values between 0 and 255 inclusive.

If your requirement of "reasonable amount of decimals" falls within that range, then the type you are looking for is "uint8\_t" or "char". Both are normally 8 bits in the C / C++ language. If you need more the next binary number has 16 bits or 2^16 or values between 0 and 65535. Then the type you are looking for is "uint16\_t" or "unsigned int".
> 0 votes

# Answer
Another option that Edgar doesn't mention (mainly because it's a more esoteric and tricky system to use) is *fixed point* values. These values, also known as *Q* values, are often used in digital signal processing (DSP) since they give predictable resolution and high speed processing.

A Q value is simply an integer where you split the bits within that integer into two portions - the integer portion and the numerator portion.

For instance, you may choose to implement a Q4.11 format. That gives 4 bits of integer value (it can store 0-15) and 11 bits of numerator (that is a decimal resolution of `1/(2^11)` or 0.000488281). The 16th bit (4+11 = 15, in a 16-bit integer there is one more bit to account for) is the implicit sign bit. Some implementations have that, some don't - it's entirely up to you. If you only want positive values you can include the 16th bit in your value to increase resolution or integer size, etc.

You're not limited to 16 bit of course - you could use 8 bit for smaller numbers and lower precision, or 32 bit for bigger numbers and higher precision.

The disadvantage to using Q values compared to using floats is that floats can arbitrarily exchange decimal precision for integer size. With fixed point you have limited yourself to the range of integers you can represent. But that sacrifice can be worth it if you have a limited range in the first place (0-5V, say) and you need extra speed.

To work with fixed point it is first necessary to convert a floating point number to and from your target Q value. This is quite simple - just multiply (or divide to convert from Q to float) the value by the Q value of 1. That is, for a Q4.11 you would use the value of the 12th bit (the first of the integer bits), or 1\<\<11 (start counting from 0, so the 12th bit is 11).

Once you have your Q values adding and subtracting is just that - exactly as normal, using the `+` and `-` operators. Multiplying and dividing though is slightly more involved, but the resultant code is considerably more efficient. The whole lot can be done using just left and right shifts. For instance, some functions which I use in a small library of mine for Q15 values (more specifically Q0.15), which store values between ±1 with 15 bit resolution, look like:

```
typedef int16_t Q15;

static inline int16_t __satQ15(int32_t x)
{
    if (x > 0x7FFFL) return 0x7FFF;
    else if (x < -0x8000L) return -0x8000;
    else return (int16_t)x;
}

static inline Q15 Q15_mul_Q15(Q15 a, Q15 b) {
    int16_t result;
    int32_t temp;

    temp = (int32_t)a * (int32_t)b; // result type is operand's type
    // Rounding; mid values are rounded up
    temp += (1 << 14);;
    // Correct by dividing by base and saturate result
    result = __satQ15(temp >> 15);
    return result;
}

static inline Q15 Q15_div_Q15(Q15 a, Q15 b)
{
    int16_t result;
    int32_t temp;

    // pre-multiply by the base (Upscale to Q16 so that the result will be in Q8 format)
    temp = (int32_t)a << 15;
    // Rounding: mid values are rounded up (down for negative values).
    if ((temp >= 0 && b >= 0) || (temp < 0 && b < 0))
        temp += b / 2;
    else
        temp -= b / 2;
    result = (int16_t)(temp / b);

    return result;
}

```

You can learn more about Q numbers here:
> 0 votes

---
Tags: data-type
---


title: Low power wifi temperature sensor

text:
# Question
Title: Low power wifi temperature sensor
I want to make a wifi-enabled temperature sensor and place it inside my HVAC system to measure and push the temperature to a central server, every minute or so.

I have a LoLin NodeMcu v3 unit laying around, and I am wondering if it is possible to use this one - and have it last for many years inside the HVAC system?

I realize the LoLin unit has a onboard wifi chip, I also realize LoLin takes 3v input. Aside from that, I am pretty blank.

Yesterday I tested the LoLin board by programming it with the following code, which lists networks in the vicinity. It worked great:

```
#include "ESP8266WiFi.h"

void setup() {
  Serial.begin(9600);
  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(2000);
  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  int n = WiFi.scanNetworks();// WiFi.scanNetworks will return the number of networks found
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

```

**The actual question**

Is the LoLin board a feasible board for making a low power wifi enabled temperature sensor? Or should I rather make board that communicates with a wall-connected parent unit via radio?

# Answer
Yes, the NodeMCU can connect to a temperature sensor and forward that on to your WiFi access point to send to the internet.

Yes, the NideMCU can run from batteries.

Can it do it off one battery for many years? Only if that battery contains a small nuclear reactor.

Running something from battery for many years requires incredibly close attention to detail and incredibly tight component specifications, even down to the precise battery chemistry used. It's a very very difficult task for which people are very highly paid.

When you start looking at periods like that you begin to run up against the problem of battery self-discharge. Getting your power consumption down to an absolute minimum is a must, but even then if you have near zero power consumption the battery is still going to go flat by itself. So you have to invest time and effort into selecting a battery technology with a very low self-discharge.

All that is pretty moot though with the NodeMCU since:

* WiFi is a power hungry technology. You can expect hundreds of mA while transmitting, and doing that once a minute for, say, 10 seconds (reconnecting to the WiFi takes time) will give you quite a high average power consumption just from the WiFi
* The NodeMCU is far from optimised WRT power consumption. Linear voltage regulators, poor choice of components for low power consumption, etc, abound.

So yes you can run it from batteries, but be prepared to replace the batteries very often. By "very often" I mean every couple of days.

That means you basically have two options:

1. Don't use the NodeMCU but instead use something designed to be incredibly low power and run for long periods on battery (typically it won't use WiFi but something more efficient like nRF24L01+)
2. Don't use batteries. Hard-wire your NodeMCU into a mains-connected power supply.
> 2 votes

---
Tags: esp8266, wifi, nodemcu
---


title: SoftwareSerial data not available

text:
# Question
Title: SoftwareSerial data not available
Second time I'm asking the same question with no solution, let me elaborate in other way for clarity.

I wrote an Arduino program which uses two serial ports, one is hardware serial port and other is SoftwareSerial port.

No problem with hardware serial port, the problem is with software serial port.

The software serial port's Tx pin works but Rx pin does not work, i.e. `portone.available()` is always zero, nothing in the input buffer of the software serial port.

I'm using Arduino IDE 1.6.12 with an Uno board. Previously I used version 1.6.9 but neither works. Here is the piece of code:

```
#include <SoftwareSerial.h>

String code = "", customer = "";
bool complete = false;
byte c = 0, j = 0;
char customercode[27];
SoftwareSerial portone(10, 11);
void setup() {
  Serial.begin(9600);
  portone.begin(115200);
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);
  if (Serial) {
    Serial.print("Connecting");
  }
}

void loop() {
  String copy = "";
  char inchar = '0';

  if (Serial.available() > 0) {
    while (Serial.available()) {
      char bytes = (char)Serial.read();
      if (bytes == '1' || bytes == '2' || bytes == '3' || bytes == '4' || bytes == '5' || bytes == '6' || bytes == '7' || bytes == '8' || bytes == '9' || bytes == '0' || bytes == '.' || bytes == '-' && bytes != '#') {
        customercode[c] = bytes;
        c++;
      } else if (bytes == '#') {
        complete = true;
      }
      if (c > 12 && bytes != '#') {
        code += bytes;
      }
    }

    if (c == 13) {
      customer += '+';
      for (byte i = 0; i < 12; i++) {
        customer += customercode[i];
      }
    }
  }
  portone.listen();
  if (portone.available() > 0) {
    portone.println("AT+CMGF=1");
    portone.println("AT+CNMI=2,2,0,0,0");
    portone.flush();

    while (portone.available()) {
      inchar = (char)portone.read();
      copy += inchar;
    }
    delay(1);
    Serial.print(copy);

  } else if (complete == true && customercode != "" && code != "") {
    sending();
  }
  Serial.print(portone.available());
  delay(1000);
}

```

# Answer
Don't call `portone.listen()`. That method is only necessary when you have created *multiple* `SoftwareSerial` ports. It specifies which port you are listening to, because only one of them can receive at a time (you can transmit on any of them at any time). It also *empties the receive buffer* so that data from one `SoftwareSerial` port is not mistakenly returned by another. In your code, this empties the input buffer before checking `portone.available()`. Surprise, it's always empty! ;)

Also, don't set the pin mode of the pins used for the `SoftwareSerial` object. The pin modes were set during the constructor of `portone`, which happens before `setup`. You're messing with pins that have been "promised" to that library for its own use and control.

As Edgar suggested, you should consider a more-efficient software serial library. AltSoftSerial is best, but is only available on certain pins. My NeoSWSerial library is next best, and works on any two pins, but only at 9600, 19200 and 38400. Both of those libraries can transmit and receive at the same time, unlike `SoftwareSerial`. Here is an answer with all the gory details.

And you really should ditch the `String` class usage. You obviously know how to use `char` arrays (aka "C strings"). We can't see the `sending()` function, but you can probably just print a few pieces instead of building a complete `String` and printing it:

```
    portone.print( '+' ); // leading plus sign
    portone.write( (uint8_t *) customerCode, 13 ); // array of bytes, length

```

It would be better to terminate the character arrays with a zero byte (NUL-termination) in `loop` so they can be used as a standard C string instead of a byte array:

```
    customerCode[14] = '\0'; // NUL-terminate the C string

```

Then you can use the standard C string `print` in `sending`:

```
    portone.print( '+' ); // leading plus sign
    portone.print( customerCode );

```

Printing the pieces is always more efficient than building a big buffer with all the pieces. This avoids copying the pieces and needing twice as much RAM. :P
> 1 votes

---
Tags: arduino-uno, serial, arduino-ide, softwareserial
---


# Question
Title: How to keep amperage in serial and parallel?
I have a 2000mA AC adapter and also I have the lights that I show here:

Each of these lights consume up to 300mA.

If I make a circuit with 3 lights in serial, ¿will the amperage of each light decrease?

If I make a circuit with 3 lights in parallel, ¿will the amperage of each light decrease?

I am asking it because I don't want the lights to decrease the luminosity. I want the maximum luminosity in each light.

The lights are for growing lettuces. Now I am using a low consumption light but are not efficient:

# Answer
You haven't said what the voltage rating of your Power Supply is, but if we assume it is a "constant voltage" regulated supply, then it will attempt to maintain a constant voltage up to the rated current capacity (2000 mA).

If you put your LEDs in series, then the voltage from your power supply is distributed across the LEDs, and is therefore lower on each LED. This would cause your LEDs to be less bright.

If you put your LEDs in parallel, then the voltage remains constant.
> 1 votes

# Answer
The simple answer to that is "No, and stop right now whatever you are doing."

Those LEDs, because of their high current requirements, need a *constant current driver*.

First a little theory:

* LEDs in series sum the voltage, the current stays the same.
* LEDs in parallel with no form of current management split the current unevenly and LEDs start dying (or even exploding when you have high currents involved).

If you don't want any control over the brightness then the simplest constant current driver is to use an LM317 voltage regulator wired in constant current mode.

It is also possible to make a constant current sink (the same as a constant current source but between the LED and ground instead of positive) using discrete components.

If you want control of the brightness then the best solution is to use something like the CAT4101 PWM LED driver.

Why don't you use a simple resistor like you would for any other small LED? It's quite simple. Both resistors and LEDs characteristics change with heat. When you are using higher currents like this both the resistor and the LED give off heat (more so the LED than the resistor unless you pick too small a wattage). That means you get changes in the characteristics, which means the current you originally calculated for is now wrong - typically the current increases above what you had originally calculated. More current means more heat. More heat means more current. The result: a cascade. Worst case? The LED dies.
> 1 votes

# Answer
If you put them in series the they require 300mA, but you'd need to have a higher voltage (around 10 Volt).

If you put them in parallel, you could keep the same voltage as a single led (around 3.3 Volt), but you'd require trice the amount of current (i.e. 900mA).

You however **need** to add proper current regulation, of you'll **burn out the leds**. The advantage of having the leds in series, is that you only need a single constant current driver.

You could use resistors, but since these leds require that much current, the leds will have to dissipate a lot of heat. Which is both wasteful, and requires special high wattage resistors.
> 1 votes

---
Tags: serial, led
---


# Question
Title: How do I change the I2C address on the LCD backpack?
The 20 x 4 LCD comes with a I2C backpack. I know it has A0, A1, A2 to set the address, as shown at the bottom here: https://tronixlabs.com.au/news/tutorial-serial-i2c-backpack-for-hd44780compatible-lcd-modules-with-arduino/

It points to here: http://www.nxp.com/products/interface-and-connectivity/interface-and-system-management/i2c-bus-portfolio/i2c-general-purpose-i-o/remote-8-bit-i-o-expander-for-icbus-with-interrupt:PCF8574\_74A

My unit shows up as 0x3F.

And even with all this information I can't tell how to change it.

I need to have a second display on the same I2C bus.

Question: How do I change the address of the second one?

# Answer
> 4 votes
As mentioned in the page you linked, jumper together one of the address jumpers. For example, above A0 are two pads. Solder a wire across them (vertically - between the two pads above A0). I am guessing the address is pulled high by a resistor, so that will probably make the new address 0x3E, but you could run the I2C scanner to check that.

---
Tags: lcd
---


# Question
Title: Attiny45 resets when setting digitalOutput to low
I currently try to program an Attiny45 with an Arduino UNO as ISP.

The Arduino is able to program the Attiny45.

However, when I try the blink example, it resets the Attiny, when setting digitalOutput to low (on any pin)

To further confirm, that it resets only, when setting a pin to low, I wrote this sketch and let it run on the Attiny.

```
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  delay(1000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
  delay(10000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
}

```

The LED I connected to pin 3 waits 1 second, and then turns on, but when 1 second passed and it should stay off for 10 seconds, it resets and only waits 1 second.

I tried reburning the bootloader onto the Attiny, which had no effect.

# Answer
> 3 votes
> Including the 220Ω resistor with the LED as in the last step?

...

> My LED can handle 5V, so I used it without, but that cant be the issue

The one thing that "can't be the issue" is indeed the issue! Without a resistor the LED will attempt to conduct a lot of current which will damage both it and the output pin of the processor.

See The care and feeding of LEDs. From that page:

> LEDs are not like normally electronic devices in that you can’t just apply a voltage to them and they work, they have to be fed the correct voltage and current to keep them happy.

And then:

> There are several web sites and schematics on the web that suggest you can attach an LED directly to an Arduino output pin with no current limiting resistor. They are wrong, and following them will damage your Arduino.

---

So, by not using a resistor, when the output pin goes LOW it attempts to "sink" current, in order to turn on the LED. Since you have no resistor, it sinks as much as the output drivers can handle, dropping the supply voltage inside the Attiny, which then goes below the brownout level, and resets itself.

Please, when following a circuit, don't just omit bits of it, and then post a question about why it doesn't work. At least follow the circuit exactly, and then when you have learned more about electronics, you can start experimenting.

---
Tags: arduino-uno, attiny
---


title: Transistor Switching

text:
# Question
Title: Transistor Switching
I'm hoping that someone will be able to help me. I'm looking to produce a power interrupt for testing. I'm looking to have 28V DC input flowing to an output which I can hook up to a load and then switch on and off using an Arduino. I'm thinking of using an NPN high current transistor, I have built the box and code which runs fine. The issue I am having is the pin output on pin 13 doesn't have enough current to switch the transistor, can anyone recommend a transistor that would be able to take the high current and be switched by the Arduino? If you would like a schematic to help you understand it I can provide one!

Thanks for reading, Lewis

# Answer
> 1 votes
If you did manage to switch the transistor on, It would only output 4.3V, the rest would be dissipated in the transistor. If you managed to switch 4A this would dissipate 96W - and the transistor would melt.

A MOSFET would be a better option and could be easily switched by the Arduino. (I regularly switch 10A using a MOSFET and Arduino.)

This assumes you can put the MOSFET in the negative lead. If not you should use a P-Channel MOSFET, but you need a more complex circuit to drive it.

Have you considered using a relay module?

---
Tags: arduino-uno
---


# Question
Title: Talking to Eurotherm 2416 temperature controller over modbus rs232
I am trying to implement the modbus library written by smarmengol to read process values and to set new setpoints (e.g. temperature) on a Eurotherm controller. The Arduino sketch looks like this:

```
/**
 *  Modbus master example 2:
 *  The purpose of this example is to query several sets of data
 *  from an external Modbus slave device.
 *  The link media can be USB or RS232.
 *
 *  Recommended Modbus slave:
 *  diagslave http://www.modbusdriver.com/diagslave.html
 *
 *  In a Linux box, run
 *  "./diagslave /dev/ttyUSB0 -b 9600 -d 8 -s 1 -p none -m rtu -a 1"
 *  This is:
 *      serial port /dev/ttyUSB0 at 9600 baud 8N1
 *      RTU mode and address @1
 */

#include <ModbusRtu.h>
#include <SoftwareSerial>

SoftwareSerial mySerial (3,5);

uint16_t au16data[16]; //!< data array for modbus network sharing
uint8_t u8state; //!< machine state
uint8_t u8query; //!< pointer to message query

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram[2];

unsigned long u32wait;

void setup() {
  // telegram 0: read registers
  telegram[0].u8id = 1; // slave address
  telegram[0].u8fct = 3; // function code (this one is registers read)
  telegram[0].u16RegAdd = 1; // start address in slave
  telegram[0].u16CoilsNo = 1; // number of elements (coils or registers) to read
  telegram[0].au16reg = au16data; // pointer to a memory array in the Arduino

  // telegram 1: write a single register
  telegram[1].u8id = 1; // slave address
  telegram[1].u8fct = 6; // function code (this one is write a single register)
  telegram[1].u16RegAdd = 2; // start address in slave
  telegram[1].u16CoilsNo = 250; // (Setpoint) number of elements (coils or registers) to read
  telegram[1].au16reg = au16data+4; // pointer to a memory array in the Arduino

  Serial.begin(9600);
  master.begin( &mySerial, 9600); // baud-rate at 9600

  master.setTimeOut( 5000 ); // if there is no answer in 5000 ms,roll over
  u32wait = millis() + 1000;
  u8state = u8query = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    master.query( telegram[u8query] ); // send query (only once)
    u8state++;
    u8query++;
    if (u8query > 2) u8query = 0;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 1000;
    }
    break;
  }
   Serial.print(au16data[O]);

  au16data[4] = analogRead( 0 );

}

```

I can read process values with telegram\[0\] very well (temperature and/or setpoint), but I cannot change the setpoint with telegram\[1\]. If I run the code, it puts the current temperature to serial monitor but resets manually changed setpoints to zero. Where is the error? Should I write the value for the setpoint as HEX or DEC? What does the last command do actually?

Thank you!

# Answer
> 1 votes
You could also take a look at this github project: https://github.com/ukos-git/arduino-eurotherm2416

It is specifically designed for the purpose you ask for. It basically includes Module named Temperature and a possibility to set or read it:

```
Temperature.set(100)
t = Temperature.getTemperature()

```

Look at https://github.com/ukos-git/arduino-eurotherm2416/blob/master/app/app.ino.

---
Tags: arduino-uno, modbus, rs232
---


# Question
Title: Why is my arduino acting like a radio? And is there a way to abuse this?
I am playing around with an arduino and a cheap SDR dongle and I just noticed something strange!

When I play a tune on pin 13 with just a random piece of wire connected to the pin (Using the Melody example from the arduino page: http://www.arduino.cc/en/Tutorial/Melody) I can pick it up as AM sound on my SDR on exactly 64Mhz even as far as 15meters away through walls with a little gain!!!

What magic is going on here and secondly and maybe most importantly would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

(Just for educational purposes of course, I know that there is better options depending on what I need to send)

I would like any qualified guess as to what is going on, I am genuinely puzzled...

# Answer
I did something like that a while ago. Hardware:

Code:

```
const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

```

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

If you hold the Arduino near an AM radio tuned to around 800 KHz you should hear a hissing toggling on and off (like Morse code) as the carrier is turned on and off for 0.5 / 0.3 second intervals.

> would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

I think you might find making a receiver a bit harder than a transmitter.
> 3 votes

# Answer
I dont think Nick Gammon's answer actually explains clearly enough what is going on - he just made an example of how to do it. Since no-one else on this site has had a go at explaning it-I will-though Im no expert in arduino radio communications.

"What magic is going on here"

Its not magic -you are observing the principle of "electromagnetic induction" and the principle of "resonance". Its not unique to arduino- basically an Antenna transmits information by making on and off power changes in the electrical current in the wire-as you are doing playing the melody. By the famous Maxwell equations this energy in the wire creates a corresponding invisible waves in the air. A well known circuit in electrical engineering (tank circuit or oscillator circuit) says that there is also a corresponding receiver circuit (which can be a radio) that will change the waves back into sound (by using the principle of electrical resonance).
> 2 votes

---
Tags: arduino-uno, hardware
---


# Question
Title: How might the SD library be reading phantom files?
I have the Sparkfun CAN Bus shield with integrated SD card writer attached to an Arduino Mega 2560. I can delete a logged file from the SD card using Windows, log more data using the SD library, then look at the logged data in, say, Excel. The new log file will include the logged data from the old, deleted file.

The card is formatted in Windows in FAT32 and the logged file has the same name as the original. It seems like the SD card reader/SD library is able to 'recover' the deleted file by name, open it for writing having read its uncorrupted contents, and continue logging to it, despite it having been 'deleted' in Windows. I know a deleted file doesn't get rid of the data unless it is overwritten, but there seems to be some bug/oversight in how the SD library in card reader or how it interrogates the SD card or FAT32 volume for the existence of the file.

Has anyone come across this before? Is it a bug or am I doing something wrong?

# Answer
> 1 votes
* How large is the file when it is deleted in Windows? I can imagine what you describe happening if there's a bug in the Arduino File System (see below) - but that requires relatively small files (less than 4K or so).
* I assume that the SD card has zero or more "static" files, that don't change; and then the log file, that grows. That is, when the log file is deleted, the newly-freed blocks get re-used again for the new log file?
* I also assume that you're using Windows' "Safe Removal" mechanism - giving it a chance to tidy up the SD Card before you yank it out.

To delete a file in FAT, the file system needs to do two steps:

1. Unlink the used blocks from the File Allocation Table (the eponymous F.A.T.).
These should be set back to zero - making it hard to accidentally re-use them again unless they're the same blocks again (which, for SD Cards, is unlikely due to wear levelling!)
2. Mark the directory entry as available again.
This is done by merely overwriting the first character of the directory entry with `0xE5`. When FAT needs a new directory entry, it will use entries with either `0x00` or `0xE5`. If the deleted file is being "resurrected", then a bug could be that it re-uses the directory entry *but doesn't zero the existing contents*, allowing the existing block number and length to be appended to.

Rather than deleting the file in Windows, try renaming it to something else entirely. That way the Arduino will create a new file, and you shouldn't have the problem. If you still do (worse: if the renamed file gets *corrupted*) then it's a caching problem. If you don't, then it's a bug in the file system.

---
Tags: sd-card, datalogging, can-bus, fat
---


title: Interfacing Digital clock with Uno

text:
# Question
Title: Interfacing Digital clock with Uno
I want to take input from a clock for a specific time and respond to it.

I am taking alarm as input because it will send some signal to a buzzer and I want to decode it through Arduino.

I am using Arduino Uno.

The program I used is as follows:

```
int b = 0;

void setup() {
    pinMode(8, INPUT);
    Serial.begin(9600);
}

void loop() {
    b=digitalRead(8);
    Serial.println(b);
    if(digitalRead(8) != 0)
    {
        Serial.println("input in 8");
    }
    else
        Serial.println("not");

    delay(500);
}

```

I have removed the buzzer from the clock and connected the terminals to Arduino pin 8 and GND.

But the output is always random (i.e. 0 & 1), no matter if my alarm is on or off.

I cannot find if my program has a flaw or if my approach is just wrong.

# Answer
> 4 votes
It is likely that the alarm clock does not provide any voltage level (I mean `GND`) to the buzzer when it does not have to ring, the circuit is just left "open" then; it will provide a voltage level (depending on your clock power supply) only when the alarm has to ring.

On the other side, your Arduino pin 8 **must** have a voltage level that can be mapped to a `0` (anything between `GND` and `5V/3`) or a `1` (anything between `2x5V/3` and `5V`).

However, in the absence of alarm, the input is left "dangling" (no voltage level at all). In CMOS technology, leaving an input pin dangling will make it randomly take `0` and `1` levels as you described.

Fortunately, the solution to this problem should be easy: you just have to force a `0` level to pin 8, by connecting it to `GND` through a resistor. I generally use 10K or 15K for that resistor. This is called a "pulldown" resistor:

* when the alarm does not provide any voltage, the input pin level will be "pulled down" to `GND`, ie `0`.
* when the alarm provides a 5V (see important remark below) to the input pin, then it will be seen as `1`.

**IMPORTANT**: you have to make sure that your alarm clock, when ringing, provides a voltage that is not higher than 5V (it would grill your UNO, or more precisely the ATmega328 of your UNO) and is at least ~3V to be "recognized" as `1`.

**NOTE**: it is likely that solving this first issue will not be enough to make your complete program work, because your alarm clock probably does not send a continuous voltage to your buzzer but and alternate one to make it ring, hence you will get successive `1` and `0` at high speed (between 100Hz and 100Hz I would say) in your program. If that is the case please open another question as the solution for that specific issue is disconnected from the current one (random `1` and `0`).

---
Tags: arduino-uno, digital
---


# Question
Title: avrdude.conf: programmer type must be written as "id_type"?
I'm trying to compile & run using ino.

At the `ino upload` step I get the following error:

`avrdude: error at /usr/share/arduino/hardware/tools/avrdude.conf:332: programmer type must be written as "id_type"`

Relevant section of `avrdude.conf`:

`programmer
 id = "wiring";
 desc = "Wiring";
 type = wiring; # line 332
;`

I've seen various posts around the internet that suggest I just delete the config & refresh it, but I'd like to find the correct syntax and actually understand & fix the issue.

# Answer
After looking at the source repo it looks like quotes are now required:

`type = "wiring";`
> 5 votes

---
Tags: avrdude, ino
---


# Question
Title: How can I set 4 Arduino Leonardo PWM-ports between 200Hz and 1kHz?
I've noticed that I can set D9, D10, and D11 to around the timer 1 can be set to ~244Hz. However I need 4 ports that are between 200-1000Hz but I have been unable to figure out how to find the last one. I can't really touch timer 0 as they control millis etc.

# Answer
The ATmega32U4 on the Leonardo has 4 timers, named Timer0, Timer1, Timer3 and Timer4. Timer0 would be used for `millis()`.

Timers 1 and 3 are 16-bit timers, and Timer4 is a 10 bit timer.

You can get a wide range of frequencies by changing the prescalers and other factors. A bit would depend on whether you want them to all have the same frequency (but maybe with different duty cycles) or different frequencies. Each timer has two "ports" associated with it, so you can have different outputs - up to a point - for each timer. A given timer can only be in one mode at a time, which limits a bit what its two output ports can be doing at one time.

I have a page about timers which is for the Atmega328P, but the Leonardo timers have a lot in common with that. For more details see the ATmega32U4 datasheet.

You could get a more detailed answer if you clarified what the exact frequency you want is, what mode (eg. PWM, fast PWM or something else) and whether each output should be the same or different frequencies.

---

According to the Leonardo product page:

> PWM: 3, 5, 6, 9, 10, 11, and 13. Provide 8-bit PWM output with the analogWrite() function.

So even if you lose two to Timer 0, you should have 5 outputs left (it looks like the "B" side of Timer 1 and Timer 4 share the same pin).
> 1 votes

# Answer
According to Arduino Leonardo, you have available for PWM configuration ports numbered 3, 5, 6, 9, 10, 11 and 13. The specifications presented there do not provide the range of the frequency available, but I would expect that if you are able to use 9, 10 and 11, one of the others would fall into place.
> 0 votes

---
Tags: pwm, arduino-leonardo, frequency
---


# Question
Title: Problems building an Arduino Micro with through-hole components
So I'm trying to build an Arduino Micro using a bread-board and through-hole components. I'm leaving out the voltage regulator and voltage selector (see schematic at the bottom for reference). I'm powering off of USB, so the `+5V` line is connected to `VUSB`.

I checked over the circuit many times, so I think it's okay. Below is a picture of me trying to use an Arduino Micro to load the bootloader on to the Atmega32U4:

I looked here and here as references for trying to load the bootloader, but every time I try it gives me an error. It seems like the MCU is not being recognized. Has anyone tried this before, and successfully done it? I'd like some pointers as to how to achieve this.

EDIT: I've moved the crystal (and 22 pF cap's) closer to pins 16 and 17. The steps I take are:

1. Upload "ArduinoISP" sketch to Arduino Micro (the "programmer").
2. Select "Arduino Micro" as the board to be programmed.
3. Select "Arduino as ISP (Atmega32U4)" as the programmer.
4. Burn bootloader.

Here is the verbose output (compilation and upload):

```
Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Micro"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -carduino -PCOM5 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xcb:m -Uhfuse:w:0xd8:m -Ulfuse:w:0xff:m

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0xffffff (probably .reduced_core_tiny) (retrying)

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0xffffff (probably .reduced_core_tiny) (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0xffffff (probably .reduced_core_tiny)
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

# Answer
> I select "ArduinoISP" as the programmer. I press "Burn Bootloader". I get the following: avrdude: Error: Could not find USBtiny device (0x2341/0x49) Error while burning bootaloader.

You need to select **Arduino as ISP** from the **Tools \> Programmer** menu. ArduinoISP is a dedicated in system programmer made by Arduino, confusing because the name of the sketch used with Arduino as ISP is ArduinoISP.

If you're using Windows you'll also likely encounter the issue that ATmega32U4 based boards can't be used for Arduino as ISP. The cause of this is explained at https://petervanhoyweghen.wordpress.com/2012/09/16/arduinoisp-on-the-leonardo as well as a solution. Unfortunately the solution described in that blog post no longer works as-is with recent versions of the Arduino IDE. I have updated the solution to work with recent Arduino IDE versions and added support for installation via Boards Manager here: https://github.com/per1234/ATmega32U4asISP
> 2 votes

---
Tags: programming, usb, bootloader, arduino-micro
---


# Question
Title: NeoPixel setPixelColor works only in for loop
I am working with a NeoPixel RGB led and have gone through various tutorials but I have a question regarding the `setPixelColor()`.

If I do not have my `setPixelColor()` and `show()` inside of a `for` loop it will not work.

This works:

```
void holoLight(uint32_t c){
  for(uint16_t i = 0; i<2; i++){
    holo_pxl.setPixelColor(i, c);
    holo_pxl.show();
    delay(2500);
  }
}

```

This does not:

```
void holoLight(uint32_t c){
    holo_pxl.setPixelColor(1, c);
    holo_pxl.show();
    delay(2500);
}

```

I am sure it is something specific to the language or execution but would love some clarifications, thanks =)

# Answer
> 4 votes
I am not sure I fully understand your exact problem but you have to be aware that `holo_pxl.setPixelColor(1, c);` set the color of the **second** LED in a NeoPixel chain, **NOT the first one**.

For the first LED, you have to use `holo_pxl.setPixelColor(0, c);` instead.

---
Tags: arduino-uno, programming, neopixel
---


title: Why is my switch not working?

text:
# Question
Title: Why is my switch not working?
I'm trying to have a common light switch turn a LED on and off.

When I connect the light switch directly to a LED, it works like it should - the LED turns on and off with the switch.

When I connect the light switch back to the board, changing the switch does nothing - I get the exact same signals regardless of whether the switch is on or off.

Why? How do I make the board recognize whether the switch is on or off?

The diagram I followed:

```
const int  buttonPin = 2;

const int ledUt = 13;
const int ledTest = 12;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

int tilstand = 0;

int buttonStateForrigeForrige = 0;

boolean light = false;

void setup() {
  Serial.println("Hello World");
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(ledUt, OUTPUT);
  pinMode(ledTest, OUTPUT);

}

void loop() {

  digitalWrite(ledTest, HIGH);
  buttonState = digitalRead(buttonPin);
  Serial.println("Sjekk");

  tilstand = LOW;
  if ( buttonState == HIGH ) {
    Serial.println("buttonState HIGH");
    if ( lastButtonState == HIGH ) {
      Serial.println("lastButtonState HIGH");
      tilstand = HIGH;
    } else {
      Serial.println("lastButtonState LOW");
    }
  } else {
    Serial.println("buttonState LOW");
  }

  if (buttonState != lastButtonState) {

    if (buttonState == HIGH) {
      buttonPushCounter++;
      Serial.println("on");
      Serial.println(buttonPushCounter);
    } else {
      Serial.println("off");
    }
  }
  buttonStateForrigeForrige = lastButtonState;
  lastButtonState = buttonState;

  if (tilstand == HIGH) {
    digitalWrite(ledUt, HIGH);
  } else {
    digitalWrite(ledUt, LOW);
  }
  }

```

# Answer
> 1 votes
See my page about switches. Judging by your very-hard-to-read diagram, you have just connected the switch to an input pin like this:

---

That will not give a positive reading either way because it is "floating". You should connect a pull-up or pull-down resistor, like this:

Now if the switch is open, it is pulled-up to 5V by the resistor and the input will read `HIGH`. When the switch is closed the switch conducts and "overpowers" the resistor, and it would read `LOW`.

---

An alternative is to use a pull-down resistor like this:

That reverses the sense of the switch. When open it will read `LOW` and when closed it will read `HIGH`.

---

I hope you have a resistor in series with the LED.

# Answer
> 1 votes
You can also use `pinMode(buttonPin, INPUT_PULLUP);` instead of `pinMode(buttonPin, INPUT);` in that case the arduino "activates" an internal pull-up resistor.

---
Tags: arduino-uno, switch
---


# Question
Title: How to connect an RF module directly to a PC without using an arduino?
I know that in xbees i can connect the xbee module directly to my pc using the USB explorer. But I'm using the nRF24L01 RF modules. I want to transmit from my pc, via the RF transmitter to my RF receiver, which is connected to my arduino. How do I connect this RF module directly to my PC?

# Answer
The nRF24L01+ uses SPI. PCs don't (usually) have an SPI interface. So you will need some piece of hardware to provide the PC with an SPI interface.

That could be an Arduino, or it could be a dedicated SPI dongle, such as one based around the FT2232 chip.

Of course, you then would need to write software to use that SPI interface and work with the nRF24L01+ connected to it, including using the same message format / packet system, which won't be a simple task. So you may be better off just using a small Arduino to do the communication and present you with a simple serial interface for sending / receiving messages. That way you can then use the same nRF24L01+ software that you are using elsewhere in your setup.
> 1 votes

---
Tags: xbee, nrf24l01+, wireless, rf
---


# Question
Title: I need to build a char array from two integers
My C is rusty, so please forgive this simple problem.

This line works:

`Tft.drawString("Test",200,200,2,WHITE);`

But, this has compile errors:

```
String yStr = "Test";
Tft.drawString(yStr,200,200,2,WHITE);

```

The function in the library:

```
void drawString(char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor);

```

The error is **"no known conversion for argument 1 from 'String' to 'char\*'"**.

Conclusion - I need a character array. Here's what I am trying to accomplish.

I have two integers that I would like to display on my Tft screen. For example, 225 and 250 to be displayed as "225,250".

I haven't figured out a way to build the char array for the `drawString()` function.

Assistance would be appreciated.

---

Thanks for the quick reply Ignacio.
I tried that, but the compiler still doesn't like it.

Here's how I built the string:

```
string stringXY ;
stringXY += xStr;
stringXY += ",";
stringXY += yStr;
Tft.drawString(stringXY.c_str(),200,200,2,RED);

```

Error: **invalid conversion from 'const char\*' to 'char\*' \[-fpermissive\]**

I am apparently using `c_str()` wrong?

# Answer
> 1 votes
Put it in a `String` and then use the `c_str()` method to get the associated `char*`.

# Answer
> 1 votes
Many thanks to Ignacio.

I changed the function in the library to:

void drawString(**const** char \*string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor);

This fixed the problem and gave me more confidence in my vague understanding of C.

# Answer
> 1 votes
Another option in your situation is to not use `String` at all (which is preferrable for reasons I won't explain here) and exclusively use plain old C strings and their associated functions:

```
// Define a string buffer to hold the result, ensure it is long enough
// to hold "N1,N2". An additional char must be added to terminate the string with 0
char result[15+1];
unsigned int N1 = ...;
unsigned int N2 = ...;
// Format output as desired
sprintf(result, "%u,%u", N1, N2);
// Now you can use result with drawString
Tft.drawString(result, 200, 200, 2, RED);

```

`sprintf` is a very powerful formatting function that offers you plenty of options.

Note that I took it for granted that your numbers are `unsigned int`; if these were normal `integer` (possibly negative), you should replace `"%u,%u"` with `"%d,%d"`.

---
Tags: programming, string
---


# Question
Title: Can the EWRF 3022 module be directly connected to the pc totransmit data from the pc wirelessly?
In my project I want to connect my pc to an RF transmitter. The receiver will be connected to an arduino on my robot. However most of the RF modules I looked up couldn't be directly connected to my computer- in all of them I needed to use an arduino on the transmitter end too. Then I came across this:

> EWRF 3022

Can this be directly connected to my computer? If so, how is it done?

# Answer
If you use a USB to TTL UART adapter, such as an FT232 dongle, then yes you can communicate to it from a PC.

It will not directly connect to a PC though without you getting that extra hardware.
> 0 votes

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


title: How to animate a LED Strip via wifi?

text:
# Question
Title: How to animate a LED Strip via wifi?
I'm remotely connecting my phone to an arduino MKR1000 via wifi, and sending data via HTTP GET (so to switch on the debug LED, I just need to navigate to http://192.168.1.1/debug/H, for example). Now, I want to be able to remotely send animations to an RGBW led strip.

Ideally, I would have a simple keyframe based protocol such as: http://192.168.1.1/anim/(keytime in ms):R,G,B,W+(keytimeinms) etc...

So for example, to animate from white to red in 500ms, I would navigate to: http://192.168.1.1/anim/0:255,255,255,255+500:255,0,0,0

Is this the best way to remotely send animations to my arduino? How should I implement this on the arduino side in the most ressource-efficient way possible? I don't even know where to start :/ For the moment, on the arduino side, I've got a keyframe class and an array of those keyframes representing the animation.

# Answer
Ignacio's comment, “Start with something. Worry about making it efficient after you've figured out how to make it at all”, is good advice.

Note, to make the transition from one keyframe to another more efficient, use a variant of the Bresenham algorithm. This allows use of fast integer arithmetic and is intrinsically accurate. Instead of error accumulating and getting steadily worse (as will happen if you add constant increments), the Bresenham algorithm tracks error and minimizes it. See, for example, “Simplified Bresenham's line algorithm: What does it *exactly* do?”.

---

This edit addresses Paul's question about accumulating error:

> I've added a note to my answer, in which I try to battle the accumulation of error, could you check if my assumption (that the last implementation doesn't accumulate the error) is right?

There can be several sources of error, including accumulation of round-off error; arithmetic overflow errors; time-base errors; and silly errors \[it's always easier to poke holes in other people's code!\].

To illustrate those error sources and a possible solution, consider the following code snippet:

```
 0   unsigned long int startTime = millis();
 1.  unsigned int totalTime = 3000, nSteps = 100;
 2.  int msPerStep = round(totalTime/nSteps);
 3.  byte startRed = 100, startGreen = 28, startBlue= 50;
 4.  int deltaRed   = endRed   - startRed;
 5.  int deltaGreen = endGreen - startGreen;
 6.  int deltaBlue  = endBlue  - startBlue;
 7.  byte nowRed=startRed, nowGreen=startGreen, nowBlue=startBlue;
 8.  for(int step= 0; step < nSteps; step++){
 9.     analogWrite(RPin, nowRed   += deltaRed/step);
10.     analogWrite(GPin, nowGreen += deltaGreen/nSteps);
11.     nowBlue = startBlue + (deltaBlue/amountOfSteps)*step;
12.     analogWrite(BPin, nowBlue);
13.     long int elapsed = millis()-startTime;
14.     analogWrite(RPin, startRed + (deltaRed*elapsed)/totalTime);
15.     delay(msPerStep);
16.  }

```

First, consider `currentRed += deltaRed/step` expression in line 9. In the first loop pass it adds an undefined quantity, `deltaRed/0`, to `nowRed`; in the next, it adds `deltaRed/1` to `nowRed`; then `deltaRed/2`; and so forth.

Line 10 corrects the silly error of dividing by `step` instead of `nSteps`. But there can be significant accumulation of round-off error. For example, if `deltaGreen` is 199 and `nSteps` is 100, it repeatedly adds 1 instead of 1.99, and ends up with the Green level 99 counts short of being correct.

Line 11 attempts to compensate for that problem by adding a step-proportional amount of `deltaBlue` to `startBlue` at each step. However, due to the parenthesized order of arithmetic it has exactly the same round-off error problem as line 10 – it adds exactly one unit per step for my example numbers. To try to avoid this problem, one might write `(deltaBlue*step)/amountOfSteps` in place of `(deltaBlue/amountOfSteps)*step`. This will do accurate arithmetic except can easily overflow an `int` so should perhaps be written instead as `(deltaBlue*(long int)step)/amountOfSteps`.

Even if line 11 is rewritten to avoid truncation, round-off, and overflow errors, it still is subject to time-base errors. Like the color numbers, the `delay()` parameter `msPerStep` is subject to accumulation of round-off errors. During the `for` loop, several hundred milliseconds of error could accumulate, leading to mismatched or jittery color levels. To avoid that error, instead measure elapsed time (as in line 13) and make color levels proportional to elapsed time (as in line 14). In addition, one probably should change the `for` loop to a `do { ... } while (elapsed < totalTime)` loop, ie, let the loop run until the right time has passed, rather than some arbitrary number of passes.
> 1 votes

# Answer
*I'm not sure what you have working or what you haven't. I'm also not sure what you've tried and which problems occured. However, I'd like to give you atleast a basic answer before I vote for: "Too broad".*

It's actually quite simple (but you can make it difficult).

**Step 1**

Imagine the effect, what are you actually trying to achieve? Fade out the current color and fade in a new one? Or are you trying to shift the color from one to another?

**Step 2**

Find resources online. You're likely not the first person to have tried this ;D https://www.arduino.cc/en/Tutorial/ColorCrossfader

**Step 3**

Iteratively and rationally develop your project. Know what you have and what you need.

You've got these parameters:

* Current R/G/B values.
* R/G/B values you wish to shift/fade to.
* Duration of the fading effect (total time of the animation, total amount of frames for the animation)

Your goal:

Is making an "animation". Changing the colors over time, as an fading effect.

We will simplyfy it by starting with only the R (red) channel, we can add the rest later.

Let's say we want to fade from 100 to 255 in 3 seconds. We're going to have 155 different levels of brightness over 3 seconds. Which is roughly 20ms per step.

```
for(currentRed; currentRed < setRed; currentRed++){
   analogWrite(redPin,currentRed);
   delay(msPerStep);
}

```

But that won't really work for multiple channels... Just add another channel and find your way out that challenge. (I added blue, but you could add up to x amount with this code I believe)

```
unsigned char currentRed = 100;
unsigned char currentBlue = 50;
unsigned char setRed  = 255;
unsigned char setBlue = 255;
int differenceRed  = setRed  - currentRed;
int differenceBlue = setBlue - currentBlue;
unsigned int totalTime = 3000; //3sec (in ms)
unsigned int amountOfSteps = 100;
int msPerStep = round(totalTime/amountOfSteps);

for(unsigned int step= 0; step < amountOfSteps; step++){
   analogWrite(redPin, currentRed  += differenceRed/step);//We could optionally calculate the difference per step beforehand, to avoid having doing dividing in a loop (may be a tad inefficient this way).
   analogWrite(bluePin,currentBlue += differenceBlue/step);//But well, in the delay you're also just wasting CPU, so who cares? :)
   delay(msPerStep);
}
currentRed = setRed;//Compensate for rounding step values
currentBlue=setBlue;//You may want update the analog pins, though I presume it would be barely visible to a person.

```

You could get rid of the blocking delay, but well, that's beyond the scope of this answer.

I haven't tested the code, nor the algorithm extensively. You may check what happens if the setpoint is lower as the current value.

So now you can test the algorithm, finetune/adapt it to your liking and make a function out of it :)

---

---

As noted by jwpat7, combining floating point math and integers on Arduino will have quite an error in it. And if you keep applying the same error each step, it will accumulate.

I'm not sure how significant it will be for LED applications, you usually can't see the difference between a few "levels" of brightness.

I've made my own implementation of which I think may battle this problem:

```
unsigned char previousRed = 100;
unsigned char previousBlue= 50;
unsigned char currentRed = previousRed;
unsigned char currentBlue = previousBlue;
unsigned char setRed  = 255;
unsigned char setBlue = 255;
unsigned int totalTime = 3000; //3sec (in ms)
unsigned int amountOfSteps = 100;
int msPerStep = round(totalTime/amountOfSteps);

for(unsigned int step= 0; step < amountOfSteps; step++){
    currentRed = previousRed + ((setRed-previousRed)/amountOfSteps)*step;
    currentBlue = previousBlue + ((setBlue-previousBlue)/amountOfSteps)*step;
    analogWrite(redPin, currentRed);
    analogWrite(bluePin,currentBlue);
    delay(msPerStep);//If the algorithm is inefficient, you COULD compensate for it by lowering the msPerStep.
}
currentRed=setRed;
currentBlue=setBlue;

```

I believe that, by completely recalculating it every step, the error won't accumulate.

This, however, may be a lot more inefficient than what jwpat7 describes. But atleast it's easy to understand. Since you're throwing most of the cycles away by waiting for the next frame and can barely see the difference between "100 and 102" intensity from PWM, I think it's a viabale option.
> 0 votes

---
Tags: led, wifi, c
---


# Question
Title: What is a cheap way to interface a USB keyboard to an Arduino Uno?
What is the cheapest way to interface a USB 2.0 keyboard to an Arduino Uno?

The keyboard does not support PS/2 emulation (interfacing a PS/2 keyboard to Arduino is easy). So this means the Arduino will read the USB keyboard's keystrokes - whatever their speed of input is.

If it can be solved using an IC then DIP is preferred as it quicker to work with for soldering and pluggin into breadboard.

# Answer
> 1 votes
The cheapest way is to get a plain PS/2 (or PS/2-USB convertible) keyboard instead of USB1.1 (I hope you mean the standard LS keyboard, since USB2.0 HS keyboards hardly exist), and interface it to GPIOs in accord with known solutions.

The Arduino Uno is designed around Atmega8u2 and ATmega328P chips, which can act as USB device only, FS and LS. To interface it with a dedicated USB keyboard (which is a USB device), the you need to have the Arduino **as a USB host**. Probably it is possible to emulate some limited hardware host functionality for LS mode (1.5Mbps) over GPIOs, but it will be a remarkable effort.

---
Tags: usb
---


# Question
Title: How to interpret accelerometer output data?
I'm running my accelerometer through my Arduino mini and outputting my values using the following values

```
 // print the sensor values:
  Serial.print(analogRead(xpin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(ypin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(zpin));
  Serial.println();
  // delay before next reading:
  delay(100);

```

Here's an example.

The x,y,z values that are outputted are quite high even the arduino is not moving. I'm new to Arduino programming and would love some understanding on how to convert these x,y,z to an Acceleration value ie. Is the arduino moving or not?

# Answer
The accelerometer will output a specific number of volts (or millivolts) per *g*. You need to find that information in the datasheet for your accelerometer.

Then you need to take the readings you make through `analogRead()` and convert them to a voltage. Then that voltage can be used, combined with the value you found above, to determine the *g* reading.
> 1 votes

# Answer
As has been noted by @Majenko, you are reading voltages with your `analogRead()` as a ratio of the A/D reference voltage specified for the Arduino you are using rather than true accelerations. For example, your first pass readings of x=9, y=8, z=8 were really saying x = Vref * 9 / 1023 volts. The datasheet for your accelerometer sensor will specify a calibration factor to be applied in terms of Volts/g.

Therefore, if you wish to read in terms of actual acceleration g. then you will need to first convert the value read from the A/D to volts and then convert the voltage to g by applying the datasheet sensitivity factor.

You can brute force this conversion calculation if you wish by using variables of type `float`. If you wish to avoid floating point arithmetic and use fixed point calculations, you can consider defining the result as being multiplied by 10 or 100. (Example: a reading of 1.0g might be reported as 10 if using 10x reporting or it might be reported as 100 if using 100x reporting.

Additionally, if you suspect some jitter in your measurements, you can read multiple times to average and smooth the readings. You can then divide the total of the readings to get an average.

Example Code for Single Axis Using Integer Variables (Untested)

```
#define AXIS_PIN A0

void setup() {
  // Insert Setup Code Here

}

void loop()
{
  int reading;

  reading = 0;

  // Read the sensor axis value 4 times
  //  Use a short delay between reads if you might exceed
  //    the read frequency of the sensor.
  // Use millis() for non-blocking aspects if needed
  for (int readLoop = 0; readLoop < 4; readLoop++)
  {
    reading += analogRead(AXIS_PIN);
    delay(2);
  }

  // Map the reading to a voltage using a 100x multiplier
  //  The raw reading has a range of (0 to 1023) * 4
  //  The mapped reading has a range of (0 to 3300) * 4
  //    (assuming a 3.3v reference voltage)
  //    (Use 0 to 4 * 5000 if required by the choice of sensor and
  //      Arduino used.)
  reading = map(reading, 0, 4 * 1023, 0, 4 * 3300);

  // Find the average by now dividing by 4
  reading = reading >> 2;

  Serial.print(F("Average axis reading (x100) is: "));
  Serial.println(reading);

  // Read the axis once per second
  // Use millis() for non-blocking aspects, if needed
  delay(1000);
}

```

EDIT NOTE: I see you have now specified an Adafruit ADXL345 sensor. Be aware that this sensor references 3.3v (offset ratio-metric, ie +/- 1.65v) even though it runs off of a 5v power source. Depending on which Arduino you are using, you may have to adjust the map() function input above to account for the proper output. You can try something like `map(reading, 0, 4 * 1023, -2 * 3300, 2 * 3300);`.

ADDED EDIT: The above will output a converted voltage. If you would like to output directly in units of g (x100), then you can change the `map()` function to something like `map(reading, 0, 4 * 1023, -2 * 300, 2 * 300)` assuming the Adafruit ADXL345 (PRODUCT ID: 163) which reads to +/- 3g.
> 0 votes

---
Tags: accelerometer
---


# Question
Title: very lightweight low power microcontroller with memory?
I have build a couple of projects using arduino. For a new project I want to log skin surface temperature vs. time (just perhaps a few times per day) and possibly other easy to obtain info such as voltage.

I need to make everything as small and lightweight as possible (since it would be measuring skin temperature on a small mammal), i.e. below 5g, lighter if possible, ideally 3g, including the battery, so that it doesn't upset the 50-100g animal too much.

I read it might be possible to change the arduino pro mini to use less current by getting rid of the voltage regulator? but perhaps it is more sensible to change completely and learn to program another type of microcontroller which someone could recommend? It would need to be possible to operate it directly from a lightweight coin cell or similar lightweight battery. (I'm also not sure how to find a lightweight 3.3V battery for the arduino pro mini, I guess they exist but I can only find 3V batteries so far). If it has onboard memory to save temperature every few hours which could be downloaded later that would be ideal (I would also be interested if anyone has recommendations for memory). I know it's possible to buy an "Ibutton" but if I have time I would like to make my own so that I can add other sensors and obtain more information.

# Answer
I made up a small torch locator which used an ATtiny85 powered from a button-cell (CR2032). It looks like this:

Other side:

That currently weighs 5.9g. The battery-holder weighs 1.6g so you could save that by making a more light-weight holder (perhaps a bit of plastic for insulation, and soldering directly to the battery). The chip socket weighs at least 0.5g, so you could save that as well by soldering to the processor pins. So we are down to 3.8g.

The ATtiny85 has 512 bytes of EEPROM which you could use to log readings to. I'm not sure about a clock if you are trying to save weight, but if you start it at a known time, you could have a reasonable estimate of the time by using the `millis()` function to find miliiseconds since startup.

I made another one a while ago which flashes an LED every couple of seconds:

That is similar. The processor is there (upside down under the chip socket) and the battery is underneath. That weighs 6g. The battery has lasted a couple of years, and that is flashing an LED every couple of seconds!

Instead of the LED you could have a thermistor to read the temperature.

You could program it to take a reading every few hours and save it to EEPROM. Then when instructed (eg. by joining a couple of pins) it could output the readings to another pin (via serial).

You could save more weight by using SMD (surface mounted) devices, and perhaps using a tiny circuit board you could get made up.

---

## Code

The code for my torch locator is below. Of interest is the fact that it sleeps most of the time. Also it sleeps during the ADC sampling. Although in my case I am measuring a LDR (light dependent resistor) the code for measuring a thermistor would be similar. You just need to do some calculations at the end to turn the reading into a temperature.

```
// ATtiny85 torch detector
// Author: Nick Gammon
// Date: 25 February 2015

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

/*

  Pin 2 (PB3) <-- LDR (GL5539) --> Pin 7 (PB2) <----> 56 k <----> Gnd

  Pin 5 (PB0) <---- LED ---> 100 R <-----> Gnd

*/

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer

const byte LED = 0;          // pin 5
const byte LDR_ENABLE = 3;   // pin 2
const byte LDR_READ = 1;     // Ain1 (PB2) pin 7
const int LIGHT_THRESHOLD = 200;  // Flash LED when darker than this

 // when ADC completed, take an interrupt
EMPTY_INTERRUPT (ADC_vect);

// Take an ADC reading in sleep mode (ADC)
float getReading (byte port)
  {
  power_adc_enable() ;
  ADCSRA = bit (ADEN) | bit (ADIF);  // enable ADC, turn off any pending interrupt

  // set a2d prescale factor to 128
  // 8 MHz / 128 = 62.5 KHz, inside the desired 50-200 KHz range.

  ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);

  if (port >= A0)
    port -= A0;

#if defined(__AVR_ATtiny85__)
  ADMUX = (port & 0x07);  // AVcc
#else
  ADMUX = bit (REFS0) | (port & 0x07);  // AVcc
#endif

  noInterrupts ();
  set_sleep_mode (SLEEP_MODE_ADC);    // sleep during sample
  sleep_enable();

  // start the conversion
  ADCSRA |= bit (ADSC) | bit (ADIE);
  interrupts ();
  sleep_cpu ();
  sleep_disable ();

  // reading should be done, but better make sure
  // maybe the timer interrupt fired

  // ADSC is cleared when the conversion finishes
  while (bit_is_set (ADCSRA, ADSC))
    { }

  byte low  = ADCL;
  byte high = ADCH;

  ADCSRA = 0;  // disable ADC
  power_adc_disable();

  return (high << 8) | low;

  }  // end of getReading

// watchdog interrupt
ISR (WDT_vect)
{
   wdt_disable();  // disable watchdog
}  // end of WDT_vect

#if defined(__AVR_ATtiny85__)
  #define watchdogRegister WDTCR
#else
  #define watchdogRegister WDTCSR
#endif

void setup ()
  {
  wdt_reset();
  pinMode (LED, OUTPUT);
  pinMode (LDR_ENABLE, OUTPUT);
  ADCSRA = 0;            // turn off ADC
  power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
  }  // end of setup

void loop ()
  {
  // power up the LDR, take a reading
  digitalWrite (LDR_ENABLE, HIGH);
  int value = getReading (LDR_READ);
  // power off the LDR
  digitalWrite (LDR_ENABLE, LOW);

  // if it's dark, flash the LED for 2 mS
  if (value < LIGHT_THRESHOLD)
    {
    power_timer0_enable ();
    delay (1);  // let timer reach a known point
    digitalWrite (LED, HIGH);
    delay (2);
    digitalWrite (LED, LOW);
    power_timer0_disable ();
    }

  goToSleep ();
  }  // end of loop

void goToSleep ()
  {
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  noInterrupts ();       // timed sequence coming up

  // pat the dog
  wdt_reset();

  // clear various "reset" flags
  MCUSR = 0;
  // allow changes, disable reset, clear existing interrupt
  watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
  // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
  watchdogRegister = bit (WDIE) | bit (WDP2) | bit (WDP1) | bit (WDP0);    // set WDIE, and 2 seconds delay

  sleep_enable ();       // ready to sleep
  interrupts ();         // interrupts are required now
  sleep_cpu ();          // sleep
  sleep_disable ();      // precaution
  }  // end of goToSleep

```
> 15 votes

# Answer
I would personnaly suggest an ATtiny 45/85. It is pretty much a small AVR with 5 GPIOs. You can program it with the Arduino IDE and use the Arduino as ISP. If you can design you own custom PCB, a SMD version of the ATtiny is small, low and compact. The total circuit to make the ATtiny function is also minimal.

Also, at a low clock speed (0-4MHz), you can power the ATtiny at a voltage as low as 1.8V. You could probably even run it at 1.5V, but this is not totally recommended. If you want to be safe, a 3V coin cell will be small, flat, and it can last probably many years. It is also a little safer compared to lipos which have many risk, especially if you mount it on an animal that you can't really control.

I would also recommend SMD components if possible. It lets all the component be lower and it doesn't hurt or sratch the skin of the person/animal you are monitoring.
> 8 votes

---
Tags: power, atmega328, arduino-pro-mini
---


# Question
Title: ESP-12e, Arduino IDE, NeoPixel Strip - Flickering
I have a NeoPixel RGB strip connected directly to my NodeMCU ESP12-e board. I'm using Arduino IDE with the NODEMCU 1.0 ESP 12-e module to programm the board.

```
ESP12-e | NeoPixels
GND    ---> GND
3.3V   ---> +5V
GPIO0  ---> Din

```

With the 3.3V output I have a strange flickerin on the LEDs. When I use the VIV 5V output of the ESP12-e the flickerin is gone, but the lights turn off after a few seconds and some lights turn on with strange behavior.

I guess 5V is to much for the board? What can I do to get rid of the 3.3V flicker?

**EDIT:** I'm using WS2812B LED Strip Band with 224 LEDs 5050 SMD connected directly (see above) to a NodeMCU ESP-12e (http://learn.acrobotic.com/uploads/esp8266\_devkit\_pinout.png)

I'm using:

```
#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>

```

I'm turning LEDs on for example like this:

```
#define PIN 0
#define NUMPIXELS 224

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int individualPixels[NUMPIXELS];
  void allOn(){
      for(uint16_t i=0; i<pixels.numPixels(); i++) {
        individualPixels[i]=1;
        pixels.show();
      }
    }

   for (int i=0; i<sizeof(individualPixels); i++){
    if (individualPixels[i]==1){
      pixels.setPixelColor(i, pixels.Color(red,green,blue)); //Set Neopixel color
    }
    else{
      pixels.setPixelColor(i,pixels.Color(0,0,0));
    }
  }
  pixels.show();

```

The ESP12-e is plugged in via USB Power

Thanks in advance

# Answer
I found a solution for my problem:

```
USB Powerbank --> ESP12-e --3.3V--> WS2812 --> FLICKER
USB Powerbank --> ESP12-e --5V--> WS2812  --> Strange behavior

```

**Solution:**

```
USB Powerbank with 2 Outputs:
Output 1 --> ESP12-e
Output 2 --> WS2812
Connect GND form Output 2 with GND ESP12-e

```

This works without level shifter.
> 0 votes

# Answer
Have a google for (WS2812 or Neopixels) and ESP, it should give several good hints on how to wire it up reliably. Also really read this: https://learn.adafruit.com/adafruit-neopixel-uberguide/overview .

But some things to consider:

* WS2812 requires 5V, so you do want to use a 5v source, not 3.3v.
* Make sure all your grounds are connected together, especially if you have a separate power supply for the leds.
* The data input on the WS2812 needs a 5v high signal, especially when the WS2812 is (correctly) powered by 5v. This means you probably need some kind of level shifter, which needs to be able to switch fast as well, cause it's a pretty high frequency signal.
* 224 WS2812's can chew up a lot of power, so make sure your 5v source can handle that. When all are set to full white, it's 20ma per color per led, that's 60ma per led, so 13,44 AMP maximum. Your average USB charger isn't gonna cope with that :) You can use a power supply which provides less power if you make sure you only turn on a few leds/colors at a time, but if you accidentially turn on more, voltage is gonna drop and stuff will stop working :)
> 1 votes

---
Tags: esp8266
---


# Question
Title: RFID Reader ID12-LA reads every card as ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
My new RFID reader ID12-LA by SparkFun can recognise an RFID tag, but it can't read its tag number - the Arduino IDE outputs the tag as ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

Any help on how to convert this into a proper ID would be much appreciated - btw I have tried other baud rates; no difference.

Thanks, Raihaan

Edit - the code I'm using is this:

```
#include <SoftwareSerial.h>

SoftwareSerial rSerial(4,5);

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

void loop() {
    if (rSerial.available() > 0) {
        int b = rSerial.read();
        Serial.print(b);
        Serial.print(" ");
    }
}

```

This now returns `255` 6 times... Any ideas?

Schematic:

# Answer
If you have one of the regular Arduino models, the hardware UART is connected to pins 0 and 1, which are also used by the USB programmer and in your case obviously your serial monitor, on which you expect to see some output.

Configuring a SoftwareSerial on pins 0 and 1 is probably not going to work at all. If you need the USB programmer to stay connected and the serial monitor for debugging, you have to use different I/O pins and setup your SoftwareSerial accordingly.

I assume that you are aware that the ID12-LA chip only works on the 125 kHz band and is incompatible with common tags running on 13.56 MHz?
> 1 votes

# Answer
You created a `SoftwareSerial` connection to read from the module and then you're printing what you just read *to the same module*. You probably want to print to the serial monitor on your PC. You should add `Serial.begin(9600);` to your `setup()` and ensure that all `print()`s are to `Serial` and not `rSerial()`.
> 1 votes

---
Tags: serial, softwareserial, rfid
---


# Question
Title: What options do I have to wirelessly connect my computer to an arduino?
For my project I have an arduino Uno connected to my robot. I need to control it wirelessly. I have thought of using a bluetooth module , but I need a larger range. Then I thought of using an RF-module like the Xbees and the 2.4 Ghz nRF24L01. However I can't use the Xbees due to budget issues. As for the nRF24L01- I understand that using the trasmitter and receiver modules I can transmit information between 2 arduinos- however I need to transmit from my computer to my remote arduino. I want to achieve this without using a second arduino at the transmitting (computer) end. Is there a way to achieve this?

# Answer
How about using wifi? The esp8266 costs as low as 3$ and has good range. here's a quick tutorial What you'll need to do is send a command to the esp8266 and in turn it'll communicate with the arduino via Serial (or Software Serial) and tell it what to do.
> 1 votes

# Answer
It is also not very cheap, but you can easy use wifi shield. The one I sent you is from arduino, but there are chinese analogs which are cheaper. You can use them either to connect your arduino to computer or to connect it to the other devices. Have fun!
> 0 votes

---
Tags: arduino-uno, bluetooth, wifi, nrf24l01+, wireless
---


# Question
Title: How to ground a arduino with an external power-source?
I have magnet hooked up to my arduino with a Darlington Transistor, like this:

The powersource is a 12V adapter

I'm pretty new to electronics but i'm told that the transistor won't work unless the ground on the arduino is the same as the ground on the external source. How do I do this in practice? Should I run a wire from the ardunio-ground to the negative pole on the powersource? How do I tell which one is the negative one?

# Answer
> 2 votes
Ground is usually (though not always, but in your case it is) the point of lowest potential in a circuit. In your circuit that is the "negative" connection of the power supply. Note that the "negative" isn't actually "negative", it is zero volts when measured from the reference point of itself.

So yes, you need to know which is the "negative" connection and connect that to ground on the Arduino.

Since you already have it wired up the negative is the one which connects to the emitter of your transistor. If you don't know which that is and you just randomly connected a random wire to a random pin then you need to investigate your power supply.

The simplest way is with a Digital MultiMeter (one of the most basic items you need to own if you are working with electronics - if you don't have one then go and buy one immediately). Set it to DC Volts in the right range then connect the two probes (correctly inserted into the right sockets on the DMM) to the power supply's output connections. If the voltage reads positive then the black probe is connected to negative. If it reads a negative value then the red probe is connected to negative.

If you cannot get a DMM but you have an LED (note: a bulb will not work) and a suitable resistor (say 2.2K) you can connect the resistor in series with the LED then connect the two to the power supply. The cathode of the LED (the pin with the flat side on the case) connects to negative. Connect the power both ways round. The way round that it lights the LED is the correct way round, and you know that the connection that goes to the cathode (flat side of the lip round the bottom of the LED) is the negative.

# Answer
> 2 votes
Majenko explained how to figure out what is what. I'm just repeating the shematics again with "additional" description:

Current limiting resistor R1 is REQUIRED, if you don't want to destroy Arduino output by over current.

About using the LED to test your power source polarity:

And again, current limiting resistor is required, or you'll burn it. As Majenko stated, it should be about 2k2.

# Answer
> 2 votes
I would be careful about "ground loops" when using two supplies connected to the mains electricity. You may get strange results. If you are using a lap top then maybe disconnect it from the charger while the PSU is plugged in the wall. Or use a battery for your coil. Or power the Arduino from a power bank. Or get a 12v USB adaptor and power the arduino from the 12v supply. Add and LED for debugging while connected to the computer. Then disconnect from the computer and plug in the 12v supply.

---
Tags: power, transistor
---


# Question
Title: How to program an nRFL01 RF module that is connected to a pc via a USB to UART/TTL adapter?
In a few of my previous questions I was told that the nRF24L01 RF Module can be connected to a pc using a USB to UART/TTL adapter. After a bit of research I understand that one way to use it is to connect it to an arduino- and then to use certain dedicated libraries like RF24.h, and nRF24L01.h to send and receive data. Though I've not been able to find any tutorial outlining the procedure for programming the nRF24L01 once its been connected to the pc. How do I send and receive data using my pc-interface? What software do I write and how do I write it?

# Answer
In short: whatever software you use on the remote end (rf24.h for example) you have to re-write on the PC using whatever language you can interface to the FT2232 with. That means having intimate knowledge of:

1. The USB to SPI adapter you choose (NOT USB TO UART!)
2. The low-level control and interfacing of the nRF24L01+ chip
3. The exact protocol used by your chosen Arduino library.

That's a lot of understanding which (by the level of your questions) is most likely way outside your area of ability.

If you equate time to money then the cost of doing what you want to do is far higher than just using a small Arduino to act as an intelligent interface between your PC and your chosen wireless system. You can discount points 2 and 3 above since they have already been done for you by the Arduino libraries and tutorials. Point 1 becomes considerably easier since you are then just talking to an Arduino using a protocol which you yourself have come up with.

So do yourself (and us) a favour and come to your senses and just plug the nRF24L01+ into an Arduino then plug the Arduino into your PC and program the Arduino to do the RF communications according to commands and instructions you send to your sketch from the PC.
> 1 votes

---
Tags: usb, nrf24l01+, wireless, uart, rf
---


title: Coding problem (gesture sensor)

text:
# Question
Title: Coding problem (gesture sensor)
Hi I am using an Arduino Mega 2560 with two sparkfun zx gesture sensors, two servos, 4 rgb leds strips and 4 light switches.

With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.

My knowledge of coding is limited so I am unsure of how to work around this, I think I have to introduce some new code. interrupts leds and servos However, I am unsure of how to introduce it.

Any help would be appreciated.

# Answer
Driving servos and LEDs from a hardware PWM may help. They will maintain a steady state even if there are interrupts. They may be a little less responsive to changes if there are interrupts.

Are you doing too much when the sensor interrupts? Typically a sensor makes multiple measurements and may be filters the results. When it is ready it interrupts. In the interrupt it should do as little as possible. Typically sending a message via global to a polling function that is not running in an interrupt. For example it may set a flag and the poling function reads the result. Reading the result in the interrupt would be bad.
> 1 votes

# Answer
> With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.

The best solution for this problem would be to use objects and the `millis()` function.

Here is a great tutorial about objects and why do we use them with the `millis()` function. I wont explain it because it it too long and this tutorial is simply better.

I would also suggest to see the `blinkWithOutDelay` example code from the Arduino IDE. It is probably the first step you have to take to learn how to use the `millis()` function.
> 0 votes

---
Tags: servo
---


# Question
Title: Arduino trim: does it remove the \n as well?
According to the manual:

https://www.arduino.cc/en/Reference/StringTrim

Trim strips one or more whitespaces from the beginning and the end. Does it also removes tabulators and \n ?

I have the following code which works:

```
 while (Serial.available()) {   // something came across the serial
      char c = (char)Serial.read();
      Command += c;
      Command.trim();
      if (c=='\n')
         {
           Complete =true;
         }
   if (Command.length() >0 && Complete) {

        if (Command == "LED_ON") {
               // Do stuff
        }

```

Although I'm not sure that it is working because of the last if statement which says: if (Command == "LED\_ON") ignores the ending \n and say ok it matched OR Command.trim() really takes off that \n.

Thank you

# Answer
Yes, \n is also removed.

The source for the trim() function is in WString.cpp.

```
void String::trim(void)
{
    if (!buffer || len == 0) return;
    char *begin = buffer;
    while (isspace(*begin)) begin++;
    char *end = buffer + len - 1;
    while (isspace(*end) && end >= begin) end--;
    len = end + 1 - begin;
    if (begin > buffer) memcpy(buffer, begin, len);
    buffer[len] = 0;
}

```

We can see it uses the `isspace()` function, but where's that function defined? `WString.cpp` only `#include`s `WString.h`, so we go there.

In `WString.h`, we can see it includes `ctype.h`. Time to go to the C++ Reference, which tells us that yes, `\n` is a "space" according to isspace(), so it is trimmed.

(note that `isspace()` is affected by localization settings. I'm not sure what the localization settings are when compiling for Arduino)
> 5 votes

# Answer
Whilst rchard2scout is quite right that `trim` will remove newlines, why not rearrange the code so it doesn't matter?

```
  char c = (char)Serial.read();
  if (c == '\n')
     Complete = true;
  else
     Command += c;

```
> 1 votes

---
Tags: serial
---


# Question
Title: Which interrupts are enabled when programming an ATTiny85 with Arduino IDE?
I have programmed a tiny85 using the Arduino IDE. I am using the pulseIn() function. Wrapping it in noInterrupts()/interrupts(); appears to make the function more consistent. This would imply that interrupts are running.

Which interrupts are running? Can I disable them?

I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.

(I know I can improve the code by not using pulseIn and using interrupts, however the question I have at the moment is which interrupts are running when I am not explicitly enabling any.)

# Answer
The only interrupt that is *always* running is the one which generates the count for `millis()` and `micros()`. Disabling interrupts disables your ability to keep track of time and use `delay()`.

Timer interrupts are also used by the `tone()` function and for sending / receiving serial data if the chip has a UART.

Disabling interrupts would also affect the use of external interrupts and pin change interrupts should you be using them.

It sounds, from your brief description, that you would only be effecting the use of `millis()` and `delay()` since you aren't using the other systems that use interrupts at all.
> 1 votes

# Answer
> Which interrupts are running?

It depends on your code which you haven't shown. The Timer 0 overflow interrupt is usually active, as that lets the library count when a millisecond is up (roughly).

If you have done a `Serial.begin` then serial interrupts would be active. If you have used the I2C library (Wire) then I2C interrupts would be active.

*(Disclaimer: That really refers to the Atmega328P. I'm not quite so sure on the ATtiny, it would depend on what the libraries do).*

---

> Can I disable them?

If you want to. Doing `noInterrupts()` is the simplest way. Note that if you disable interrupts for more than a millisecond (approximately) then the time returned by `millis` and `micros` will be wrong. Plus `delay` won't work. Plus you won't be able to serial print properly or at all.

---

> I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.

That is exactly what it does. Once activated the hardware timers can generate a PWM signal purely in hardware.

---

There are other ways of timing intervals (than `pulseIn`). One method is to use one of the other timers, configured with a small, or no prescaler. Then you can measure up to very high accuracy. I have examples of that on my page about timers.

*(The ATtiny85 only has two timers, so you couldn't use the second timer for measuring **and** do PWM output with it, however you can use Timer 0 for the PWM output). That limits the PWM frequency to its default, however you could still alter the duty cycle)*
> 0 votes

---
Tags: arduino-ide, attiny
---