# Question
Title: How high of a baud rate can I go (without errors)?
The standard is 9600 baud. That's just the *standard*. Using a Arduino Uno SMD R2, what is the highest practical baud rate I can achieve?

Bonus points for the audacious: how would you go about creating an error checking mechanism and then increasing the baud rate ridiculous high to get high transfer rates?

# Answer
> 80 votes
There are several factors here:

* How high of a baud-rate can the ATmega328P MCU achieve?
* How high of a baud-rate can the USB-Serial interface achieve?
* What is the oscillator frequency on the ATmega328P?
* What is the oscillator frequency on the USB-serial interface (if it has one)?
* How tolerant is the USB-serial interface of baud-rate mismatch?

All of these factors are relevant to determining the maximum achieveable baud rate. The ATmega328P uses a hardware divisor from it's clock-rate to generate the base-clock for the serial interface. If there is no integer ratio from the main clock to the bit-time of the desired baud rate, the MCU will not be able to *exactly* produce the desired rate. This can lead to potential issues, as some devices are much more sensitive to baud-rate mismatch then others.

FTDI-based interfaces are quite tolerant of baud-rate mismatch, up to several percent error. However, I have worked with specialized embedded GPS modules that were unable to handle even a 0.5% baud rate error.

General serial interfaces are tolerant of ~5% baud-rate error. However, since each end can be off, a more common spec is +-2.5%. This way, if one end is 2.5% fast, and the other is 2.5% slow, your *overall* error is still only 5%.

---

Anyways. The Uno uses a ATmega328P as the primary MCU, and a ATmega16U2 as the USB-serial interface. We're also fortunate here in that both these MCUs use similar harware USARTs, as well as 16 Mhz clocks.

Since both MCUs have the same harware and clock-rate, they'll both have the same baud-rate error in the same direction, so we can functionally ignore the baud error issue.

Anyways, the "proper" answer to this question would involve digging up the source for the ATmega16U2, and working out the possible baud-rates from there, but since I'm lazy, I figure simple, empirical testing will work.

A quick glance at the ATmega328P datasheet produces the following table:

So given the max stated baud-rate of 2 Mbps, I wrote a quick test program:

```
void setup(){};

void loop()
{

  delay(1000);
  Serial.begin(57600);
  Serial.println("\r\rBaud-rate = 57600");
  delay(1000);
  Serial.begin(76800);
  Serial.println("\r\rBaud-rate = 76800");
  delay(1000);
  Serial.begin(115200);
  Serial.println("\r\rBaud-rate = 115200");
  delay(1000);
  Serial.begin(230400);
  Serial.println("\r\rBaud-rate = 230400");
  delay(1000);
  Serial.begin(250000);
  Serial.println("\r\rBaud-rate = 250000");
  delay(1000);
  Serial.begin(500000);
  Serial.println("\r\rBaud-rate = 500000");
  delay(1000);
  Serial.begin(1000000);
  Serial.println("\r\rBaud-rate = 1000000");
  delay(1000);
  Serial.begin(2000000);
  Serial.println("\r\rBaud-rate = 2000000");
};

```

And then looking at the relevant serial port with a serial terminal:

So it appears the hardware can run at 2,000,000 baud without problems.

Note that this baud rate only gives the MCU 64 80 clock-cycles per byte, so it would be very challenging to keep the serial interface busy. While the individual bytes may be transferred very rapidly, there is likely to be lots of time when the interface is simply idle.

---

Edit: Actual Testing!

The 2 Mbps is real:
each bit-time is 500 ns, which matches exactly with what is expected.

Performance issues! Overall packet length:
500 Kbaud:

1 Mbaud:

2 Mbaud:
Note: The noticeable overshoot is due to poor scope probe grounding practices, and is *probably* not real. I'm using the ground-clip-lead that's part of my scope probe, and the lead-inductance is likely the cause of the majority of the overshoot.

As you can see, the overall transmission length is the same for 0.5, 1 and 2 Mbaud. This is because the code that is placing the bytes in the serial buffer is poorly optimized. As such, you will never achieve anything better then an *effective* 500 Kbaud, unless you write your own serial libraries. The Arduino libraries are very poorly optimized, so it probably wouldn't be *too* hard to get a proper 2 Mbaud, at least for burst transmissions, if you spent a bit of time on it.

# Answer
> 9 votes
The Arduino Serial Monitor window limits you to 115200, but that's not the highest baud rate capable. You can read the Atmel and the FT232 (or whatever you're using) datasheets to find out the maximum but I am able to successfully use 230400 (twice as fast as the largest the Arduino Serial Monitor supports) with no issues.

If you want to see the results in your computer, you will need another serial monitor that supports other baud rate options. I like CoolTerm and Termite.

Do note that this heavily depends on your clock speed as well.

Here's a calculator to help you with calculating what's possible.

# Answer
> 3 votes
This is probably one of the few aspects where el-Cheapo boards differ from original boards. The maximum serial transfer rate is pretty much only limited by the quality of the board and its layout. Once the serial data enters either AVR or USB interface chip, the data will be processed differently from the serial UART protocol.

Keep in mind though that the microcontroller has some basic hardware to shift in/out serial data to/from the IO pins, but the absolute maximum rate is limited to the 16MHz clock (for AVRs). Once a byte is moved to the serial buffer, the UART hardware will take over and push out / pull in the bits on its own. An AVR at best reaches 16M instructions per second and the interrupts used to fill the serial buffer have some overhead (at least 8 clock ticks for the interrupt handling + instructions to save current state + several instructions for actually filling the buffer). At a given bitrate, the protocol will run at a whopping n bits per second, but your controller needs more time to fill the serial buffer than it needs to actually output the data, resulting in a lower average throughput than you expect and the UART idling for a relatively long time. Disadvantage is the increased probability for bit errors.

Another effect to remember is that all the overhead required to push data out onto UART (or pull it in) cannot be spent in your actual program, again affecting the average practical throughput. You can only use every instruction cycle once, either for filling the buffer or for computing the main loop.

The maximum throughput is therefore dependent on the application you use (how fast is data generated/computed/ready to move to/from the serial buffer) and the actual 'physical' bitrate is only a small part of the design decision.

# Answer
> 3 votes
Error checking is actually very easy and there is an AVR lib that does this in a one liner.

Read up on `util/crc16.h` and you should be good to go in no time with the included examples.

CRC is quite robust and fast for simple applications.

---
Tags: arduino-uno-smd
---


# Question
Title: Are there different revisions of Arduino Uno SMD?
I know there are different revisions of the Arduino Uno itself, but are there any revisions of the SMD? If they are is SMD R2 identical to through-hole R2? I have a board marked R2 SMD and I am wondering if that is the only version that they produced in SMD format and just are signifying that it is compatible with the standard R2.

# Answer
> 4 votes
The only difference with the SMD Uno is the fact you can't remove the chip. There are also 2 extra analog comparators not connected to anything.

The SMD boards are compatible with the thru-hole boards, but they have SMD components, which apparently make them easier to make and cheaper. As I said before, the two extra analog inputs (A7 and A6) are left unconnected on the official boards.

Here is my Uno R3:

---
Tags: arduino-uno-smd, revisions
---


title: Why is int only 2 bytes?

text:
# Question
Title: Why is int only 2 bytes?
When using C/C++ on other platforms, the `int` type is typically 4 bytes (or potentially more). However, on Arduino, it's only 2 bytes.

Why is it different? Does it affect performance if I always use the 4 byte `long` instead?

# Answer
> 10 votes
The ATmega328 used in a lot of Arduinos is a 8-bit microcontroller. This means that registers are 8-bits, the data bus is 8-bits, the ports are 8-bits. There are some minimal 16-bit aspects to the system (e.g. one of the timers), but nearly everything is 8-bits.

Therefore, most operations handle 8-bits at a time. Working on anything except 8-bits (i.e. 16-bit or 32-bit integers and floating point numbers) requires what could essentially be described as software emulation, where the compiler uses multiple instructions to work on these larger variables.

8-bits is obviously adequate to address a 8-bit port. It's also enough to deal with many loop counters, return values, and ASCII characters. It isn't really enough though when dealing with numbers. A signed 8-bit int (int8\_t) can only represent -128 -\> +127. Unsigned (uint8\_t) can only represent 0 -\> 255.

8-bit integers are quite limiting. C/C++ int must represent at least -32,678 -\> +32,767 so maps to int16\_t - the smallest size that will do so. This gives a good balance of range and efficiency. This is especially important when beginners are learning - overflow is not really something that non-programmers understand.

There is a performance impact of doing this however, because most 16-bit operations take at least twice as long as an 8-bit operation, and use twice as many registers. This may or may not make a difference to you.

Many of us switch to the native types such as int8\_t and uint8\_t as it gives you far more control.

# Answer
> 3 votes
One important fact about C and C++ languages is that their respective standards do not define the size (in bytes) of integral and floating point number types.

They just define minimal ranges and relation between these ranges, e.g.

```
range(short) <= range(int) < range(long)

```

So the size of e.g. an `int` will typically depend on:

* the target platform (processor)
* the compiler itself

---
Tags: programming, c++, data-type, performance
---


# Question
Title: Why do I need to include libraries used in other libraries?
I have a simple library which uses another library.

Here is the header:

```
#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <HardwareSerial.h>

class DerivedClass
{
private:
    HardwareSerial* serial;

public:
    DerivedClass();
};
#endif

```

And the CPP:

```
#include "DerivedClass.h"

DerivedClass::DerivedClass()
{

}

```

And the sketch:

```
#include <DerivedClass.h>

void setup()
{
}

void loop()
{
}

```

This works fine.

However, if I change the library header to this:

```
#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <SoftwareSerial.h>

class DerivedClass
{
private:
    SoftwareSerial* serial;

public:
    DerivedClass();
};
#endif

```

The sketch fails to compile:

> /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9: error: ISO C++ forbids declaration of 'SoftwareSerial' with no type /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9: error: expected ';' before '\*' token

If I change the sketch to:

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

void setup()
{
}

void loop()
{
}

```

i.e. including the SoftwareSerial library in the top level sketch, it compiles fine.

If I expand the library out so it actually performs actions, then if it compiles, it works.

Why is this? HardwareSerial is a built-in part of the Arduino, located in *hardware/arduino/cores/arduino* and SoftwareSerial is in *libraries*, but why would the build process differentiate between the two.

# Answer
If I remember correctly this is in fact a limitation of the **Arduino IDE**.

If you use a better IDE (personally I use Eclipse with the Arduino plugin) it works as it should, i.e. if you include a library A that includes another library B, then in the end you won't get compile-time errors and both B and A will be included in the final binary.
> 3 votes

---
Tags: library, c++, build
---


title: How precise is the timing of pulseIn()?

text:
# Question
Title: How precise is the timing of pulseIn()?
I've been using the `pulseIn()` function for processing PWM-based binary data encoding. It works well for distinguishing pulses which are significantly different lengths, e.g. 500us vs. 1500us. That makes it more than sufficient for handling typical IR remotes.

However, I want to make my own IR system which can use more than 2 pulse lengths, so that data transfer can occur faster. Ideally, I'd like to use 8 different pulse lengths for octal encoding (e.g. 200us, 400us, 600us, etc.).

I've noticed quite significant variations in the values returned by `pulseIn()` though (+/- 10%). I expect at least some of it is introduced by the IR transmitter and receiver modules, but I don't have good enough equipment to verify that.

Assuming I can mitigate that external error, is `pulseIn()` likely to be precise enough to distinguish such similar pulses?

# Answer
The pulsein() function is very lossy, in that it is a hard loop and returns a number * the assumed clock cycles it takes for per loop

```
...
// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask) {
  if (numloops++ == maxloops)
    return 0;
  width++;
}

// convert the reading to microseconds. The loop has been determined
// to be 20 clock cycles long and have about 16 clocks between the edge
// and the start of the loop. There will be some error introduced by
// the interrupt handlers.
return clockCyclesToMicroseconds(width * 21 + 16);

```

---

The most accurate method for capturing the timing of a PIN is use the INPUT CAPTURE FEATURE. Look at the this example. It enables the input capture at 1x of CPU for max resolution and each edge of the input pin captures the timer's clock value for reading from the generated Interrupt service. It also enables the timer overflow interrupt to as to maintain large absolute time, to be capture. Since the 1x will roll rather quickly. The captures store the time into an array for reading by the main loop.

---

Where for signals over IR the typical library to use is shirriff/Arduino-IRremote library. Where it has several demo's that will read and send the IR from a demodulated signal. To allow one to build a sketch of their own design. This code originally creates a timer interrupt that polls the input pin at a rate determine by

```
#define USECPERTICK 50  // microseconds per clock interrupt tick

```

in the IRremote.h file. For my purposes I have change it to 25 us. Where I find this still can be intermittently missing pulse streams.

Note the demodulation is best accomplished within the IR receiver, which in turn outputs this signal of interest. Where to add some background. Using the typical 38KHz modulation, equates to a minimum resolution of 26.3uS per pulse's cycle. sherriff's library shows typically most bauds or bits are in the order of 10+ pulses. Which appear to meet your desired timings.

microtherion/Arduino-IRremote fork of shirriff's work improves the reception by replacing the timer interrupt polling of the pin with the use of PinChangeInterrupts. Which I have merged into my own mpflaga/Arduino-IRremote fork, that adds several other features.

So you could use any of the above libraries. Or create your own app that uses either of the below to capture edges.

1. polls on a Timer event (e.g. 50uS)
2. captures the micros() on a PinChangeInterrupt
3. uses Input Capture Interrupts to grab the exact time
> 11 votes

# Answer
Here is some test data of a `pulseIn` test. One Arduino sent what were supposed to be 14us pulses, and the other spat out this data:

> 18,18,18,12,18,18,18,18,18,18,18,18,18,18,18,18,18,24,19,18,18,18,18,18,24,18,18,18,19,18,18,12,18,18,19,18,18,18,18,18,18,18,18,18,18,18,19,18,19,24,18,18,18,18,18,18,18,24,18,18,18,18,18,18,18,18,18,18,18,18,18,19,18,18,18,18,18,18,18,18,18,18,19,18,18,18,11,18

As you can see, the pulses are by no means accurate. The time would be more accurate if the sending and recieving ends were written in assembly, or even offloaded to their own processors.
> 2 votes

---
Tags: pwm, pulsein, timing
---


# Question
Title: Can a stepper motor be controlled directly from an Arduino?
I'm planning to build a simple XY plotter, and have been looking at the possibility of using a pair of small 5V 4-phase steppers to provide the movement. In my research, I've often seen stepper driver boards advertised, ranging from very big and expensive, through to quite small and cheap. Some of them actually look like little more than a darlington array on a PCB.

Do I really need one of those external driver boards, or can I control the steppers directly from my Arduino?

# Answer
Generally, stepper motors cannot be controlled by an Arduino pin. They have a current draw of over the 20mA any single pin can supply.

Kickback is also a problem. Because the motors have moving magnetic parts inside, they will continue to generate electricity after power has been cut. this will almost certainly cause enough negative voltage that is enough to fry your Arduino.

A solution is to use a motor driver chip or shield. This one is a good example. These have transistor based chips that can drive enough current to power a motor, and diodes to mitigate the kickback from the motors.
> 11 votes

---
Tags: motor
---


# Question
Title: Logging multiple gigabytes of data with Arduino
I have Arduino Uno with SD card shield. I'm planning to log a huge amount of data from various sensors - including accelerometers and 3D compass - to the SD card.

However, I have understood that Arduino, 64GB SD, FAT and large amount of data are not working too well.

Does Arduino work well with this amount of data on FAT? There's no need to read any data from SD on Arduino. If not, is there a better approach? Writing directly to SD without FAT?

This data logger will be on the environment where no computer or network connection is available. Performance is not an issue - around 8kB/s (over three months) is already enough.

# Answer
I'm not sure where you have the impression it won't work. I haven't used 64GB cards, but have used 32GB cards and they work fine in terms of FAT32 and writing files.

As you have already worked out, reading or searching the file system can get very slow as size increases.

That said, I have found that larger capacity cards are more likely to have problems with the SPI interface being poor quality. Consumer devices do not use the SPI interface, and it seems that some manufacturers are willing to skimp on this side of it. The SPI interface can be buggy or unstable as a result. Genuine name-brand cards should work fine though.
> 1 votes

# Answer
You should consider using sdfatlib. This is currently supported version. Where an early version of this was the predecessor the IDE's stock SD library. SdFat better supports newer and larger SdCards, along with more features.
> 1 votes

---
Tags: fat, sd-card
---


# Question
Title: Would an infinite loop inside loop() perform faster?
When you're writing a typical sketch, you usually rely on `loop()` being called repeatedly for as long as the Arduino is running. Moving in and out of the `loop()` function must introduce a small overhead though.

To avoid that, you could presumably create your own infinite loop, like this:

```
void loop()
{
    while (true)
    {
        // do stuff...
    }
}

```

Is that a viable way to improve performance? Will it cause other problems if `loop()` never returns?

# Answer
The part of the code on an ATmega core that does setup() and loop() is at follows:

```
#include <Arduino.h>

int main(void)
{
        init();

#if defined(USBCON)
        USBDevice.attach();
#endif

        setup();

        for (;;) {
                loop();
                if (serialEventRun) serialEventRun();
        }

        return 0;
}

```

Pretty simple, but there is the overhead of the serialEventRun(); in there.

Let's compare two simple sketches:

```
void setup()
{

}

volatile uint8_t x;

void loop()
{

    x = 1;

}

```

and

```
void setup()
{

}

volatile uint8_t x;

void loop()
{
    while(true)
    {
        x = 1;
    }
}

```

The x and volatile is just to ensure it isn't optimised out.

In the ASM produced, you get different results:

You can see the while(true) just performs a rjmp (relative jump) back a few instructions, whereas loop() performs a subtraction, comparison and call. This is 4 instructions vs 1 instruction.

To generate ASM as above, you need to use a tool called avr-objdump. This is included with avr-gcc. Location varies depending on OS so it is easiest to search for it by name.

avr-objdump can operate on .hex files, but these are missing the original source and comments. If you have just built code, you will have a .elf file that does contain this data. Again, the location of these files varies by OS - the easiest way to locate them is to turn on verbose compilation in preferences and see where the output files are being stored.

Run the command as follows:

> avr-objdump -S output.elf \> asm.txt

And examine the output in a text editor.
> 18 votes

# Answer
Cybergibbons's answer describes quite nicely the assembly code generation and the differences amongst the two techniques. This is intended to be a complementary answer looking at the issue in terms of *practical* differences, i.e. how much of a difference either approach will make in terms of *execution time*.

---

## Code Variations

I did an analysis involving the following variations:

* Basic `void loop()` (which gets inlined on compilation)
* Un-inlined `void loop()` (using `__attribute__ ((noinline))`)
* Loop with `while(1)` (which gets optimized)
* Loop with un-optimized `while(1)` (by adding `__asm__ __volatile__("");`. This is a `nop` instruction that prevents optimization of the loop without resulting in additional overheads of a `volatile` variable)
* An un-inlined `void loop()` with optimized `while(1)`
* An un-inlined `void loop()` with un-optimized `while(1)`

The sketches can be found here.

## Experiment

I ran each of these sketches for 30 seconds, thereby accumulating 300 data points each. There was a 100 millisecond `delay` call in each loop (without which bad things happen).

## Results

I then calculated the mean execution times of each loop, subtracted 100 milliseconds from each and then plotted the results.

http://raw2.github.com/AsheeshR/Arduino-Loop-Analysis/master/Figures/timeplot.png

# Conclusion

* An un-optimised `while(1)` loop within `void loop` is faster than a compiler optimised `void loop`.
* The time difference between the un-optimized code and default Arduino optimized code is insignificant *practically*. You will be better off compiling manually using `avr-gcc` and using your own optimisation flags rather than depending on the Arduino IDE to help you with it (if you need microsecond optimisations).

---

<sub> **NOTE:** The actual time values are not of significance here, the difference between them is. The ~90 microseconds of execution time includes a call to `Serial.println`, `micros` and `delay`. </sub>

<sub> **NOTE2:** This was done using the Arduino IDE and the default compiler flags that it supplies. </sub>

<sub> **NOTE3:** Analysis (plot and calculations) was done using R. </sub>
> 6 votes

---
Tags: programming, avr-gcc, performance
---


# Question
Title: Can I link another device to the Uno's clock?
I'm trying to use an unusual 16x2 LCD display with my Uno. As far as I know, it's an EA-X16027AR. It doesn't seem to be compatible with the HD44780 driver, which is typically used for Arduino LCD's.

According to the datasheet, the display's ENB (Enable) pin requires a clock input, described as follows:

> Basical Clock to perform Instructions in Controller LSI. The Clock at the same timing as MPU are usually input.

The timing graphs elsewhere in the datasheet show it wants a speed of around 2 MHz.

Is it possible to get the internal clock signal from the Uno, scale it down to 2 MHz, and output it to a GPIO pin or similar? Alternatively, is it possible to emulate a clock signal at that speed on-board, without adding additional timing components?

# Answer
Rather than using microprocessor-specific low-level programming, I was able to get a suitable signal using the core `tone()` function:

```
tone(11, 2000000);

```

It can be used to generate a 50% duty cycle square wave of a custom frequency on any individual GPIO pin (I'm using 11 in this case). Given the name, it's obviously designed for producing simple audio output, and 2 MHz is way above the range of human hearing.

The documentation doesn't list any upper limit on the frequency though, and the code it's based on doesn't appear to introduce any limitations. With that said, it clearly can't run faster than the internal timer it's based on (which I think will typically be 8 or 16 MHz).

It seems reasonable to assume that it will be in-sync with the microprocessor's internal clock, although I haven't been able to confirm that empirically as I don't have suitable equipment at home. Similarly, I haven't been able to confirm that it's *actually* producing a 2 MHz signal, but the LCD display is working properly so it's likely to be in the right vicinity. I had previously tried running it from regular PWM, but that didn't work, so frequency is obviously important here.

The signal can be stopped by calling:

```
noTone(11);

```

There are a couple of caveats to be aware of when using `tone()`. First of all, it can only work on a single pin at a time, so you can't generate multiple signals with it. And secondly, it will prevent some PWM output from working properly (on pins 3 and 11, according to the documentation). This is because it has to reconfigure one of the internal timers which is normally used for PWM.
> 1 votes

---
Tags: arduino-uno, lcd, oscillator-clock
---


# Question
Title: Is there a color LCD display for an arduino?
I currently have a Mega2560 with the LCD4884 Shield. The Shield is good for putting out text and simple pixel images. But I am wondering if there is something that has a full range of colours that would work with the Arduino? The screen size would only have to be a few inches in size.

# Answer
There are actually several shields that have color screens on them. Many of the shields are just regular mini TFT displays, however there are also touch screen ones.

Here is one from Adafruit that includes a MicroSD holder and a Joystick.

Here is one from Radio Shack that features a 2.8 inch screen with touch capabilities

As far as screen size, many of the screens are only about an 1 inch across, however the biggest I have ever been able to find are 2.8 in.
> 10 votes

# Answer
There's also a 2.2" Adafruit TFT.

The nice things about the Adafruit displays are: i) library support for both the display and the graphics core library. So it's easy to get it up and running.

The built in frame buffer reduces resource requirements on Arduino.
> 5 votes

# Answer
Another very cool screen is the official Arduino TFT LCD Screen. (Datasheet if you're curious.)

It's a 1.77" screen, with a resolution of 160x128. It has a micro-SD slot in it, which is easily accessible. It is a color screen, with up to 18 bit per pixel.

The extremely nice thing with this screen is that since it's officially supported, you don't need to do anything extra to support it. The official Arduino TFT library works perfectly with it. However, according to Jameco:

> Library Update: There is a known issue with the TFT library supplied in IDE versions 1.0.5 and 1.5.4 Beta. You will need to replace the library. We have zipped up the updated TFT library for both versions available here. Just delete the existing library and copy in the replacement for the appropriate IDE version and restart the IDE. (IDE v1.0.5 or v1.5.4)

So beside that minor fix, everything should be easy and quick to work with. This page has some code samples which should make it easy to work with.
> 2 votes

---
Tags: lcd, shields
---


title: How can I use Python from a sketch?

text:
# Question
Title: How can I use Python from a sketch?
I'd like to be able to use Python from a sketch. According to the Arduino playground, one can use PySerial from a computer to talk with an Arduino via Python.

It looks like from that page you can also use various API's to use Python with an Arduino from a computer. However, I'd like to know if you can execute Python directly from a sketch. It would be nice because then you could execute Python directly from a sketch, and not all of it would have to be written in Python.

If this is not possible, is there an easy way to execute Python on an Arduino? Looking at the various API's it was hard to determine exactly what they did, and if you could execute a `.py` script from a computer or from anything on the Arduino.

# Answer
> 4 votes
> It looks like from that page you can also use various API's to execute Python directly on the Arduino.

I don't see that, at all. All those links show you how to communicate with the Arduino over serial using Python on the host side.

You'd need a python interpreter to be able to run python on the Arduino. There is the Python On A Chip project and it seems like they have support for the Mega.

> 2010/09/01 (1bdb8d31f27b) New platform: Arduino Mega.

Some more info from the PyMite page:

> any device in the AtMega family which meets these requirements: 20KiB Flash and 4K RAM, will run today

I doubt you'll find anything that'll let you mix Arduino and Python code in the same sketch.

---
Tags: programming, python, sketch
---


# Question
Title: How can I rename how my Arduino shows up on the computer?
I have a clone of a Mega 2560, and the Chinese manufacture apparently had a broken shift key. To my annoyance, whenever I connect it to my computer it reads, `arduino compatible mega 2560`. With my extreme *annoyance* with *slightly* misspelled or incorrectly capitalised English, it has been very distracting to me.

However, the reason that I'm asking this question is for more than how to rename it to be capitalised. Think of how many projects could be simplified by this! Or for many Arduinos, you can label they physically and then rename them `Arduino #1`, etc. so you can tell which port it is on using device manager. If you designed a product with Arduino, then you can even rename it to your product name.

**I would imagine that there would be an easy way to do this by reburning the firmware to the \[Insert USB chip model #### here\].** I've seen it done for keyboards on the Uno, so I would imagine that you could modify it somehow.

# Answer
This string is contained in the FT232 USB to UART interface chip and the manufacturer has released the FT\_PROG tool to reprogram it. But do take note of the warning on their website: "**PLEASE NOTE - The use of some of these utilities by an end user may result in a device being rendered useless**". Another word of warning is to **ensure there is only one device connected with an FTDI-chip**.

Here is a screenshot of the MProg tool:
> 5 votes

---
Tags: arduino-mega
---


# Question
Title: Is there a limit on how much current a pin can sink?
I've been experimenting with an 8x8 LED matrix controlled by an Arduino Uno. As I think is typical, the matrix uses a common anode for each row, and a common cathode for each column.

At the moment, I've got all the matrix pins connected directly to IO pins on the Uno, and I haven't had any problems lighting the LEDs one-by-one. Going through the whole matrix like this makes updates a little slow though, meaning the LEDs aren't as bright as I'd like.

As far as I know, I can't safely light up an entire row at once, because an individual pin on the Uno isn't capable of sourcing enough current to drive 8 separate LEDs at the same time (requiring at least 10mA each to be bright enough).

It occurred to me that the reverse might be safer. If I light up an entire column at a time, then each pin only has to source enough current for one LED, which should be no problem. However, it relies on one pin potentially sinking the current from all 8, totalling at least 80mA.

Is this possible, or am I going to fry my board?

# Answer
> am I going to fry my board?

Pretty likely outcome. Here's why:

The Arduino Uno uses the atMEGA328 microcontroller, which has an absolute maximum rating of 40 mA source or sink per GPIO. Also, the total current through the supply or ground rails (i.e. the total of all current OP wants the GPIO pins to sink, or source) is rated to a maximum of ~~150~~ 200 mA.

Realistically, the current graphs in the atMEGA328 datasheet do not even go all the way to 40 mA, hence it is safest to restrict the current to perhaps 20 mA total per GPIO.

In other words, whether a GPIO is used as source or sink, the limits remain pretty low, and in practice, should be kept much lower than the absolute maximum ratings. Even below absolute maximum, running a microcontroller to too high a temperature reduces its life expectancy.

**Solution**:

Use either BJTs, MOSFETs, or some driver IC such as the ULN2003 to actually drive the current through the LEDs.
> 17 votes

# Answer
I'm going to steal my answer from when I answered this question on the last arduino SE attempt.

---

This is a bit complex. Basically, there are a number of limiting factors:

The IO lines from the microcontroller (i.e. the analog and digital pins) have both an aggregate (e.g. total) current limit, and an per-pin limit:

From the ATmega328P datasheet.

However, depending on how you define the Arduino "Pins", this is not the entire story.

The 5V pin of the arduino is *not connected through the microcontroller*. As such, it can source significantly more power. When you are powering your arduino from USB, the USB interface limits your total power consumption to 500 mA. This is shared with the devices on the arduino board, so the available power will be somewhat less.
When you are using an external power supply, through the barrel power connector, you are limited by the local 5V regulator, which is rated for a maximum of **1 Amp**. However, this it also *thermally limited*, meaning that as you draw power, the regulator will heat up. When it overheats, it will shut down temporarily.

The 3.3V regulated output is able to supply 150 mA max, which is the limit of the 3.3V regulator.

---

## In Summary

* The *absolute maximum* for any single IO pin is **40 mA** (this is the *maximum*. You should never actually pull a full 40 mA from a pin. Basically, it's the threshold at which Atmel can no longer guarantee the chip won't be damaged. You should always ensure you're safely *below* this current limit.)
* The total current from all the IO pins together is **200 mA max**
* The 5V output pin is good for **~400 mA on USB, ~900 mA when using an external power adapter**
    + The 900 mA is for an adapter that provides ~7V. As the adapter voltage increases, the amount of heat the regulator has to deal with also increases, so the maximum current will drop as the voltage increases. This is called *thermal limiting*
* The 3.3V output is capable of supplying **150 mA**.
    + Note - Any power drawn from the 3.3V rail *has to go through the 5V rail*. Therefore, if you have a 100 mA device on the 3.3V output, you need to *also* count it against the 5V total current.

**Note: This does not apply to the Arduino Due, and there are likely some differences for the Arduino Mega. It is likely generally true for any Arduino based off the ATmega328 microcontroller.**
> 13 votes

---
Tags: pins, arduino-uno, current
---


# Question
Title: Why does my sketch report too many button presses?
I've been using a button to interact with a sketch (on my Uno), and it's mostly working fine. However, sometimes it seems to be detecting multiple presses when it's only pressed once.

It's a small circuit-mounted momentary button, which is normally open. It's connected from +5V directly to an input pin. I've also added a 10K pull-down resistor on the pin to make sure the input isn't left floating.

Here's a test sketch I've been using, which reports the number of presses to the serial monitor:

```
    int oldState = LOW;
    int numPresses = 0;

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

    void loop()
    {
        const int newState = digitalRead(5);

        if (newState != oldState) {
            if (newState == HIGH) Serial.println(++numPresses);
            oldState = newState;
        }
    }

```

Sometimes when I press the button once, the serial monitor shows two presses in a row. It sometimes even reports a press when I *release* the button.

Is it possible to fix this? Or do I just have a faulty button or pin or something?

# Answer
> 11 votes
# Contact Bounce

This is known as contact bounce and happens when the metal contacts in the button or switch bounce against each other when you push it. The microcontroller is fast enough to pick up these bounces and, as far as it's concerned, you're toggling the switch many times in as much as 10 milliseconds of time.

Different switches and buttons will have a different amount of contact bounce, and even one switch will behave differently between two presses.

Here's a button press captured on a scope (image from Maxim):

At 2ms/div we don't see a stable signal until 6ms after initial contact!

# Solutions

## Add a delay

The absolute simplest solution is to introduce a short delay after you read the button input. This will prevent the code from picking up any bounces and when it resumes, the signal should be stable.

```
if (digitalRead(A3) == 0) {
    // do something here
    delay(500);
}

```

In the example above, I delay 500ms after reading the state of the pin. The button is normally high so when I press it down, the state of the pin goes to logic 0. I pick that up in the code and do something and then wait at least 500ms before continuing.

Obviously, this code will just halt for half a second every time you push a button, which may or may not be acceptable in your application. You can decrease the amount of delay depending on the contact bounce time of your switch, too, but I play it safe here.

# Ignore button presses too close to each other

Similar to the solution above but instead of adding a hard delay, you use the `millis()` function to keep track of when the last time the switch was triggered. Every time you see a switch trigger, you compare against the time and, if not enough time has elapsed (say like 500ms in my previous example), you ignore it.

This solves the problem of having to use `delay()` in your code.

# Switch debouncer IC

There are things like the MAX6816 which is an IC that you put in between your switch and microcontroller input. It will denounce the signal for you. At a price of $1.62 @1k you'll probably never use this.

## Other

There are many solutions to this problem... I always do it in software, but some others include using a latch or capacitor.

Debounce Code – one post to rule them all

# Answer
> 4 votes
The button contacts themselves are probably bouncing in and out of contact, which is causing the circuit to open and close multiple times, even though the button position isn't changing.

It's a common problem with buttons and would be the first thing I would check. In order to fix this, you need to de-bounce the button. There are various ways in which to accomplish this, some of which can be done in the sketch itself.

A good solution is code that measures the duration of each button state and only registers a change in state if the current duration is greater than the desired duration. That option should be used for more complex projects. The code for it will be project specific and likely use sketch defined variables, but an example of what needs to be done can be found here.

If the sketch is very basic or you just want to make sure that bounce is the problem, you can add a short delay after the button state changes. For example:

```
void loop()
{
    const int newState = digitalRead(5);

    if (newState != oldState) {
        if (newState == HIGH) Serial.println(++numPresses);
        oldState = newState;
        delay(10) //Adjust the delay length to be as short as possible without triggering errors
    }
}

```

# Answer
> 3 votes
This is your button **bouncing** which is quite usual behavior; it has nothing to do with button quality.

There are 2 ways to "debounce" a button: by hardware or by software.

Personally, I prefer by hardware; just google for `button debouncing circuit` and you should find many examples.

If you don't have the necessary components available, you can use software debouncing.

By software, you have an example here on Arduino web site.

---
Tags: pins, button
---


title: How can a 5v Uno talk to a 3.3v Due?

text:
# Question
Title: How can a 5v Uno talk to a 3.3v Due?
I currently have an Uno (which operates at 5v), and I'm looking at buying a Due (which only operates at 3.3v). I'd like to make them communicate via Serial or SPI or similar, but presumably connecting them directly isn't an option (I guess the Due's pins would get damaged).

Is there any way to make the connection safe? Or is there an alternative form of communication I could safely use between them instead?

# Answer
> 8 votes
* For a 5V logic output to a 3V3 logic input, you can use a resistive divider to lower the voltage.
* When unloaded, a 3V3 logic output is just enough to drive a 5V logic input. Check the AVR datasheet for the exact voltages (0.6 × Vcc = 3V, found under DC Characteristics in the datasheet).

In other words, with a little bit of special care it may just work.

To construct a more reliable and bidirectional solution, use a level shifter. There are several listed on this page but other manufacturers make similar devices.

This document describes how a MOSFET can be used to bidirectionally convert logic levels between different supply voltages.

---
Tags: arduino-uno, serial, pins, arduino-due, voltage-level
---


# Question
Title: What will happen if I give my Arduino Uno more or less than 5 volts?
Will it still run on less than 5 volts? Will it break?

# Answer
> 6 votes
# Will it break at \< 5V? Not likely.

* Check the datasheet for the IC's on the board and find the minimum power supply voltage the device works at.
* At typical ATmega328 Safe Operating Area (under "Speed grades" in the datasheet) specifies approximately 4.1V for 16MHz.
* If you require to use the USB interface, you'll have to check the datasheet for that chip too.

# Will it run at \< 5V? Maybe.

* If the supply voltage gets below the minimum operational voltage, the controller may behave erratically. That means it can do anything (un)expected. This value is in the datasheet and probably somewhere around 2.7V.
* If the Brown Out circuit is configured (in fuses), then the controller will switch itself off when supply voltage gets too low to prevent undefined situations. Once the supply voltage returns, it restarts.

# Will it break at \> 5V? Depends on where you apply it.

* V(IN) should work fine for 7-20VDC as it is fed through an on board regulator. Notice though that the regulator has to dissipate the excess voltage and can get pretty hot when you draw a fair bit of current. The regulator will fail if the voltage goes over 20V or gets too hot too often;
* +5V should work fine up to 5V, and I personally wouldn't worry if an external supply delivers up to 5.5V unloaded. Above that 5.5V you will probably release the magic blue smoke.

---
Tags: arduino-uno, power, safety
---


# Question
Title: Last element of a struct disappearing on write/read
I'm building a weather station with two UNOs, using NRF24l01+ radios. Communications are fine. I'm sending a struct from one to the other. The struct has three elements:

```
    struct weather {
      float tempData;
      float humData;
      float pressData;
    };
    weather wData = {0, 0, 0};

```

I then populate the struct with values from my DHT22 Temperature Sensor and my BMP085 pressure sensor.

```
    float c = dht.readTemperature();
    wData.tempData = (c * 9/5) + 32;
    wData.humData = dht.readHumidity();

    sensors_event_t event;
    bmp.getEvent(&event);
    wData.pressData = (0.0295 * event.pressure);

```

Now I send it via the NRF24L01+.

```
    radio.write(&wData, sizeof(wData);

```

On the receiving Uno I have this.

```
    struct weather {
      float tempData;
      float humData;
      float pressData;
    };

    weather wData = {0, 0, 0};

    radio.read( &wData, sizeof(wData) );
    Serial.println(wData.tempData);
    Serial.println(wData.humData);
    Serial.println(wData.pressData);

```

I get results similar to this:

```
    Temp = 75.43
    Hum = 35.76
    Press = 0.00

```

The first two are correct. The final one is not. I can change the order and the first two will always be correct, but the last element is always 0.00. For example:

```
   Hum = 35.76
   Press = 30.14
   Temp = 0.00

```

I know I'm missing something here with my code but I can't find it. Anyone have some suggestions?

# Answer
> 2 votes
Modified my `struct` by changing the first two elements from `float` to `int`.

```
struct weather {
  int tempData;
  int humData;
  float pressData;
}
weather wData;

```

**Everything transmits fine now.** I don't really need the precision of a `float` for temperature and humidity. However, I would still like to find the problem. Could there be some problem with the size of three `floats` versus two `ints` and a `float`? `Serial.print(sizeof(wData))` is `12` when all elements are `floats` and `8` when using two `int` and a `float`. My understanding is the NRF24L01+ has a transmit and receive buffer of 32 bytes.

---
Tags: c++, struct
---


# Question
Title: How does this code line detect if a serial interface is connected?
I am working with some code for remote temperature sensor nodes. They turn the debug interface on and off depending on if anything is conneced to the serial port or not.

The code is on Github here. Line 111 is the line of interest:

```
if (Serial) debug = 1; else debug=0; //if serial UART to USB is connected show debug O/P.

```

So, a simple question: On a hardware and software level, how does this work? I can't see anything in HardwareSerial or Stream that would return true/false if anything was connected or not.

Note that I am not confident that it actually works. This simple test indicates it doesn't work as the LED flashes regardless of the presence of a serial adapter or connection:

```
boolean debug;

const int toggle = 6;

void setup()
{
  if (Serial) debug = 1; else debug = 0;

  pinMode(toggle, OUTPUT);
  digitalWrite(toggle, LOW);

  if (debug)
  {
    Serial.begin(9600);
    Serial.println("Setup");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
  }
}

void loop()
{
  if (debug)
  {
    Serial.println("Loop");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
    delay(1000);
  }
}

```

# Answer
You're right -- it doesn't work in most cases, and will almost always return true. The one board where it's actually functional is the Leonardo. According to the official documentation:

> On the Leonardo, **if (Serial)** indicates wether or not the USB CDC serial connection is open. For all other instances, including **if (Serial1)** on the Leonardo, this will always returns true.

Basic serial connections (used by most Arduinos) usually don't care if anything is actually listening. It's not uncommon for embedded devices to send debug info by serial even when nothing is receiving it. This has the advantage that the code's timing and behaviour won't change when debugging, which could cause all sorts of problems if you're trying to diagnose a problem reported in the field.
> 13 votes

# Answer
While it may not be possible to detect whether a device is connected to the Arduino serial connection or not, it is possible to *enable the debug messages over the serial connection* based on the presence of a device on the serial connection.

Considering that you will be using the debug interface of your sketch only when connected to a computer capable of serial communication, it is possible to incorporate a simple test into the sketch based on which debug mode is enabled or not.

When the sketch starts, you can check to see if any data is available on the Serial connection or not. If there is, then a device is present and debugging can be enabled. On the computer side, everytime you want to start the debugging mode on the Arduino, simply send a byte over the serial connection during the `setup` phase and sit back.

Here is a sample sketch showing the same:

```
int debug = 0;

void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);

  //Wait for four seconds or till data is available on serial,
  //whichever occurs first.
  while(Serial.available()==0 && millis()<4000);

  //On timeout or availability of data, we come here.
  if(Serial.available()>0)
  {
    //If data is available, we enter here.
    int test = Serial.read(); //We then clear the input buffer

    Serial.println("DEBUG"); //Give feedback indicating mode

    debug = 1; //Enable debug
  }
}

void loop()
{
  if(debug==1) Serial.println("ON");
  digitalWrite(13,HIGH);
  delay(1000);
  if(debug==0) Serial.println("OFF");
  //Turn off if serial is not available
  digitalWrite(13,LOW);
  delay(1000);
}

```
> 6 votes

---
Tags: serial, library
---


# Question
Title: Extracting data from Arduino MultiWii Flight Controller
I am new to the world of Arduinos but have a new project going with a MultiWii Flight controller. With the MultiWii comes a software for showing all data that is measured from the sensors (acceleration, velocity, roll, pitch, etc) which is nice but I would like to have/extract this data (call raw data or something) from all sensors (i.e. the data plotting everything, in numbers). Maybe it is the simplest thing to do, and I guess I have to set up some serial connection between the controller and tell it to send this data somehow but I do not know where to start so any guidance and help is appreciated.

# Answer
> 2 votes
Since you're new to Arduino, I'd suggest beginning with a basic interfacing arduino activity. Once you understand reading and writing digital and analog signals it's pretty much plain sailing from there. You may want to invest some time and a bit of cash in a beginners course on Udemy (try PEter Dalmaris' course https://www.udemy.com/arduino-sbs/) it's a good start. From there, talking to the MultiWii should be a piece of cake. Also, check out http://www.multiwii.com/connecting-elements

---
Tags: serial, sensors
---


# Question
Title: Can you fry an arduino with nothing plugged in to it?
I only get to work on my arduino every few weeks, so sometimes and get interrupted a lot by small children, so if I completely forget what is on the firmware, then I unplug the pins (because I haven't got anything soldered on there) should I be 100% certain I'm not going to fry my board?

# Answer
> 7 votes
Although the controllers on an Arduino are pretty well protected, they can still be damaged by ESD (Electro Static Discharge). The same effect that makes a crispy sound when you pull off your woolen sweater in the winter, or after walking with rubber shoes on a carpet and you touch someone else or a metal and grounded object and you feel a pick. Static electricity can damage the controller. It may get completely broken, or it may function 'most of the time' or lifetime may be shortened.

An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller. This is largely the same effect as above.

Again, the controllers themselves are pretty well protected, don't worry too much about them. But with kids running around (on their rubber shoes) better make sure they don't accidentally draw a spark from their little finger to your Arduino. The protective metallic bag is best, but putting it away in a cupboard or box should do the trick equally well.

As a general rule of thumb, the faster the electronics, the more sensitive it is for ESD. A Due is probably more sensitive than a UNO or a MEGA. But with normal, avoiding static electricity, use you should be OK.

# Answer
> 5 votes
Arduinos are far from bulletproof but with nothing connected (apart from a power source of course) I doubt it will come to harm. If in doubt, upload Blink to it.

There are rugged Arduino-compatibles. One of them has a rather obvious name

# Answer
> 3 votes
It's generally a good idea not to try to take input from a pin configured as `pinMode(OUTPUT)` and vice versa. In addition, I prefer not to take input from tristated pins. Both of these cases are harmless, but it's good practice not to do so, especially since they *can* cause issues when coupled with some hardware.

In general, Arduinos are protected from software issues. You can't burnout an Arduino with just faulty software.

There are, however, many ways to fry an Arduino via hardware.

# Answer
> 2 votes
**100% certain? No. 99.9999\[Repeating\]%? Yes**

Here's a couple problems you could run into:

* Using pins `0` and `1` when connected to USB (wouldn't damage it, the USB chip if on a board with a separate USB chip would probably ignore the "corrupted" data.)
* You never mentioned your board. If it's a Uno and you modified your USB firmware, there might be some issues reflashing your board if you forget that you flashed it with a keyboard firmware. **It won't damage it, but you may think it's bricked if you forget to reflash it.**
* If you only disconnect a couple pins and leave others in, it may give wierd results and fry the Arduino or whatever is partially attached
* If you make any physical modifications to the board

The second to last one is the one you really have to worry about. I have seen previous discussions about destroying a board with a sketch, but nothing has been suggested.

Lastly, there a chance you can damage it with setting the fuses on the chip(s) on the board.

---
Tags: safety
---


# Question
Title: How can I transmit data to/from arduino from up to ~750 ft away?
I am working on a design project for school (non-capstone non-electrical engineering project) where we are building a system to remotely control a winch on a boat that will lower an independently operating meter to specified depths using a pressure transducer (controlled from the shore).

My current idea is to have an arduino collecting data from the pressure transducer while being connected to the winch (adjusting it up/down as needed, based on the desired inputted depth). The arduino would then be connected to the a Raspberry Pi B via USB. The Raspberry Pi would then communicate via wifi USB adapter to a router @ 2.5 GHz 802.11n on the shore, which would then communicate with the laptop on the shore. The important thing is that the laptop on the shore will be recording data as well as changing the input depth for the arduino.

Arduino \<==\> Raspberry Pi \<==\> Router \<==\> Laptop on shore

I saw \[this information\]\[2\] talking about connecting to an arduino via wifi, but I was unable to determine the potential range.

A related project using a boat that uses the Xbee shield.

Once concern is that we will not be able to specifically point any antenna on the boat back to shore, so we are looking for a non-direction-oriented solution.

I was wondering what potential ways I could communicate back to the shore to control the winch depth (output display on shore showing depth, then being able to change the depth from shore). Furthermore, I was wondering if my setup would be feasible and what your suggestions might be.

Thanks!

# Answer
There are a number of considerations that need to be made when considering any wireless communication solution over long distances and over water.

WiFi is capable of working over long distances especially with higher power cards (1W ones are now readily available) and directional antenna (anything from 3dBi to 30dBi of gain). There are advantages and disadvantages to using WiFi like this for your purposes:

* WiFi uses 2.4GHz which is attenuated by the presence of water and water vapour. If you are close to the surface of the water surface, this can cause variable range with weather conditions increasing humidity and spray - even slight choppiness can massively increase the humidity close to the surface.
* WiFi is a fairly heavyweight protocol that has several layers that need setting up each time a connection is made. This takes time and means marginal connections will have zero throughput as they will never get setup.
* WiFi is intended to have high throughput (\>1MBps) and doesn't degrade gracefully below this point. There isn't often a need to shift data this fast on an Arduino project. Speed and range are a trade-off.
* Directional antenna on boats can be hard work. The more gain an antenna has, the more directional it is, which in turn means you need to aim it better. Even mild rocking can make this difficult to impossible. It depends if you are on a smooth pond or the sea really.

If you do want to go with WiFi, Ubiquiti make some neat products like the Nanostation that allow long range connections to be set-up over long ranges.

Personally I would stay away from 2.4GHz near water, and go with one of the other ISM bands. Depending on your location, this could mean 315MHz 433MHz, 868MHz, or 915MHz. It depends which region of the world you are in which ones you are allowed to use.

These lower frequencies are suited to longer ranges and penetrating object and water. There are a lot of different solutions in this space, all of which have ups and downs.

The Hope RFM12B is a very popular small RF board that has several easy to use libraries available - I use Jeelib personally. These are just capable of the 750ft range you require. They are available in all most ISM bands, and personally I have found the 868MHz best outdoors, whilst the 434MHz is better indoors.

The newer Hope RFM69W is a similar board but with more functionality and more power. It has 13dBm (20mW) of power vs 0dBm (1mW) of power on the RFM12B. I have been seeing an increase in range of ~50-100% with these boards.

The RFM69HW is a high power version has 20dBm (100mW) of power. I haven't range tested this, but would expect up to 3-4 times the range of an RFM12B.

Ciseco, a UK company, also make a series of boards that use CC1110 chips as transceivers. These are in an XBee like form. One of their boards, the ARF, has a power amplifier. These have 26dBm output power (400mW) and in a brief test in a built up area, I have seen a range of about 2km.

It's important to note that these are transceivers so that they can send and receive, which means you can acknowledge if packets have been received.

There are boards like the nRF2401L which use 2.4GHz, but use a much lighter weight protocol than WiFi so work better on marginal ranges. They are dirt cheap (~£2). They have the same disadvantage of water impacting range.

I don't like Xbee at all. The boards are overpriced and I find the range isn't great even with the higher powered modules.

You could also "roll your own" and use simple 434/868/915MHz on-off-keyed (OOK) transmitter/receivers. Protocol design isn't easy though, and you lose a lot of hidden functionality that the more advanced boards have.
> 8 votes

---
Tags: wifi
---


# Question
Title: How to switch an external circuit with Arduino?
I have an object with a series of led and I want to turn on and off these leds from my Arduino. The input of the LED circuit is 24v DC 100mA.

What I've done is the following:

* I've cut a wire of this object and I connected one end to the collector and the other end to the emitter of a NPN transistor
* I connected the base of the transistor to a digital output (through a 1k resistance)
* I connected the power to the led series while the digital pin was LOW (actually completely disconnected)

**But with no current on the base of the transistor, the LED has turned on to my surprise.** I may have completely misused the transistor and other items. How do I fix this circuit?

# Answer
If I understand your writeup correctly, this is what you have built:

simulate this circuit – Schematic created using CircuitLab

What you didn't mention in your question is that you made a connection from Arduino ground to the base of the transistor and the seconds circuit's ground connection. I drew the extra lead 'loose' for illustration only, but you see where it should connect. Current needs a return path, it is not sufficient to only have the forward path (from Arduino through R1 and base-Q1). The return path is emitter-Q1 to Arduino-GND.

Do notice though that the two batteries / power supplies must be floating with respect to each other otherwise you're going to short them out.
> 6 votes

---
Tags: power, transistor, voltage-level
---


# Question
Title: sprintf() to assemble String and float pieces locks up
I'm trying to parse many variables into a URL so that I can update a website through a simple HTTP API with sensor data. After talking to a buddy of mine, he suggested going with the code below.

When I put this in, the Arduino Yun boots up. I see the L13 red LED turn on, but then it hoses. When I comment out the `sprintf();` line, everything works fine — except no URL is parsed.

I've tried to debug to the best of my ability and am looking for thoughts on what may be happening.

I'm not sure how much code to post without posting the whole 130 line sketch, so I'm just dumping the parts from the `loop` that is trying to piece together the URL.

```
  // Get update time
  Process date;
  date.runShellCommand("date --utc \"+%Y-%m-%d%%20%H:%M:%S\"");
  String utcDateString = "";
  while (date.available()) {
    char d = date.read();
    utcDateString += d;
  }

      char url[512];
      url[0]='\0';
      float humid, baro, windspeed, raingauge;
      int winddir;
      Serial.print("humid: ");
      Serial.println(humid);
        Serial.print("baro: ");
      Serial.println(baro);
        Serial.print("windspeed: ");
      Serial.println(windspeed);
        Serial.print("raingauge: ");
      Serial.println(raingauge);
        Serial.print("winddir: ");
      Serial.println(winddir);
 //sprintf(url,"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=123456&PASSWORD=xxxxxx&dateutc=%s&temp=%2.2f&humidity=%2.2f&baromin=%f&winddir=%d&windspeedmph=%3.2f&rainin=%3.2f&softwaretype=Custom%%20Arduino&action=updateraw",
//         utcDateString,Thermistor(analogRead(0)),humid,baro,winddir,windspeed,raingauge);
        Serial.print("url: ");
      Serial.println(url);

double Thermistor(int RawADC) {
  double Temp;
  Temp = log(11100.0/((1024.0/RawADC-1)));  // Was 10000... Manually dialed down to increase accuracy. 9400 is a good value. Changing again to match wunderground
  Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
  Temp = Temp - 273.15;            // Convert Kelvin to Celcius
  Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
  return Temp;
}

```

Here's the output from those `Serial.print()` calls:

```
humid: 0.00
baro: 0.00
windspeed: 0.00
raingauge: 0.00
winddir: 0
url:

```

I'm not sure how else to debug this because when I uncomment `sprintf();` the Yun locks up and I have to press the `32U4 Reset` button and power cycle the Arduino to get it to work again.

# Answer
This variable:

```
String utcDateString = "";

```

Is a C++ String, not a character array like sprintf() is expecting. To convert this string to a character array such that sprintf is expecting, you must use .c\_str() in your sprintf, i.e.:

```
sprintf(foo,"This is a format for %s", utcDateString.c_str());

```

Doing this should prevent the sprintf line from causing a memory fault.
> 7 votes

# Answer
Looks like `%f` isn't wired up for performance reasons. You can convert floats to strings first using `dtostrf()`.
> 3 votes

---
Tags: sketch, c++
---


# Question
Title: Is it better to use c_str or toCharArray?
When reading/trying a recent answer, I was surprised to see that Arduino's `String` class supports the `c_str()` method, just like the C++ `std::string` class. As expected, it appears to get a pointer to the string's contents as a null-terminated `char` array (i.e. C-style string).

However, (as far as I can see) that method is not mentioned in the official Arduino documentation. Additionally, in all example code I've seen using `String`, a different approach seems to be used. A secondary `char` buffer is setup, and then the contents of the string are copied to it using `String::toCharArray()`. This obviously requires double the memory, plus an O(n) copy operation.

It seems like `c_str()` should be the preferred approach. Is there some reason why `toCharArray()` is more commonly used?

# Answer
> 3 votes
> It seems like `c_str()` should be the preferred approach. Is there some reason why `toCharArray()` is more commonly used?

basically, I'd say it's a lack of knowledge from the people doing the codes you've seen. Definitely `c_str()` is better. Though, what I see even more often is the use of character arrays `char*` strings instead of `String` (and I plead guilty of that as well in my own codes).

And that's because the Arduino library has been built upon a messy set of C and C++ libraries and coding style. Trying to make things easier actually messed them up and complicated them more.

That's actually why we have new projects like xpcc trying to make a real and smart use of the C++ abilities in the embedded world.

---
Tags: programming, c++, string
---


# Question
Title: How to debug an Arduino sketch on a Mac?
I have 2 Lowpowerlab WaterMote's talking to each other using the 'out of the box' pre-installed sketch that just confirm they're talking to each other. I verified this by opening a COM connection and saw traffic of 'receiving packets...' That was just to show that they are functioning and talking to each other.

Now, using Arduino IDE on Mac OS X 1.9.x (Lion?) I have loaded the WaterMote sketch (found on Github) on the Moteino with the sensor (not the gateway) as it should be. The traffic looks like it's working, except the text being transmitted (number of Gallons) stays the same at 0.02 Gallons.

So... I want to debug the WaterMote sketch, *but* I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

My current setup

* Moteino Gateway (as out of the box) connected to a Raspberry Pi (with ssh enabled)
    + Connected via USB to the RasPi
* Moteino with WaterMote sketch loaded
    + Connected via USB to the MacBook Pro
    + Arduino IDE running, but I see strange "\[\]\[\]\[\]" square output in the Serial connection.
    + I do not know what to make of this since that text is not in the WaterMote sketch.

Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

I found a debugging article:

# Answer
> So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

It's definitely possible to debug a sketch with OS X. But it's definitely an advanced AVR topic, and if you're not experienced enough with embedded programming you should first try to avoid it, except if it is really necessary.

Debugging a sketch for an ATmega328 implies:

* Running a flasher such as the AVR Dragon, the JTAG ICE 3, the STK500 or the AVR ONE; no cheap flasher implements the `DebugWire` protocol;
* Setting up the debug fuse, which is an operation that can brick your MCU.

If you're using an ATmega32U4 (or alike), you won't be able to do it out of the box, as the 32U4 needs a JTAG connection for on-chip debugging.

Finally, once you got through that, you can bind a `gdb` to the AVR using AVaRICE. I'm not getting you through all that, because I really, really, strongly advise you not to do it until you're experienced enough to know what you're doing.

> Moteino with WaterMote sketch loaded connected via USB to the MacBook Pro Arduino IDE running, but I see strange "\[\]\[\]\[\]" square output in the Serial connection. I do not know what to make of this since that text is not in the WaterMote sketch. Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

It is very likely you did not setup the correct baudrate for the serial outputs. Arduino IDE defaults to 9600 bits/s connections, whereas the WaterMote source code defines a 115,200 bits/s connection. When you open the `Serial Monitor` change the setting at the right of the status bar.

And finally, be sure to uncomment the `#define SERIAL_EN` line to enable the serial communication and debug outputs.
> 5 votes

---
Tags: ide
---


# Question
Title: Why are the files not being created correctly?
I have been through http://arduino.cc/en/Hacking/LibraryTutorial but I can't do it. Whenever I create a new sketch and try to save it as `.cpp` or `.h` from the `Save As` button in the Arduino IDE, it gets saved as `_cpp` and `_h`. I am not able to create a library this way. How do I create a new library? What am I missing here?

# Answer
> 1 votes
When you save a file using the `Save As` button from the Arduino IDE, it saves the current file as a sketch i.e. as an `.ino` file.

To create a `.cpp` and `.h` files for working on a new library, you need to create the files alongside a sketch. For this, you can use the `Tab` button on the top right (circled in red).

>

Click on it, and select `New Tab`. You will get a bar at the bottom of the screen asking for a file name. Enter the name with extension (`test.cpp`) and press `Enter`.

>

Your file has now been added to the current directory.

>

Similarly, follow the same steps for creating the `.h` file.

Once your library is complete and ready to ship, you can move the `.cpp` and `.h` files to a separate directory and then add it under libraries.

---
Tags: library
---


# Question
Title: What is the difference between declaring a variable outside of loop and declaring static inside loop?
These are two ways I can hold a variable outside of loop (or any function).

First, I can declare it with global scope outside of loop:

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

int count = 0;

void loop()
{
    Serial.println(count);
    count++;

    delay(250);
}

```

I can also declare it static inside the loop:

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

void loop()
{
    static int count = 0;

    Serial.println(count);
    count++;

    delay(250);
}

```

What difference, if any, will this make?

# Answer
> 10 votes
The most basic difference is of scope.

In the first case, you are declaring a global variable. It is a variable that is accessible in every scope after its definition.

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

void inc();
int count = 0;

void loop()
{
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

void inc() //Can edit the value of count
{
  count=count+1;
};

```

In the second case, you are declaring a static variable with local scope. The variable will persist for the entire program run similar to global variables, but will be accessible only in the code block it is declared in. This is the same example, with only one change. `count` is now declared as a static variable inside `loop`.

```
void inc();

void loop()
{
    static int count = 0;
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

```

This will not compile as the function `inc()` does not have access to `count`.

Global variables, however seemingly useful, come with some pitfalls. These can even cause damage when it comes to writing programs that can interact with the physical surroundings. This a very basic example of something that is quite likely to happen, as soon as programs start getting larger. A function may inadvertently change the state of a global variable.

```
void setup()
{
    Serial.begin(9600);
}
void another_function();
int state=0;

void loop()
{
    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Inadvertently changes state
  state=1;

}

```

Such cases are very hard to debug. *This* type of problem however, can easily be detected, by simply using a static variable.

```
void setup()
{
    Serial.begin(9600);
}
void another_function();

void loop()
{
    static int state=0;

    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Results in a compile time error. Saves time.
  state=1;

}

```

# Answer
> 5 votes
From a functional perspective, both versions generate the same result, since in both cases the value of `count` is stored between the executions of the `loop()` (either because it is a global variable or because it is marked as `static` and therefore keeps its value).

So the decision which to choose come down to following arguments:

1. Generally, in computer science, it is encouraged to keep your variables as local as possible in terms of **scope**. This usually results in much clearer code with less side-effects and reduces chances of someone else using that global variable screwing up your logic. E.g. in your first example, other logic areas might change the `count` value, whereas in the second, only that particular function `loop()` can do so.
2. Global and static variables always occupy **memory**, where as locals only do when they are in scope. In your above examples that makes no difference (since in one you use a global, in the other a static variable), but in bigger and more complex programs it might and you could save memory using non-static locals. *However*: If you have a variable in a logic area that is executed very often, consider making it either static or global, since otherwise you loose a tiny bit of performance each time that logic area is entered, since it takes a bit of time to allocate the memory for that new variable instance. You need to find a balance between memory load and performance.
3. Other points such as better layout for **static analysis** or **optimization** by the compiler might also come into play.
4. In some special scenarios, there might be issues with the unpredictable initialization order of static elements (not sure about that point, compare this link though).

Source: Similar thread on arduino.cc

# Answer
> 2 votes
Both variables are static - they persist for the entire execution session. The global is visible to any function if it declares - not defines - the global, or if the function follows the definition in the same compilation unit (file + includes).

Moving the definition of `count` to inside of a function both limits its scope of visibility to the nearest enclosing set of `{}`es, and gives it function invocation lifetime (it is created and destroyed as the function is entered and exited). Declaring it `static` as well gives it execution session lifetime it exists from the start to the end of the execution session, persisting across function invocations.

BTW: be cautious about using initialized statics within a function, as I have seen some versions of the gnu compiler get this wrong. An automatic variable with an initializer should be created and initialized on every function entry. A static with an initializer should only be initialized once, during the execution setup, before main() is given control (just as a global would be). I have had local statics get reinitialized on each function entry as though they were automatics, which is incorrect. Test your own compiler to be sure.

---
Tags: programming
---


# Question
Title: Are there any commonly available and supported backlit, monochrome graphic LCDs with more than 128x64 pixels?
I am currently using a ST7565 graphic LCD for display in a heat pump system.

This LCD has the following characteristics:

* 128x64 pixels
* 2.5"x1.5"
* monochrome, no greyscale
* backlit
* good viewing angles
* serially connected (i.e. only uses a small number of pins)
* high enough refresh rate to show animated icons
* low cost (£20)
* has a high-quality, maintained library
* available from multiple sources for several years

I am finding the resolution of the screen limiting for my application. Ideally I would like a display that is exactly the same but with a higher resolution. Something between

I do not want:

* colour (largely as the display is less visible, but also increased cost and code complexity), but red/green/blue on black would be OK.
* a physically smaller display (all of the OLED displays are small - 2" and below) as it needs to be visible from a distance

Are there any displays that meet these requirements?

I hope that the specific requirements here mean that this is not a simple "shopping question".

# Answer
Here you can find a bunch of displays at new haven display, which are big and OLED and not too expensive:

Those OLED Displays have a really excellent viewing angle and can be read from far (given you accept those sizes, which are \>2").

Otherwise, the biggest I know about are LCD ones from NHD over there:

What's good with them, it's that they can cope with production in case this is needed, their prices are decent and their product just work(cTMr). You can find the u8g library to run them.
> 2 votes

---
Tags: display
---


title: Arduino + IMU vs ArduIMU

text:
# Question
Title: Arduino + IMU vs ArduIMU
I am working on a UAV and we are currently exploring inertial measurement units or IMUs. The two options that we have come across are:

* Using an Arduino Uno and a 9 DOF IMU like this one
* Using an ArduIMU chip like this one

Ignoring the cost aspect and assuming the same microprocessor on board, what would be the pros and cons of either of these approaches?

Keep in mind that performance is very important for a UAV controller as ESCs require 60 Hz or higher refresh rates for stable flight.

# Answer
> 2 votes
**Weight:** marginal as the difference between one board (with everything on it) and two boards (Uno plus DOF) may be - for model airplanes every bit counts.

**Size:** the traditional "Uno" is much larger than the ArduIMU integrated boards.

**Power:** the integrated board PROBABLY will use less and thus get away with a smaller (lighter) battery.

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


# Question
Title: Internet connectivity for the Arduino Due using AtmelStudio?
What hardware and software solutions work and what are the tradeoffs for connecting an Arduino Due to the internet? I gather the ethernet hardware is much cheaper than WiFi hardware (€29 versus €69). In either case (wired or wireless), what software stacks and drivers work under AtmelStudio?

# Answer
> 2 votes
Well, your best bet is to import the arduino libraries in your Atmel Studio project. Then you'll be able to use existing code to connect to the "traditional" Ethernet Shield using SPI.

Though, the Sam 3X features an hardware ethernet that is not wired, unlike the MBed LPC1768… Sadly that's the ethernet PHY component you saw, but won't be able to actually use…

---
Tags: ethernet, arduino-due, atmel-studio, wifi, tcpip
---


# Question
Title: How can I sense when someone is sleeping with my Arduino?
## Ignore the stalker-like title.

I am thinking about creating a project with Arduino that can sense you sleep habits, when you're asleep, and how much you sleep. It would be convenient to not have to turn it on/off at night; it should know how to do this.

Some ideas that I have:

* Motion sensor
* Breathing patterns (if an Arduino microphone could even pick that out... I would be surprised if it could)
* A RTC clock could assist in deciding *It's midnight. Usual, Steve isn't asleep at this time on Fridays. He's probably not sleeping now.* It won't always be there to help you, but you might be able to try to get more accurate results this way

**How can I accomplish this?** (Extra points for some sort of algorithm that can tell dozing off from a deep sleep.)

# Answer
I actually did something like this, using a PIR Motion sensor.

The motion sensor is good enough to detect a person turning in their sleep, and my simple algorithm just counts movements per minute and when its over a threshold (found by trial and error), it sounds the alarm to wake you up.

The image above represents my body movements during a night. The spikes represent a high movements/minute.

> Here we see after about 30 minutes body motion was minimal. This suggests I was in a deeper stage of sleep during that time.
>
> The spike at 250 minutes (around 4:30AM) is when I woke up only to realize I could sleep for couple of hours longer. I recall the time being 4:38 when I looked at my clock and I was already facing it. This means I turned around to face the clock but actually "woke up" 8 minutes later to see the time, and then turned back around (indicated by the shorter spike at 265).
>
> The data suggests I was not able to sleep very well (compared to the time period between 30 and 240 minutes) after waking up once and finally got up at 400 minutes (7:00AM), when I shut everything down.

Here are a couple of posts from my blog that have a lot more information.
> 13 votes

---
Tags: sensors, arduino-uno-smd
---


title: Build Infrared Camera Remote

text:
# Question
Title: Build Infrared Camera Remote
I wish to build a remote for my Camera i.e Sony NEX 5R. It has a built in IR receiver and has several Sony as well as aftermarket remotes provided for it. Due to my interest in Micro controller design I wish to build one myself rather than use an aftermarket one.

A friend who did the same for his NEX 5 series camera posted a video of the same on Facebook, which inspired me to build my own. I plan to use an Arduino Uno R3 with the following additional components:

* IR LED
* NPN Transistor(for amplification)
* Schmidt Triggers(for rectification)
* 9 Volt Battery

Ultimately I would like to swap out the Arduino for a standalone ATmega328 or ATtiny2313 but currently I have some issues as of now:

1. I currently do not have a schematic or a sample code which I can use. I have been trying to search the internet for the same but to no avail.
2. I am unsure of the protocol used by my camera. I have found it difficult to find documentation on the same.
3. How can I replace the 9-Volt battery for something smaller?
4. I would like to use a smaller micro controller but what differences will I encounter when trying to change my code for the smaller micro controller?
5. For such a project, will I need additional hardware?

# Answer
> 5 votes
1. Using the Arduino shouldn't be any different than any other microcontroller.
2. The IRremote library is my go-to library for any IR related stuff.
3. Power shouldn't be an issue, look at the Moteino from LowPowerLab and check out his coin cell battery tests. It's definitely possible. Not with a full blown Uno, but with a bare chip, yes.
4. You want to burn the bootloader on the IC first, before you can start writing Arduino code. Check out this tutorial: From Arduino to a Microcontroller on a Breadboard. It's the same process for an ATTiny, you just have to look at the datasheet to see where to plug things into. Specifically, MOSI, MISO, SCK, and Reset pins. The Tiny AVR Programmer is also a good choice. It's meant for the 8 pin micros but it has an ISP header so you can use it for almost any chip.

This may be useful for more information about decoding IR signals:

# Answer
> 1 votes
1.) I'm not exactly sure what you mean by this. What I'd recommend is a ATMega328 for the heart of the chip. It's what is in the Uno, so with a exception of uploading code, for this project this will cut down on the size of your project. However, an Uno will work pretty much identical. If you do want to use a chip like this, this design looks pretty complete. You'll probably want to move to a PCB for your final product, but since you have a little electronic experience, I assume you can solder and know about this. Here is another tutorial for barebones.

2.) Again, what do you mean by "standard?" Like protocol? If so, there's no real protocol to use. This may be easy for a begginer. It's the remote and the receiver. If you want to go all geek you can also hack an existing TV remote to do the same task. That library should take care of everything you need (see code later).

---

**A bit of code/wiring:**

The circuit will depend on what receiver you choose. Most IR receivers have one pin for 5v, one for GND, and the last one is connected to a digital pin. Again, look at the information on the specific receiver you choose.

Some sample code with the library I listed:

```
#include <IRremote.h>

int RECV_PIN = 11;        //Using pin 11 for the signal pin
IRrecv irrecv(RECV_PIN);  //Creates a variable that will be used later to inference between library and code
decode_results results;   //Use it to store the value of the keycode

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
}

```

You'll have to run this sketch to determine the value of the button you'll use on the remote. It should print on the serial window some sort of hexadecimal value IIRC that you'll have to convert into decimal if you want to use it inside the code to compare that to the button you want to use on the remote. The post I mentioned is a great resource: go and look at it.

---

3.) I don't recommend building a remote. Like I said, you can use existing TV remotes or buy one for this purpose. Start small, figure out how IR remotes work, and then build one later if you desire. A v2 is often required on Arduino.

4.) Don't bother for the receiver. It *can* be bigger. If you don't know how to to program it, this guide is a good reference. It has some files that you download to add it in the IDE to trick the IDE to think the chip is a board. Note: You'll have to program it with an Uno or similar to upload and to burn the firmware. (I would explain it more in case the site goes down, but you need the files there so it'll be pointless anyway.)

Also a quick tip: don't be afraid to ask your friend for some help. You don't need to rely on him, but if you get stuck ask him.

I don't know how to connect the Arduino to the camera, but you seem to know how to do that.

# Answer
> 1 votes
Well, for your project you can simply buy/rebuild a TV-B-Gone made by Mitch, which he uses as a basic project to teach soldering all over the world.

You can "hack" the TV-B-Gone by adding a TSOP4838 that can work as an IR receiver (or use another device as a code recorder).

And as you can see here the TV B Gone features an ATTiny85. A really small and nice beast.

Here you'll find the source code for the TV B Gone. I'm not sure what format they use for their code database though.

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


# Question
Title: What are the FLASH_ARRAY/FLASH_TABLE macros in this code?
In this code for heating monitor, there appears to be macros called `FLASH_ARRAY` and `FLASH_TABLE`. I can't find any reference to them either in this code, Arduino, or on the Internet. What do they do?

```
FLASH_ARRAY(byte, VARIABLE_DEVICE_TABLE,
    DEVICE_LADDNING_RETUR,
    DEVICE_LADDNING_UT,
    DEVICE_TANK1,
    DEVICE_TANK2,
    ...
    VARIABLE_ID_LOAD,
    VARIABLE_ID_TIME_EMPTY);

```

and

```
FLASH_TABLE(byte, NUMBER_TEMP_TABLE, 7,
  {DEVICE_LADDNING_RETUR, 99,  5, 10,  7, MAIN_TYPE_TEXT_CELCIUS, 2},
  {DEVICE_LADDNING_UT,    99, 43, 10,  7, MAIN_TYPE_TEXT_CELCIUS, 2},
  ...
  {DEVICE_UTE,             0, 55, 15,  7, MAIN_TYPE_TEXT_CELCIUS_WITH_NEGATIVE, 103},
  {VARIABLE_ID_EFFECT,   114, 29, 10,  7, MAIN_TYPE_TEXT_VARIABLE, 2});

```

# Answer
> 5 votes
After further digging, this appears to be from Mikal Hart's Flash library.

The reason this library was developed is:

> Storing static program data in flash/PROGMEM is a tricky part of Arduino programming. To save precious RAM, a novice user already at odds with unfamiliar C++ syntax must digest such daunting concepts as prog\_char, PSTR(), PROGMEM, pgm\_read\_word(), etc. Even seasoned users get tripped up by the indirection and typecasting that are required to retrieve valid PROGMEM data. Add to that a couple of apparent bugs in the implementation, and it’s clear that PROGMEM is a complicated mess.
>
> I have written a new library, Flash, which abstracts away most of this complexity. It provides new String, Array, Table, and String Array types that make ROM-based data collections as easy to use as “normal” types. Each overrides the C++ \[\] operator, so to extract individual elements one uses familiar array access syntax:

Specifically, these are macros and a simple helper class to make it easier to create arrays and tables of values in program memory.

The two macros are declared as so:

```
// Example: FLASH_ARRAY(float, temperatures, 98.1, 98.5, 99.1, 102.1);
#define FLASH_ARRAY(type, name, values...) \
  static const type name##_flash[] PROGMEM = { values }; \
  _FLASH_ARRAY<type> name(name##_flash, sizeof(name##_flash) / sizeof(type));

// Example: FLASH_TABLE(uint8_t, fonts, 7, {ON, OFF, ON, ON, OFF, ON, OFF}, {OFF, ON, OFF, ON, OFF, ON, OFF});
#define FLASH_TABLE(type, name, cols, values...) \
  static const type name##_flash[][cols] PROGMEM = { values }; \
  _FLASH_TABLE<type> name((const PROGMEM type *)name##_flash, sizeof(name##_flash) / sizeof(name##_flash[0]), cols);

```

The helper functions include size and override the operator \[\] so that they can easily be accessed like so

```
FLASH_ARRAY[0]

```

I disagree with zmo - this is more than boilerplate. The area of PROGMEM causes a lot of questions from Arduino users, and it is very easy to do things wrong when creating arrays in PROGMEM.

# Answer
> 4 votes
The flash array is from Mikal Hart's flash library as you show, and what it does is that they declare an array or a matrix (table) object in the PROGMEM memory:

```
#define FLASH_ARRAY(type, name, values...) \
static const type name##_flash[] PROGMEM = { values }; \
_FLASH_ARRAY<type> name(name##_flash, sizeof(name##_flash) / sizeof(type));

```

which is an instance of the `_FLASH_ARRAY` class defined in that same file, which is a facility to access PROGMEM/Flash memory.

Basically, it's a lot of boilerplate for what already does the `PSTR()` macro amongst other from `pgmspace.h`. I personally would avoid using that and prefer to use the original macros along with my own index and pointers.

BTW, except for some Arduono IDE magic, I don't think that can compile, as the `Flash.h` is not included.

EDIT:

To make another point against the `FLASH_TABLE`/`FLASH_ARRAY` boilerplate/overhead, since avc-gcc 4.8 has been introduced the `__flash` qualifier which is a replacement for the `PROGMEM` macro, simplifying the whole stuff:

```
// to use string literals without having to cast
#define FSTR(X) ((const __flash char[]) { X })

// create string pstr in the .progmem.data address space
const __flash char* pstr = FSTR ("foo");

```

and no more use of the `pgm_read_*()` functions, you can now access the content of the flash memory using `*pstr`, as shown is this thread. In case you want to keep a code compatible with older version of avr-gcc, here's a post that offers macros to deal with both systems.

---
Tags: library, flash
---


# Question
Title: How can I sense very high temperatures with Arduino?
I've seen many temperature sensors, but the highest temperature they go up to is 125 degrees C (257 degrees F). I want to reach *higher* temperatures than that. I'm thinking about rigging up a closed loop sensor for my soldering iron (for a convenient LCD display), but I can't find out how to sense the temperature of the tip due to the higher operating temperature than most sensors.

# Answer
> 7 votes
You probably want to use a thermocouple. It'll give you the ability to measure much higher temps than regular temperature sensor. You'll also need a IC like the MAX6675 to interface with it.

> The MAX6675 performs cold-junction compensation and digitizes the signal from a type-K thermocouple. The data is output in a 12-bit resolution, SPI™-compatible, read-only format.
>
> This converter resolves temperatures to 0.25°C, allows readings as high as +1024°C, and exhibits thermocouple accuracy of 8 LSBs for temperatures ranging from 0°C to +700°C.

Page 6 of the datasheet has the serial interface protocol information and. You can really just set the Chip Select line and it'll give you 16 bits of information, 12 of which will be the temperature.

# Answer
> 6 votes
One of the options to measure high temperatures would be to use thermocouples. This table provides a basic description of the types and the corresponding temperatures that they can sense.

A simple search led me to these components.

> This is how the board is connected to the thermocouple.

There is also a tutorial on Adafruit that deals with using and interfacing thermocouples.

> This is an image of the thermocouple interfaced with the Arduino.

---
Tags: sensors, temperature-sensor
---


# Question
Title: Redirecting Arduino Serial Output to a File
I am integrating the MPU-6050 Accelerometer + Gyro sensor into a large project that contains 12 Arduino boards and 6 Raspberry Pis. At some point, I will have to load the output of my MPU-6050 sensor into another application through command line. The process is to be all done with Python and Bash (on the Raspberry Pi side), and so what I need is a way to store the output of my Arduino boards.

What I am currently looking at is the python program `ino`. I have used the product for about a year now, and as far as I am aware of, the only way to exit out of serial mode in `ino` is by closing the command-line window!

Is there a way I can achieve what I've discussed above? Essentially, all I want is a way to hold the output of my Arduino serial output so I can use it later in other parts of my project.

# Answer
Well, I don't know about your `ino` program, but here's how I'd do it:

get\_serial.py

```
import serial, sys

with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
    while ser.isOpen():
        print(ser.readline())

```

The idea, here, is to print on `stdout` the data coming on the serial line:

```
python get_serial.py /dev/ttyACM0 115200 > output.log

```

or you can do it this way:

get\_serial.py

```
import serial, sys

with open(sys.argv[3]) as f:
    with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
        while ser.isOpen():
            f.write(ser.readline())

```

which is ran:

```
python get_serial.py /dev/ttyACM0 115200 output.log

```

Hope this helps!
> 3 votes

---
Tags: arduino-uno
---


title: A digital I/O pin as ground

text:
# Question
Title: A digital I/O pin as ground
I want an I/O pin to return current in a circuit, similarly to the function of ground.

Which of these will achieve what I require?

```
pinMode(pinnumber, OUTPUT)
digitalWrite(pinnumber, LOW)

```

or

```
pinMode(pinnumber, input)

```

# Answer
> 9 votes
Your first snippet is the correct solution.

```
pinMode(pinnumber,OUTPUT)
digitalWrite(pinnumber,LOW)

```

Be careful though, you can only sink up to 6mA or 9mA per pin (as per the documentation \["Input and Output" section\], I never tried more). If you need more current, use a transistor (this looks like a good example, you just need to invert the output pin to `HIGH`).

When the pin is configured as input it is supposed to be high impedance, not what you want.

---
Tags: pins, arduino-due, current
---