text:
Button state changing randomly
I have a push button wired to my Arduino but it seems to be triggering randomly.
I have one pin of the button connected to pin 2 on the arduino and the other connected to ground.
void setup() {
    Serial.begin(9600);

    pinMode(2, INPUT);
}

void loop() {
    Serial.println(digitalRead(2));
}

I expect it to print 1 continuously and go to 0 when I press the button down but sometimes it shows 0 even when I don't touch it.

When a button is connected in that configuration, the input is what's called floating, meaning it's not a 0 or a 1. When the button is pressed, it is connected to ground, so that's definitely a 0, but when it's not pressed down, we don't know the value of the pin.
Pull Up Resistor
We need to include what's called a "pull-up" resistor to pull the signal up to a logic 1 when the button is not pressed.

Image from Sparkfun
What this means is when the button is not pressed, the Arduino reads a logic 1. When the button is pressed, the current flows through the resistor to ground and the Arduino reads a logic 0.
Internal Pull Up Resistor
The Arduino also has internal pull up resistors so you don't necessarily have to add an extra component to your circuit. There are a couple of ways to use this.
You used to have to do it like this:
pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors

Now we can do it simply in one line:
pinMode(pin, INPUT_PULLUP);

This enables the 20k pull up resistor on that pin. The input will no longer be floating when the button is not pressed.
Note: This only works when the other end is connected to ground.

It's worth noting that the same idea works for pull-down resistors too; i.e. the resistor normally pulls the pin low, but pressing the button brings it high. Obviously it has to be external though, as there's no internal pull-down on standard Arduinos.

I dunno if you evencheck arduino stack exchange now but I am unable to understand the pin diagram. I have push button, with one end having 5V, and the other end having my wire connected to arduino and a 20k Ohm resistor which is connected to ground. Still I am getting random value when the button is not pressed. When it is pressed, I always get 1

There are several possible reasons random values are seen at micro controller inputs when connected to switches. Here are two:

Missing pull up or pull down resistor when using a SPST switch.

Micro controller inputs should not be allowed to float. This can lead to unexpected input states. Instead, inputs should be connected to ground or the micro controller's positive voltage supply usually either directly or though a resistor. It is common to use a pull up resistor when using a SPST switch connected to ground. Or a pull down resistor when using a SPST switch connected to the micro controller's positive voltage supply. Not all micro controllers have pull up or pull down resistors built internally. Some only have one or the other. In these cases an external resistor may be required. Some thought should be given to using micro controllers that do have built in pull up or pull down resistors. The actual resistance value of these built in resistors does vary (may not be carefully controlled). This is fine for the majority of cases. However, if a specific value is needed, it may be best if external resistors were used instead.

Long wires between the micro controller and the switch.

Longer wires are more likely to develop unexpected currents due external electrical noise. It is possible wires are long enough and the environment they are in electrically noisy enough to develop currents that will change the voltage across a pull up or pull down resistor. And, in turn, change the value of the micro controller's input. The higher the resistor value the more likely this will happen. However, the lower the resistor value chosen the more power needed when the SPST switch is closed. This is usually a concern when operating on batteries. There are many aspects to mitigating the effects of electrical noise. And will take us off subject. Instead, if long wires are necessary, consider using a "brake-before-make" SPDT switch which will connect the micro controller's input pin directly to ground or the micro controller's positive supply voltage. This will require running 3 rather than 2 wires to the switch.
Last words: Take care not to connect pull up resistors or switches to voltages higher than the micro controller's positive supply voltage! Some Arduino boards regulate higher voltages to lower voltage before supplying power to the micro controller. For instance, an Arduino board that runs from the 5 Volt USB power source may have a micro controller which actually runs at 3.3 Volt. In such a case, use the 3.3 Volts supplied to the micro controller when connecting a pull up resistor or switch.

Added this answer as the existing answer does not cover long-wires/electrical-noise inducing unexpected results and the use of SPDT switches instead of a SPST switch with a pull up resistor.


text:
What happens when I call exit() from my program?
In either of setup or loop, if I were to add an exit(0) call, where would control be passed to? What would the next state of the microcontroller be? Would it stop execution and power down?
I am using a revision 2 Arduino Uno.

My initial guess is wrong. I would have thought it would simply return from loop and the core library would just call loop() again. However, I see the following code was created. Noticing that __stop_program is a hard loop...
An extract of Blink.ino's listing, with exit(0) added:
// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
  exit(0);
}

The disassembly of the above:
// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
 100:   80 91 00 01     lds r24, 0x0100
 104:   61 e0           ldi r22, 0x01   ; 1
 106:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 10a:   68 ee           ldi r22, 0xE8   ; 232
 10c:   73 e0           ldi r23, 0x03   ; 3
 10e:   80 e0           ldi r24, 0x00   ; 0
 110:   90 e0           ldi r25, 0x00   ; 0
 112:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
 116:   80 91 00 01     lds r24, 0x0100
 11a:   60 e0           ldi r22, 0x00   ; 0
 11c:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 120:   68 ee           ldi r22, 0xE8   ; 232
 122:   73 e0           ldi r23, 0x03   ; 3
 124:   80 e0           ldi r24, 0x00   ; 0
 126:   90 e0           ldi r25, 0x00   ; 0
 128:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  exit(0);
 12c:   80 e0           ldi r24, 0x00   ; 0
 12e:   90 e0           ldi r25, 0x00   ; 0
 130:   0e 94 1e 02     call    0x43c   ; 0x43c <_exit>

...

0000043c <_exit>:
 43c:   f8 94           cli

0000043e <__stop_program>:
 43e:   ff cf           rjmp    .-2         ; 0x43e <__stop_program>

Note that if _exit had not called cli, interrupts would be able to do stuff. But that is not the case.

avr-objdump -S {compiled *.elf file} produces a file that includes the C code that lead to each section of assembly code. It's much easier to follow.

aaaand I just tried it, and it's not correctly emitting inline C code for the loop function. What the hell?

Whoa, extremely strange. I compiled the project with Stino instead of the arduino editor, decompiled the *.elf from that, and then I get the proper debugging symbols. I think the Arduino text-editor/button-macro (I refuse to call it an IDE since it's not) thing is stripping the debug info from just the compiled main C++ file, for some bizarre and stupid reason.

There is an explanation, and it is to do with the way the IDE copies your files to a temporary location. You can "fix" that by telling avr-objdump where the source is: avr-objdump -S -I/path/to/the/sketch/folder  xxx.elf  . That is the sketch folder path, not the .ino file itself. Then you should get the C source in the dump.

Well I just tested it with my Arduino Uno and it just completely stopped the code and left all the outputs as they were when the code stopped running (so it left an LED I had on on). There seems to not be a IO cleanup when you call exit. This was what I expected because the Arduino IDE provides the setup and loop functions, if you program the ATMEGA*28 with with any other AVR IDE you start with the main function like all C/C++ programs. The setup and loop functions are not standard on AVR MCU's.
Note: The press of the reset button restarts the code, if you were wondering.

Good to know. I was looking for something more detailed and at a lower level. On calling exit(0) the disassembled instructions are (IIRC) __stop_program, cli and a spinlock. I wanted to verify if that is correct with an explanation of how the control is passed i.e. call stack pop?, ISR call?

Ah, well I haven't looked into arduino on such a low level, for that information you might want to check the atmel website.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
What happens if there is a runtime error?
What happens if there is a runtime error in a program? Will execution of the program just stop? Is there some way I can get the Arduino to tell me what the error is?

First, let's see a few examples of what can go wrong.
Uninitialized local variables
void setup() {
  int status;
  pinMode(13, OUTPUT);
  digitalWrite(13, status);
}

As pointed out by Edgar Bonet in the comments, local variables like status in the code above are not implicitly initialized by the C++ compiler. So, the outcome of the code above is indeterminate. To avoid that, make sure you always assign values to your local variables.
Things are a bit different with global and static variables:

Global and static variables are guaranteed to be initialized to 0 by the C standard.

Source:
AVR Libc Reference Manual - Frequently Asked Questions - Shouldn't I initialize all my variables?
That means you shouldn't worry about initializing them to 0 in your code. In fact, you should really avoid it, as the initialization may waste memory. Only initialize them to values other than 0.
Memory overflow
int array[10];
int v = array[100];
array[-100] = 10;

The first problem here is that you don't know what will be assigned to v, but worse is that you don't know what you messed up with the assignment to position -100 of array.
Jump to an illegal instruction
void doSomething( void ) {
    for (int i = 0; i < 1000; i++);
}

void setup ()
{
    void (*funcPtr)( void );

    funcPtr = &doSomething;
    funcPtr(); // calls doSomething();

    funcPtr = NULL;
    funcPtr(); // undefined behavior
}

The first call to funcPtr() will actually be a call to doSomething(). Calls like the second one may lead to undefined behavior.
Other bad things that may happen
Well, you can run out of RAM, for example. What else. In any case, I think your program will keep running, probably not the way you intended it to.
Kinds of Protection
In computer systems, problems like these are usually dealt with at various levels:

By the compiler
By the programming language runtime (as in Java for example).
By the operating system or the processor (if your memory access a position outside the boundaries of the address space reserved to your program, the OS or the processor may have safety mechanisms to prevent that)

Arduinos only have limited protection of the compiler, and probably nothing else. The good news is that they aren't multi-tasked, so the only program being affected is yours. In any case, any of those bugs will lead to erratic behavior.
The Answers
The assumptions are the all of the problems I stated above are runtime problems.

What happens if there is a runtime error in a program?

The program will continue and what happens will depend on the side-effects of the runtime error. A call to the null function pointer will probably make the program jump to an unknown location.

Will execution of the program just stop?

No, it will keep going as if nothing extraordinary happened, probably doing what you didn't intend it to do. It may reset or act erratically. It may turn some inputs into outputs and burn a sensor or two (but that's highly unlikely).

Is there some way I get the Arduino to tell me what the error is?

I don't think so. As I said earlier, the protection mechanisms aren't there. There's no runtime support from the language, no OS, no hardware checks for out-of-bounds memory access (the bootloader doesn't count as either). You just have to be careful with your program and probably set your own safety nets.
The reason for the lack of protection is probably because Arduino controllers are too cheap, have too little memory, and should not run anything too important (yes, there seems to be a disclaimer by AVR somewhere for you not to use the MCUs normally used by Arduino in life support systems).

Great! The best answer I have seen on Arduino.SE so far!

Thanks!! I think we should strive to give great answers as much as possible. But it worries me a little the fact that we don't have that many REAL EE EXPERTS that could look at answers like mine and find any glaring mistakes. Actually, that's the reason I posted the answer even though I don't know that much about AVR MCUs. That's to see if we get someone to correct it. We sure don't want smart pents like me saying stuff that isn't right and getting away with it. But that's probably a discussion for the Meta site.

Would any of this damage the Arduino?

@AnnonomusPerson - The only likely mechanism for damage would be code that changes pin state in a manner that results in a bus contention (e.g. the ATmega trying to set a pin high, while external hardware is setting it low). It's also possible that if there is external hardware the ATmega is controlling that cannot handle certain control-input states, the external hardware could cause some manner of failure and damange, but an arduino with nothing connected it pretty bulletproof. The arduinos have series resistors to prevent possible contention issues on the serial lines.

@Ricardo - One comment I would make is that non-explicitly initialized variables are not necessarily uninitialized. Variables defined outside of functions generally have what's termed "automatic storage duration", which then get default-initialized to zero. See http://en.cppreference.com/w/cpp/language/default_initialization for more information. The initialization behaviour is complex enough that it's probably dangerous to rely upon, but making blanket statements is probably not a great idea.

Furthermore, the SRAM is initialized to 0 at reset or startup, so you can make some informed guesses about uninitialized variables, if you want to live dangerously. You shouldn't rely on this behaviour, but it is interesting.

There is an interesting example of what happens when you run out of SRAM here: http://electronics.stackexchange.com/questions/42049/arduino-serial-print-changes-behavior-of-program-undesireably/42069. Basically, the stack clobbers part of the heap, or vice versa. This can do interesting things like corrupt some part of the stack-frame (breaking function returns, etc), or writing invalid data to variables.

Also relevant is the question about recursion: http://arduino.stackexchange.com/questions/355/how-much-can-i-recurse-how-much-can-i-recurse-how-much-caqfsdrfw since recursion is one of the easy ways to blow the stack.

@FakeName - Right! I'll edit my answer to fix the statement about uninitialized variables. As for the other great suggestions you posted, why don't you make them an answer and I'll add a reference to it from mine? Glad to see you (or maybe just the picture of your annoyed cat) around here.

@FakeName - BTW, that picture always reminds me of the great Cat Yodeling technique from Engineer's Guide to Cats at 4:57min.

One note: The good news is that you only messed up with RAM and not with the EEPROM, thus your program is safe.. The program running on the ATmega is stored in the Flash memory, not EEPROM. The EEPROM is generally only 1-2 KB, and is more for storing small amounts of non-volatile data (think: user configuration settings, serial number, etc...), not actual code.

@ConnorWolf Right! Well spotted. Just edited and fixed my answer.

the C++ compiler does that for you. It sets it as zero Local variables are not initialized. I interpret status to be local in your example therefore this is wrong. it's not considered good practice to rely on that behaviour it actually is considered good practice to rely on that behavior for global variables since it's guaranteed that they will be zero-initialized and zero initializing globals in your code can waste memory(though current compilers should be smart enough to avoid this) see http://www.atmel.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_varinit.html

You wrote: “array[-100] = 10; [...] you only messed up with RAM [...] thus your program is safe.” You may well end up writing into the IO space of the MCU, which is memory-mapped right below the RAM on the AVRs. This is definitely not safe. “[Calling a NULL function pointer] that's equivalent to a soft boot”. Not exactly. The program will restart from the very beginning: it will initialize the stack pointer, the RAM, call main, etc. But, unlike a soft boot, this does not reset the IO registers to their default initial state.

@Connor Wolf: You wrote: “the SRAM is initialized to 0 at reset or startup”. This is incorrect. Unlike the IO registers, the SRAM is not initialized by the hardware at startup. The BSS section of the RAM (and only this section) is initialized to zero by the C runtime. The DATA section is initialized to whatever contents the programmer requested. All the remaining RAM is left uninitialized.

@EdgarBonet - Point taken. Too bad I can't edit my older comments.

@EdgarBonet - Thanks for pointing out the problem with my answer. I read the link you provided and have tried to correct the statements about local variables. Would you please check it out? Thanks!

Your statement about the program restarting when calling a NULL function pointer was correct, at least on the AVR. I was just pointing out that restarting the program is not quite the same as a reset. BTW, there is no illegal instruction involved in the process. “Would you please check it out?” I cannot find anything wrong in your answer.

There are no runtime exceptions. There is only undefined behaviour.
Really, there are no exceptions at all. If you try to perform an invalid operation, it's results will be unknown.
There is no runtime checking at all, except what you implement. Your program is running on bare-metal hardware. It's the Desktop equivalent of running in ring-0 all the time, because the ATmega doesn't have rings.

There is one mechanism that can get MCU from erratic state and it's the watchdog timer. If you're implementing some code that will repeatedly run in a loop, that will not run anytime longer than some fixed time, you can set this time as watchdog period and enable the timer.
Then, you have to repeatedly reset the timer in the loop. If your code freezes at some condition loop that will never end, then the watchdog will count to zero and eventually reset the MCU.
This way you are losing data, but if you run the AVR WDT in interrupt mode, you can store some data before resetting the MCU.
So the watchdog timer can guard your code from occasional unintended endless loops.
Documentation: AVR132: Using the Enhanced Watchdog Timer

You'd need a hardware debugger for something like this. But usually you'll see the program not behaving as you expect it to and will have to look at that section of the code to identify the problem.
A common/quick/easy way to do this is to add print statements to print out the values of variables or just anything so you know the program gets to that point in the code without a problem. This will help you isolate the problem further.
I believe VisualMicro has some debugging functionality built in.

I would assume the AVR CPU doesn't have any error detection or recovery tools. It may just stop, or keep going ignoring the error and the consequences. Like sachleen said, you should add some debug statements in your program that print out data in the middle of an operation, to test if it's working. If you use an emulaor and set breakpoints, you could easily find a problem.

I wrote an *.ino environment:
// Testing environment for Arduino sketch files.
// Aduino IDE 2.3.0
// Author   : Anders Munck
// Released : 2024 02 09

#include <iostream>

const bool LOW=false;
const bool HIGH=true;
const bool INPUT=false;
const bool OUTPUT=true;
const unsigned char LED_BUILTIN=13;

using namespace std;

void where(std::string hank)
{ cout <<"Where : "<<hank<<"\n"; }

int random(int max)
{ return std::rand(); }

unsigned long klokken=0;
unsigned long int millis()
{ klokken++;
  cout <<"When : "<< klokken <<"\n";
  return klokken;
}

class SERIAL
{ public:
    void begin(int Baud)
    { cout<<"Arduino sketch : Serial.begin()\n"; };
    void end()
    { cout<<"Arduino sketch : Serial.end()\n"; };
    void print(std::string A)
    { cout<<"Arduino sketch : print()\n"; };
    void println(std::string A)
    { cout<<"Arduino sketch : println()\n"; };
} Serial=SERIAL();

void digitalWrite(unsigned char A,bool S)
{ cout << "Arduino sketch : digitalWrite()\n"; }

void pinMode(unsigned char A,bool S)
{ cout << "Arduino sketch : pinMode()\n"; }

// Include Your Arduino sketch file here:
#include "signal.ino"

int main()
{ setup();
  for(int i=0;i<100;i++){ loop(); };
  return 0;
}

The purpose is to get run time error messages from the *.ino sketch.
You will not get usefull timing information this way, as the program is running on another processor.
I run it with a GPU C++ IDE.
Please regard my code as preliminary ad-hoc program; You may need to develop further for Your needs.

The downvote is not mine. You need to explain your code and what it does.

the Question is 10 years old. just saying in case you didn't notice

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to really shrink a sketch
I want to make a sketch that is as small as possible, for test purposes. The problem is, when i compile the BareMinimum sketch (with an empty setup and loop), i get 466 bytes for the Uno and a whopping 4,242 for the Leonardo. Is there any way to write your own code that has no extra functions (namely Timer0 for millis() and delay()). I would also like to be able to disable the keyboard/mouse functions for the Leonardo.

Shouldn't this be tagged leonardo and not uno (and focus on one board)? These are separate questions.

I'm just pointing out that a blank compiled sketch is large for a lot of boards, especially the native USB based ones

I would also like to be able to disable the keyboard/mouse functions for the Leonardo. is the second question.

You should be able to create your own board definition with a custom boards.txt file as per https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification. As I see there are several usb features in the leonardo's definition. I would hope that the compiles inclusion of the 4K is based off of these flags and not the processor type.
Where the boards.txt would use the upload, bootloader sections from the Leonardo and the build from the uno.
This is all assuming the core library build does not use processor specific flags to include USB functions.
If you get such working. post back, I am sure others would be interested in such.

I recently ran into this 4K used limitation on a library demo that actually maxed out the UNO and had to put in a
#if !defined(__AVR_ATmega32U4__)
...

around a large chunk of extra features in the sketch to fit on the Leonardo.
I had assume (wrong) that this 4K was because I still included Serial.print which when over the USB's CDC on the Leo. But I see after a memory dump of an empty sketch they are still there.
C:\Users\mflaga\AppData\Local\Temp\build8958339595868119500.tmp>avr-objdump -d sketch_feb13a.cpp.elf > sketch_feb13a.cpp.elf.lst

Which makes sense. As the Leonardo still requires the USB-CDC client (the 4K) as to detect the 1200 Baud connect from AVR-DUDE as to stroke the remote reboot.

Hence making a custom boards.txt without USB in the build, also needs to have
leonardo.upload.use_1200bps_touch=true

removed.
Once loaded on the target, this would require the upload to be synchronized with a manual reset of the target. As the ability to remote reboot is lost.

updated as to why 4K is still compiled in, even if Serial.print is omitted.

I recently wanted to do exactly this. Since there is no nice way to do so, I wound up writing a patch for the Stino sublime-text arduino plugin to do exactly this. It's subsequently been accepted, so it should be in any up-to-date Stino installs.
This adds a new option to Stino:

Using this mode produces compilation results like the following:
For a Uno:

Binary sketch size: 172 bytes (of a 32256 byte maximum, 0.53 percent).
  Estimated memory use: 0 bytes (of a 1024 byte maximum, 0.00 percent).

For a leonardo

Binary sketch size: 240 bytes (of a 28672 byte maximum, 0.84 percent).
  Estimated memory use: 0 bytes (of a 2560 byte maximum, 0.00 percent).

Actually programming the leonardo with the above compiled output is probably a bad idea, as it might break the auto-reset functionality, but you could, if you wanted. Hat-tip to mpflaga for noting this in his answer.
Note that the memory reports are actually incorrect, but that's a separate issue.
The code used for the above is:
int main()
{
    while (1)
    {

    }
}

Some notes:

You ain't writing a "Sketch" anymore, not that you ever actually do write a sketch. You write programs. Period. I don't care what the Arduino wackos want to say, they don't get to redefine terms.
All interrupt management is manual. This means no milis() or similar.
You can still use the arduino serial libraries and so forth, if you want. You do have to #include <Arduino.h>.
You define main. You don't ever return from main. If you want setup stuff, it goes before the while (1).

@jfpoilpret You call that an IDE? More like notepad with macros...

@Ron-E I don't call it an IDE, Arduino IDE is its name, so I just used its name, even though it is not worth that name.

@FakeName Bad language isn't permitted on Stack Exchange sites (see: http://stackoverflow.com/help/behavior). I've edited it out in this case, but please try to refrain from using expletives on this site in future. Thanks.

Although it depends on your sketch, you can somewhat decrease the size by reusing code with methods.
Take this code:
int led = 13;
int val;

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

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  val = digitalRead(10);
}

1,322 bytes on Arduino Uno. Now let's shrink it a bit:
int led = 13;
int val;

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

void loop() {
  for(uint8_t i = 0; i < 8; i++) {
    blink(HIGH);
    blink(LOW);
  }
  val = digitalRead(10);
}

void blink(uint8_t state) {
  digitalWrite(led, state);   // turn the LED to the right state
  delay(1000);                // wait for a second
}

1,194 bytes. That's about a 10% decrease!
Anyway, although it doesn't greatly shrink a sketch, it sometimes can be the easiest route when you are two bytes over the limit, or just want to make a more compact sketch to begin with without loosing any functionality. It's not for every situation, but I find it useful sometimes.

Generally, if you pull code out into functions, the compiler will do the hard work and get the rest right for you.

@Cybergibbons Can you define that [for users that aren't familiar with that]?

If you break out code into a function and it isn't efficient, generally the compiler will in-line it for you. However, a compiler will never break code out into functions. Therefore, it's nearly always better to write  more functions.

Plus putting the code into functions makes it much more easier to read and understand

Using direct port access, the size is decreased to 646 bytes. Using only avr-libc (no Arduino core), it gets down to 220 bytes.

@annonomus penguin, sure we can
Although the code compiles into 1180 bytes flash + 13 bytes RAM for an uno on my computer, we can improve on it :) so golf challenge accepted and also a few usefull tips since we are in the business of learning.
Step 1: decrease variable requirements.
Using an int for a led port seems a bit overkill, we certainly don't have 65535 addressable IO ports on the arduino :) So we change it to a byte just for the fun of it. We will change it over to a #define later on, but to show the impact of using too large variable types.
byte led = 13;
int val;

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

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Compiles into 1172 bytes + 13 byte RAM. This saves 8 bytes of flash due to fewer needed operations for the byte instead of a integer. I would expect 12 bytes of ram, but okay. Not that much, but every byte saved is good.
Step 2: change over variable into defines when it makes sense.
For example, the led byte is not needed, the pin won't unsolder itself.
#define LED 13
int val;

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

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Compiles into 1142 bytesflash + 11 bytes ram. Already 38 bytes saved. This is due to fewer register operations needed to fetch the int value. Also we saved 2 bytes from RAM. (still wondering why the byte didn't compile into 1 less byte of ram.....)
Step 3: optimize code.
I see 2 delays. I wonder if i change it to 1 delay it would save space, but i have to figure out the value of the LED pin and toggle (invert) it. We can do that with digitalRead(), but will it save space?
#define LED 13
int val;
void setup() {
  pinMode(LED, OUTPUT);
}
void loop() {
  blink();
  val = digitalRead(10);
}
void blink() {
  digitalWrite(LED, !digitalRead(LED));   // toggle the led based on read value
  delay(1000);               // wait for a second and spare yourself the other delay
}

Compiles into 1134 bytes + 11 bytes ram. Yay! another 8 bytes. That makes a total of 46 bytes and 2 fewer lines of code.
Also another general tip on decreasing codesize. Don't use the String class. It's HUGE, learn how to deal with char arrays, strcpy(), strcmp(). If all you have are some basic string operations, the usage of the String class is mostly just wasting space on both flash and RAM.


text:
When to use different variable types?
There are several different types in the Arduino programming language. They each have different applications that can use up the limited RAM in the Arduino. When should i use each?

Could just be me, but this doesn't seem on-topic. I mean, it's basically an SO question. Maybe a topic for a [meta] question?

While I'm inclined to agree that this isn't entirely on-topic, I suppose it's worth noting that the types available using the Arduino IDE aren't exactly the same as regular C++. Notably, the type names boolean, byte and word. are not standard C++. Additionally, the String class is nothing like the C++ std::string. Perhaps a more specific question about the differences is warranted?

I think this question has value as these are not standard types. Explaining how the map from Arduino to avr-gcc is important.

First of all, arduino programmers may not want to go to SO to get their questions answered. second of all, The Arduino has very limited ram, so variable choice based on variable size is important.

The question was in context of specific usage and differences from that when used in Arduino.

I can understand the practicality of this question based on your answer, but from the question it's not immediately clear to me. Perhaps rewording the title to something like "What are the limits of the data types on the Arduino platform?"

It should probably also be mentioned that no one should use int, long, long long or similar variable declarations anyways. They should be using the types defined in <stdint.h> (e.g. uint8_t, int16_t, etc...), since int does not have a specified size in C/C++, and making compilation behaviour dependent on compiler implementation defined behaviour is irresponsible.

@TheDoctor - If you rewrite this question to be better phrased, it would probably be reopened. Right now, there is no evidence of even understanding what the difference between types.

@FakeName Relying on some of the stdint types for compiler portability isn't always a good idea because they won't necessarily exist. Things like uint32_t will not be defined if the compiler doesn't support a type matching the specified size. Therefore, where exact size is not critical, it may be better to use more generic types.

One should appreciate that the Arduino is an Embedded Processor. Specifically that it has limited resources of RAM and ROM(aka Flash/program space).
Often is the case I see coding use the "int" defaultly. Almost sloppily. If that works great.
BUT!!!!
You can run out of room REAL FAST with only 2K of RAM.
I would recommend that you size down your type to the minimum of what it needs to be describing it. One also gets a better understanding of what it really is and its limitations. There is no need for an array of int(16bits) from bytes that were recieved from the SPI, UART or I2C. Or a matrix of RGB's that consume 3 bytes each, being int's. You cut your capacity in half.
The pro/con: PRO: using default int everywhere makes it more inter changeable. The CON is that such interchangeability can lead to unintentional casting errors.
I would also recommend using C99 type def's which can be found at "avr_stdint.html">http://www.nongnu.org/avr-libc/user-manual/group_avr_stdint.html" and elsewhere. It makes things vivid, regards to this aspect. Hence a "int" would be a "int16_t", "unsigned long" be "uint32_t" etc...
It is worth knowing that in some cases a byte or char can not be replaced with int8_t, as such when used with string array functions. But they are still just as vivid.

Or you could use the mega with 128x the ram :)

@TheDoctor - the mega only has 4X the ram. 2K vs 8K

@FakeName - sorry, that's 256kb flash

@TheDoctor - That's still only 8X. 32K vs 256K.

An overview of the most commonly used variables:

byte: uses one byte (8 bits), holds numbers from 0 to 255
char: a signed byte
boolean: uses 1 byte, but only holds a value of true or false
int: uses 2 bytes, holds numbers from -32768 to 32767, mostly used in general programming. an int is what is known as a signed variable, where the last bit controls if it is negative or positive
long: uses 4 bytes, holds numbers from -2147483647 to 217283648, it is also signed
long long: uses 8 bytes, can hold -9223372036854775808 to 9223372036854775807, signed
float: uses 4 bytes, holds decimals from -3.4028235E+38 to 3.4028235E+38.
double: almost identical to float
string: an array of chars that represent text
String: not to be confused with string, this is a class that holds text data with extra functions

Most variable declarations can be prefixed with signed or unsigned to change the function of the sigh bit. For example, unsigned int x = 0; would create a variable that holds numbers from 0 to 65535 because the sign bit is used as an extra data bit.

This makes some extremely broad assumptions, and does not list their caveats. All the variable sizes are not specified, can vayry on some platforms/compilers, and is compiler implementation dependent. Furthermore, you're grossly oversimplifying things like floats, which have a large range, but limited resolution.


text:
Sending Large Amounts of Serial Data
So in the fields of robotics sometimes you need multiple boards and or computers linked together to share information or save statistical data. Currently I need to send a few different variables over a serial connection and was wondering what was the best way to go about doing such?
So far I've determined that sending structures would probably be the easier way to send data. Does anyone know of any other way that might be more efficient?
Please keep in mind that I will essentially be having to send the data for 4 motors, compressor, different temperatures, random things, and the 3 sections of the arm.

With my personal thoughts on Structs being the most efficient way to send many different variables I've constructed a library to help make it easier to send structs and variables over serial.  Source Code
In this library it makes sending through serial easily. I've used with with hardware and software serial. Usually this is used in conjunct with xbee's so I can wirelessly send the data to and from the robot.
When sending data it make it simple as it allows you to either send a variable or a struct (it doesn't care).
Here is an example of sending a simple char over the serial:
// Send the variable charVariable over the serial.
// To send the variable you need to pass an instance of the Serial to use,
// a reference to the variable to send, and the size of the variable being sent.
// If you would like you can specify 2 extra arguments at the end which change the
// default prefix and suffix character used when attempting to reconstruct the variable
// on the receiving end. If prefix and suffix character are specified they'll need to
// match on the receiving end otherwise data won't properly be sent across

char charVariable = 'c'; // Define the variable to be sent over the serial
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Example of sending a simple int over the serial:
int intVariable = 13496; // Define the int to be sent over the serial
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Example of sending a struct over serial:
// Define the struct to be sent over the serial
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct;
simpleStruct.charVariable = 'z'; // Set the charVariable in the struct to z

// Fill the intVariable array in the struct with numbers 0 through 6
for(int i=0; i<7; i++) {
  simpleStruct.intVariable[i] = i;
}

// Send the struct to the object xbeeSerial which is a software serial that was
// defined. Instead of using xbeeSerial you can use Serial which will imply the
// hardware serial, and on a Mega you can specify Serial, Serial1, Serial2, Serial3.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Send the same as above with a different prefix and suffix from the default values
// defined in StreamSend. When specifying when prefix and suffix character to send
// you need to make sure that on the receiving end they match otherwise the data
// won't be able to be read on the other end.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'u');

Receiving Examples:
Receiving a char that was send via Streamsend:
char charVariable; // Define the variable on where the data will be put

// Read the data from the Serial object an save it into charVariable once
// the data has been received
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable));

// Reconstruct the char coming from the Serial into charVariable that has a custom
// suffix of a and a prefix of z
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Receiving an int that was sent via StreamSend:
int intVariable; // Define the variable on where the data will be put

// Reconstruct the int from xbeeSerial into the variable intVariable
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Reconstruct the data into intVariable that was send with a custom prefix
// of j and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Receiving a Struct that was sent via StreamSend:
// Define the struct that the data will be put
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct; // Create a struct to store the data in

// Reconstruct the data from xbeeSerial into the object simpleStruct
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Reconstruct the data from xbeeSerial into the object simplestruct that has
// a prefix of 3 and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'p');

Once you read the data using StreamSend::receiveObject() you need to know if the data was GOOD, Not Found, or BAD.
Good = Successful
Not Found = No prefix character was found in the specified ostream
Bad = Somehow there was a prefix character found, but the data isn't intact. Usually it means there was no suffix character found or the data wasn't the correct size.
Testing Validity of Data:
// Once you call StreamSend::receiveObject() it returns a byte of the status of
// how things went. If you run that though some of the testing functions it'll
// let you know how the transaction went
if(StreamSend::isPacketGood(packetResults)) {
  //The Packet was Good
} else {
  //The Packet was Bad
}

if(StreamSend::isPacketCorrupt(packetResults)) {
  //The Packet was Corrupt
} else {
  //The Packet wasn't found or it was Good
}

if(StreamSend::isPacketNotFound(packetResults)) {
  //The Packet was not found after Max # of Tries
} else {
  //The Packet was Found, but can be corrupt
}

SteamSend Class:
#include "Arduino.h"

#ifndef STREAMSEND_H
#define STREAMSEND_H

#define PACKET_NOT_FOUND 0
#define BAD_PACKET 1
#define GOOD_PACKET 2

// Set the Max size of the Serial Buffer or the amount of data you want to send+2
// You need to add 2 to allow the prefix and suffix character space to send.
#define MAX_SIZE 64

class StreamSend {
  private:
    static int getWrapperSize() { return sizeof(char)*2; }
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar);
    static char _prefixChar; // Default value is s
    static char _suffixChar; // Default value is e
    static int _maxLoopsToWait;

  public:
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize);
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static boolean isPacketNotFound(const byte packetStatus);
    static boolean isPacketCorrupt(const byte packetStatus);
    static boolean isPacketGood(const byte packetStatus);

    static void setPrefixChar(const char value) { _prefixChar = value; }
    static void setSuffixChar(const char value) { _suffixChar = value; }
    static void setMaxLoopsToWait(const int value) { _maxLoopsToWait = value; }
    static const char getPrefixChar() { return _prefixChar; }
    static const char getSuffixChar() { return _suffixChar; }
    static const int getMaxLoopsToWait() { return _maxLoopsToWait; }

};

//Preset Some Default Variables
//Can be modified when seen fit
char StreamSend::_prefixChar = 's';   // Starting Character before sending any data across the Serial
char StreamSend::_suffixChar = 'e';   // Ending character after all the data is sent
int StreamSend::_maxLoopsToWait = -1; //Set to -1 for size of current Object and wrapper

/**
  * sendObject
  *
  * Converts the Object to bytes and sends it to the stream
  *
  * @param Stream to send data to
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize) {
  sendObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}

void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  if(MAX_SIZE >= objSize+getWrapperSize()) { //make sure the object isn't too large
    byte * b = (byte *) ptr; // Create a ptr array of the bytes to send
    ostream.write((byte)prefixChar); // Write the suffix character to signify the start of a stream

    // Loop through all the bytes being send and write them to the stream
    for(unsigned int i = 0; i<objSize; i++) {
      ostream.write(b[i]); // Write each byte to the stream
    }
    ostream.write((byte)suffixChar); // Write the prefix character to signify the end of a stream
  }
}

/**
  * receiveObject
  *
  * Gets the data from the stream and stores to supplied object
  *
  * @param Stream to read data from
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize) {
    return receiveObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  return receiveObject(ostream, ptr, objSize, 0, prefixChar, suffixChar);
}

byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar) {
  int maxLoops = (_maxLoopsToWait == -1) ? (objSize+getWrapperSize()) : _maxLoopsToWait;
  if(loopSize >= maxLoops) {
      return PACKET_NOT_FOUND;
  }
  if(ostream.available() >= (objSize+getWrapperSize())) { // Packet meets minimum size requirement
    if(ostream.read() != (byte)prefixChar) {
      // Prefix character is not found
      // Loop through the code again reading the next char
      return receiveObject(ostream, ptr, objSize, loopSize+1, prefixChar, suffixChar);
    }

    char data[objSize]; //Create a tmp char array of the data from Stream
    ostream.readBytes(data, objSize); //Read the # of bytes
    memcpy(ptr, data, objSize); //Copy the bytes into the struct

    if(ostream.read() != (byte)suffixChar) {
      //Suffix character is not found
      return BAD_PACKET;
    }
      return GOOD_PACKET;
  }
  return PACKET_NOT_FOUND; //Prefix character wasn't found so no packet detected
}

boolean StreamSend::isPacketNotFound(const byte packetStatus) {
    return (packetStatus == PACKET_NOT_FOUND);
}

boolean StreamSend::isPacketCorrupt(const byte packetStatus) {
    return (packetStatus == BAD_PACKET);
}

boolean StreamSend::isPacketGood(const byte packetStatus) {
    return (packetStatus == GOOD_PACKET);
}

#endif

All-code answers, like all-link answers are discouraged. unless your code has tons of comments, i would recommend putting some explanation of what is going on

@TheDoctor, I've updated the code. There should be more comments now

If you really wanted to send it fast, i recommend Full Duplex Serial (FDX). It's the same protocol that USB and ethernet use, and it's a lot faster than UART. The downside is that it usually requires external hardware to facilitate the high data rates. I've heard that the new softwareSreial supports FDX, but this may be slower even than hardware UART. For more on communication protocols, see How to connect two Arduino without shields?

This sound interesting. I'll have to look further into it.

How can "full duplex serial" be "a lot faster than UART" when it is, in fact, standard UART communication?

UART is a fixed rate communication. FDX sends data as fast as possible and resends the data that didn't make it.

I would love to find out more about this protocol.
Could you add a link to your answer that describes a protocol that is faster than UART?
Are you talking about the general idea of automatic repeat request using ACK-NAK, or is there some specific protocol you have in mind?
None of my Google searches for "FDX" or "full duplex serial" seem to match your description.

Sending a structure is fairly simple.
You can declare the structure as you normally would, and then use memcpy(@myStruct,@myArray) to copy the data to a new location, and then use something similar to the below code to write the data as a datastream.
unsigned char myArraySender[##];   //make ## large enough to fit struct
memcpy(&myStruct,&myArraySender);  //copy raw data from struct to the temp array
digitalWrite(frameStartPin,High);  //indicate to receiver that data is coming
serial.write(sizeof myStruct);     //tell receiver how many bytes to rx
Serial.write(&myArraySender,sizeof myStruct);   //write bytes
digitalWrite)frameStartPin,Low);   //done indicating transmission

Then you can attach an interrupt routine to the pin on the other device that does the following:
volatile unsigned char len, tempBuff[##];
//volatile because the interrupt will not happen at predictable intervals.

attachInterrupt(0,readSerial,Rising);

//tell the mcu to call fxn when pinhigh. This will happen during virtually any moment. if that is not desired, remove the interrupt and simply watch for new characters in your main executive loop (aka, UART polling).
void readSerial(unsigned char *myArrayReceiver){
    unsigned char tempbuff[sizeof myArrayReceiver];
    while (i<(sizeof myArrayReceiver)) tempBuff[i]=Serial.read();
    memcpy(&tempbuff,&myArrayReceiver);
    Serial.flush();
}

Syntax and use of pointers will need some review. I pulled an all-nighter so I'm sure the above code won't even compile, but the idea is there. Fill your structure, copy it, use out-of-band signalling to avoid framing errors, write the data. On the other end, receive the data, copy it to a struct, and then the data becomes accessible via normal member access methods.
The use of bitfields will also work, just be aware that the nibbles will appear to be backwards. For instance, attempting to write 0011 1101, may result in 1101 0011 appearing at the other end if the machines differ in byte order.
If data integrity is important, you can also add a checksum to make sure you aren't copying misaligned garbage data. This is quick and effective check that I recommend.

If you can tolerate the data volume, debugging communicatons is so much easier when sending strings than when sending binary; sprintf()/sscanf() and their variants are your friends here. Enclose the communication in dedicated functions in their own module (.cpp file); if you need to optimize the channel later - after you have a working system - you can replace the string-based module with one coded for smaller messages.
You'll make your life lots easier if you hold tight to protocol specs on transmission and interpret them more loosely on reception, regard to field widths, delimiters, line endings, insignificant zeros, presence of + signs, etc.

Originally the code was written to send back data in a stabilizing loop of a Quadcopter so it had to be fairly fast.

I have no official credentials here, but in my experience things have gone pretty efficiently when I pick a certain character position(s) to contain the state of a variable, so that you might designate the first three characters as the temperature, and the next three as the angle of a servo, and so on. On the sending end I would save the variables individually and then combine them in a string to send serially. On the receiving end I would have the string picked apart, getting the first three characters and turning them into whatever variable type i need, then doing so again to get the next variable value.
This system works best when you know for certain the amount of characters each variable will take up, and you always look for the same variables (which I hope is a given) each time the serial data loops through.
You can pick one variable to put last of indeterminate length and then get that variable from it's first character to the end of the string. Granted, the serial data string could get really long depending on the variable types and the sheer amount of them, but this is the system I use and so far the only setback I've hit is the serial length, so that's the only disadvantage I know of.

What kind of functions do you use to save x amount of characters into an int/float/char?

You may not realise this, but what you describe is exactly how a struct is organised in memory (disregarding padding) and I imagine the data transfer functions that you use will be similar to the ones discussed in Steven's answer.

@AsheeshR I actually had a feeling structs might be that way, but I personally tend to hit a wall when trying to reformat structs and then read them again on the other side. That is why I figured I'd just do this string thing, so that I could easily debug if things get misread, and so that I could even read the serial data myself if I designate it like "MOTORa023 MOTORb563" and so on, without the spaces.

@Steven10172 well I admit I don't keep track of the specific functions, rather I google the particular function each time. String to int, String to float, and String to char. Bear in mind that I use these methods in regular c++ and have not tried them in the Arduino IDE myself.

Send struct data across serial
Nothing fancy. Sends a struct. It uses an escape character '^' to delimit the data.
Arduino code
typedef struct {
 float ax1;
 float ay1;
 float az1;
 float gx1;
 float gy1;
 float gz1;
 float ax2;
 float ay2;
 float az2;
 float gx2;
 float gy2;
 float gz2;

} __attribute__((__packed__))data_packet_t;

data_packet_t dp;

template <typename T> void sendData(T data)
{
 unsigned long uBufSize = sizeof(data);
 char pBuffer[uBufSize];

 memcpy(pBuffer, &dp, uBufSize);
 Serial.write('^');
 for(int i = 0; i<uBufSize;i++) {
   if(pBuffer[i] == '^')
   {
    Serial.write('^');
    }
   Serial.write(pBuffer[i]);
 }
}
void setup() {
  Serial.begin(57600);
}
void loop(){
dp.ax1 = 0.03; // Note that I didn't fill in the others. Too much work. ;p
sendData<data_packet_t>(dp);
}

Python Code:
import serial
from  copy import copy
from struct import *

ser = serial.Serial(
#   port='/dev/cu.usbmodem1412',
  port='/dev/ttyUSB0',
#     port='/dev/cu.usbserial-AL034MCJ',
    baudrate=57600
)

def get_next_data_block(next_f):
    if not hasattr(get_next_data_block, "data_block"):
        get_next_data_block.data_block = []
    while (1):
        try:
            current_item = next_f()
            if current_item == '^':
                next_item = next_f()
                if next_item == '^':
                    get_next_data_block.data_block.append(next_item)
                else:
                    out = copy(get_next_data_block.data_block)
                    get_next_data_block.data_block = []
                    get_next_data_block.data_block.append(next_item)
                    return out
            else:
                get_next_data_block.data_block.append(current_item)
        except :
            break

for i in range(1000): # just so that the program ends - could be in a while loop
    data_ =  get_next_data_block(ser.read)
    try:
        print unpack('=ffffffffffff', ''.join(data_))
    except:
        continue


text:
What happens to the Arduino if you don't use a resistor with an LED?
Making a blinking light seems to be one of the most common beginner projects with Arduino. A typical approach is to connect an LED + resistor (in series) to an IO pin, and connect the other end to ground. In code, you make the pin an output, and bring it HIGH and LOW repeatedly to flash the LED.
What happens if you leave that resistor out? Obviously you're going to wreck the LED, but will it also damage the Arduino in some way?

From page 411 of the ATmega328P data sheet, we have a graph of the output current vs voltage.

We can see over the the 20mA range of output currents, we drop ~0.5V, giving an approximate internal resistance of 25Ω.
A typical LED has a forward voltage of about 2V. Therefore, we end up in the situation where we will drop 3V over the 25Ω internal resistance of the ATmega328P, giving an output current of 120mA.
I = (5-2)V / 25Ω = 120mA
This is a simplification, but this 120mA is far larger than the recommended maximum current per pin of 40mA of the microcontroller, and far in excess of what a normal LED should take.
That said, most LEDs and the ATmega328P seem to survive this kind of abuse, especially for short periods. In general, if the pin continues to work after this is done, it should be fine.

Leaving series resistors out will definitely greatly (exponentially) shorten lifetime of both the controller and the LED. Absolute maximum ratings for most AVRs are (a.o.):

max. 40mA per GPIO pin
max. 200mA per package.

A new Arduino sets you back $20 or more, a fist full 220 ohm resistors sets you back 1$. When treated within spec, an Arduino (and LEDs for that matter) can survive a lifetime.

I have done this once (being a beginner concerning electronics). The LED died, luckily the Arduino survived (without any pin problems).
Wouldn't recommend this as it is not good for the Arduino.


text:
Why do some pins have a different PWM frequency?
According to the Arduino reference for analogWrite(), the PWM frequency on most pins is ~490 Hz. However, it's ~980 Hz for pins 5 and 6 on the Uno, and for pins 3 and 11 on the Leonardo.
Why are these different? Is it a deliberate design feature, or is it somehow dictated by the hardware?

Those aren't the only frequencies available for the PWM signals. However, they are the frequencies as determined by the applied prescaler (which you can readily change as detailed below).
Each of the 3 pairs of PWM pins is tied to one timer, each of which has its own base frequency, as follows:

Pins 5 and 6 are paired on timer0, with base frequency of 62500Hz
Pins 9 and 10 are paired on timer1, with base frequency of 31250Hz
Pins 3 and 11 are paired on timer2, with base frequency of 31250Hz

Then each set of pins have a number of prescaler values that can be chosen, that will divide the base frequency of that pair of pins. The prescaler values available are:

Pins 5 and 6 have prescaler values of 1, 8, 64, 256, and 1024
Pins 9 and 10 have prescaler values of 1, 8, 64, 256, and 1024
Pins 3 and 11 have prescaler values of 1, 8, 32, 64, 128, 256, and 1024

The different combinations yield different frequencies in a given PWM pin. Notice that timer 2 (tied to pins 3 and 11) have more prescaler values available, resulting in more frequencies available.
Now, why timer 2 is different, that's a separate question.
Edit: Here's a list of possible PWM frequencies per pin (from this article):

For pins 6 and 5 (OC0A and OC0B):

If TCCR0B = xxxxx001, frequency is 64kHz
If TCCR0B = xxxxx010, frequency is 8 kHz
If TCCR0B = xxxxx011, frequency is 1kHz (this is the default from the Diecimila bootloader)
If TCCR0B = xxxxx100, frequency is 250Hz
If TCCR0B = xxxxx101, frequency is 62.5 Hz

For pins 9, 10, 11 and 3 (OC1A, OC1B, OC2A, OC2B):

If TCCRnB = xxxxx001, frequency is 32kHz
If TCCRnB = xxxxx010, frequency is 4 kHz
If TCCRnB = xxxxx011, frequency is 500Hz (this is the default from the Diecimila bootloader)
If TCCRnB = xxxxx100, frequency is 125Hz
If TCCRnB = xxxxx101, frequency is 31.25 Hz

TCCRnB is where you set the prescaler bits for timer n, replacing n by 0, 1 or 2, depending on the timer you want to set. If you are still unsure about bitwise operations, read this bit math tutorial.
My sources:

http://playground.arduino.cc/Code/PwmFrequency
http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
http://arduino.cc/en/Tutorial/PWM
http://arduino-info.wikispaces.com/Arduino-PWM-Frequency

Note that there seems to be divergence in those sources about whether pins 9 and 10 have the same behavior as 5 and 6 or 3 and 11, but you get the idea anyway. I'm reading the datashet to try and figure out which is correct, or whether this is a difference between boards.

What ATmega does this answer refer to? I didn't check, but I bet it slightly differs per controller.

@jippie Good point! The sources refer to ATmega168 and 328.

@jippie Just to clarify, in my answer, the pin numbers refer to how they are assigner on the Uno board (pin 1 means Digital Pin 1, or D1, for example), not the IC (ATmega328 pin 1 is reset).

I believe those details change too with boards, Uno, Duemilanove, Mega, ...

@jippie Definitely, yes.

This answer is simply wrong. The timers use the same prescaler setting. The only difference is timer 1 and 2 are set to phase-correct PWM, while timer 0 is set to fast PWM, doubling the frequency.

I am not aware of the design considerations, but if you check the datasheet for the microcontroller on your Arduino, you will notice that PWM pins are grouped together and per group connected to a timer. The speed at which this timer is increased varies by the configured prescaler. If you change the prescaler for a certain timer, you change the PWM frequency for the related PWM pins. I believe some timers double for other purposes like the millis(); function. If you change the prescaler for that timer, values returned by millis() will be off by the same factor.
You can calculate the setting for the prescaler as follows:
$$\text{prescaler} = \dfrac{f_{CPU}}{PWMresolution × f_{PWM}} = \dfrac{16\text{MHz}}{256×490} \approx 128$$

prescaler = f[CPU]/(PWMresolution×f[PWM]) = 16000000/(256×490) = approx 128.

Check the datasheet and you'll find that 128 is indeed one of the prescaler values you can select.

Boy, do we miss MathJax or what? I hope we get it enabled after the beta.

@Ricardo I have a MathJax button in my browser ;o)   http://meta.arduino.stackexchange.com/questions/13/is-there-an-easy-way-to-enter-formulas-in-questions/51#51


text:
I got a missignatured ATmega328-PU. How can I fix that?
Sometime in the past, I was burning bootloaders on a fresh batch of four ATmega328-PU using the Arduino IDE (notice there's no P after 328 - it's the slightly cheaper non-picopower version of the MCU, not to be confused with the ATmega328P-PU with a P), and was surprised with the following message from avrdude:
avrdude: Device signature = 0x1e950F
avrdude: Expected signature for ATMEGA328 is 1E 95 14
Double check chip, or use -F to override this check.

That means avrdude thought the chip was not what its label said. Then I changed the chip type on my Arduino IDE to ATmega328P-PU and avrdude burned the bootloader without complaints. What that means is that the chip was labelled as one MCU and internally it responded as another, slightly different.
What I would like to know is:

How rare is this event? Has anyone had a similar experience? (Original question, off-topic)
Is it possible to fix this? How can I fix the signature so that avrdude recognize the chip correctly?

This is a cross-post from EE.SE. I posted this question there but didn't attract much attention, so I wanted to see if anyone from our community had a similar experience.

It seems that your vendor simply mislabelled some 328P's (which is what this signature represents) as 328s.

While browsing sparkfun, i have found several news posts that show their struggle with mislabeled chips. Here are a few:

https://www.sparkfun.com/news/350
https://www.sparkfun.com/news/384
https://www.sparkfun.com/news/364

Sparkfun had received a questionable shipment if ICs from a new seller in china. They decided to test them before sending them into production, and none of their test boards worked. Using nitric acid, they were able to remove the case of the ICs and fould a hunk of metal that looked like copper.
In another article, they dissected some suspicious ICs from Atmel, and found an ON semiconductor silicon wafer inside. The chips were not functional ATmegas, but they did have silicon, unlike the other ones.

Can you flesh this answer out a bit? Summarizing the articles you linked to would be a good start - right now, if sparkfun goes down for any reason your answer will be worthless.

@Shog9 Why? The question is way off base. This answer is a summary of instances of people receiving mislabeled chips (essentially people sharing experiences). Who is this going to help?

I could ask you the same, @AsheeshR - why worry about an answer when the question is the problem? Anyway, thanks for adding the detail, TheDoctor.

Not the preferred way to fix things and certainly not the first solution to consider, but you can consider programming the signature bytes. Before attempting this be absolutely sure you really want to do this and you have investigated what is involved to undo this. This may involve changing configuration files on your computer ...
Anyways the way to set the controller's signature bytes is as follows (untested, I don't have a spare AVR lying around):
avrdude -p atmega328 -c arduino -P /dev/ttyUSB003 -b 19200 -v -U signature:w:0x1E,0x95,0x14:m

I know this is very late, but I don't think it's a good idea to let this stand as the accepted answer unchallenged: The signature on an atmega328 is not writable, and to my knowledge, the signature is not writable on ANY atmega or attiny.

Out of interest, I tried the above approach, which avrdude accepted in a sense: avrdude: writing signature (3 bytes) - however it failed to do it: avrdude: verification error, first mismatch at byte 0x0002: 0x14 != 0x0f

There are several different flavors of ATMega328. The most commonly found in Arduinos Uno (et al) is the ATMega328P, which is Atmel's "picopower" version; this one has the 0x1E950F signature that AVRDude expects when it's tasked with programming an Arduino Uno. Gee, figure that.
Less common is the base model ATMega328 (no suffix) and the ATMega328PU, both of which yield a 0x1e9514 signature instead of the expected 0x1E950F.
As to commonality... that depends upon the crowd with which you run. If you are Arduino through-and-through, never use any boards that aren't teal-colored, then it's extremely uncommon for you to find a non-ATMega328P. If, on the other hand, you run in my gang and build all manner of cool stuff on funny-colored boards that don't have staggered header pin spacing in one spot... then it's very common to get non-p '328s.
There are workarounds. There was for a while a variant ArduinoISP_Multi that would translate a 0x1e9514 signature to a 0x1E950F signature, permitting you to gleefully program your breadboarded or otherwise non-teal '328 boards exactly as if they were genuine Arduino Unos. For whatever reason that "sketch" can no longer be found.
You can also edit avrdude.conf (with backup, please!) such that it (AVRDude) expects the signature that your '328 coughs up. The backup is particularly important because you may want someday to program "real teal". The avrdude.conf file can be found in your Arduino installation at ...\hardware\tools\avr\etc.
OR... wait! There's MORE! All for one money! You can also write your own hardware profile for non-P '328s and put it in your Arduino "sketchbook"'s hardware directory, then draw from that as a custom board definition. Aw, shucks... it ain't that hard! Really! I've written several of those for my own board designs.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What can I do if I run out of Flash memory or SRAM?
According to the Arduino documentation, the ATmega328 has 32KB of Flash memory for the bootloader + uploaded sketch, and only 2KB SRAM for runtime data. The ATmega2560 has quite a bit more, totalling 256KB and 8KB respectively.
In either case, those limits seem rather small, especially when compared to similarly sized consumer devices, such as smartphones.
What can you do if you run out? E.g. if your sketch is too big, or you need to process a lot of data (such as strings) at runtime? Is there any way to expand the Flash or SRAM?

Try using some variable optimization. Some different variable are discussed here

Use proper scopes for your variables if not already doing so, the compiler will optimize RAM usage for you when variables are unused.

You might actually use a Teensy 3.2 (with Teensyduino Software), which would be comparable to an Arduino. Given that you're running out of RAM/PROGMEM it would mean that you're also likely that what you're trying to do is pushing your Arduino. A Teensy 3.2 is not that much more expensive. but has: 32bit, 72MHz (wtf!?) 256KB FLASH and 64KB RAM and 3x UART. Not more program memory as the ATmega2560, but the RAM and speed increase should suffice.

Optimisation
Low-level programming for embedded systems is quite different from programming for general purpose devices, such as computers and cell phones. Efficiency (in terms of speed and space) is far more important because resources are at a premium. That means the very first thing to do if you run out of space is to look at what parts of your code you can optimise.
In terms of reducing program space (Flash) usage, the code size can be quite difficult to optimise if you're inexperienced, or if you're more used to programming for desktop computers which don't tend to need that skill. Unfortunately, there's no 'magic bullet' approach which will work for all situations, although it helps if you consider seriously what your sketch really needs to have. If a feature isn't needed, take it out.
Sometimes it's also helpful to identify where multiple parts of your code are the same (or very similar). You may be able to condense them into reusable functions which can be called from multiple places. However, be aware that sometimes trying to make code too reusable actually ends up making it more verbose. It's a tricky balance to strike that tends to come with practice. Spending some time looking at how code changes affect the compiler output can help.
Runtime data (SRAM) optimisation tends to be a bit easier when you're used to it. A very common pitfall for beginner programmers is using too much global data. Anything declared at global scope will exist for the entire lifetime of the sketch, and that isn't always necessary. If a variable is only used inside one function, and it doesn't need to persist between calls, then make it a local variable. If a value needs to be shared between functions, consider if you can pass it as a parameter instead of making it global. That way you'll only use SRAM for those variables when you actually need it.
Another killer for SRAM usage is text processing (e.g. using the String class). Generally speaking, you should avoid doing String operations if possible. They are massive memory hogs. For example, if you're outputting lots of text to serial, use multiple calls to Serial.print() instead of using string concatenation. Also try to reduce the number of string literals in your code if possible.
Avoid recursion if possible as well. Each time a recursive call is made, it takes the stack a level deeper. Refactor your recursive functions to be iterative instead.
Use EEPROM
EEPROM is used for long-term storage of things that only change occasionally. If you need to use large lists or look-up tables of fixed data, then consider storing it in EEPROM in advance, and only pulling out what you need when necessary.
Obviously EEPROM is quite limited in size and speed though, and has a limited number of write cycles. It's not a great solution to data limitations, but it might be enough to ease the burden on Flash or SRAM. It's also quite possible to interface with similar external storage, such as an SD card.
Expansion
If you've exhausted all other options, then expansion may be a possibility. Unfortunately, expanding Flash memory to increase program space isn't possible. However, it is possible to expand SRAM. This means you may be able to refactor your sketch to reduce code size at the expense of increasing data size.
Getting more SRAM is actually fairly straightforward. One option is to use one or more 23K256 chips. They are accessed via SPI, and there is the SpiRAM library to help you use them. Just beware that they operate at 3.3V not 5V!
If you're using the Mega, you could alternatively get SRAM expansion shields from Lagrangian Point or Rugged Circuits.

You can also store constant data in program memory, rather then SRAM, if you have SRAM space issues and free program memory. See here or here

Another great alternative to EEPROM is an SD card. It does take up a few IO ports but if you do need a large chunk of space for, say map data or similar, it can be easy to swap out and edit with a custom program on a PC.

People should not be encouraged to use SPI SRAMs or RAM expansions, if they are running low on memory. That's just a waste of money. Choosing a bigger MCU would be cheaper. Beside, the performance could be very poor.
One should first make a ballpark estimation: if the estimated RAM usage is too close to the limit, then you're choosing the wrong board/microcontroller/development platform.
Sure, good usage (storing strings in flash) and optimization (avoiding using some libraries) can be true game changers. However at this point I see no benefits of using the Arduino Software platform.

When you upload your code to your Arduino, say an Uno for example, it'll tell you how many bytes it uses up out of the 32K available. That's how much flash memory you have (think computer hard disk). While your program is running, it's using whats called SRAM, and there is much less of that available.
Sometimes you'll notice your program behaving oddly at a point that you haven't even touched in a while. It could be that your most recent changes cause it to run out of memory (SRAM). Here are a few tips on how to free up some SRAM.
Storing strings in Flash instead of SRAM.
One of the most common things I've seen is the chip running out of memory because there are too many long strings.
Use the F() function when using strings so they are stored in Flash instead of SRAM, since you have much more of that available.
Serial.println(F("This string will be stored in flash memory"));

Use the right data types
You can save a byte by switching from an int (2 bytes) to a byte (1 byte). An unsigned byte will give you 0-255 so if you have numbers that don't go higher than 255, save a byte!
How do I know I'm running out of memory?
Usually you'll observe your program behaving strangely and wonder what went wrong... You didn't change anything in the code near the point where it's messing up, so what gives? It's running out of memory.
There are a couple of functions to tell you how much available memory you have.
Available Memory

Do you know if the F() thing is an Arduino specific function or is it in the AVR libraries? You could consider to mention PROGMEM const ... too.

Also you can use bit structures to further reduce space used by your variables 5eg if you deal with lots of boolean).

In addition to what others have said (on which I fully agree), I would advise to read this adafruit article about memory; it's well written, explains a lot of things about memory and provide hints on how to optimize it.
At the end of the read, I think you would get a quite complete answer to your question.
To sum it up, you have 2 possible optimization targets (depending on where you memory problems are located):

Flash (ie Program Memory); for this, you can:

remove dead code (e.g. any code that is included but not used) and unused variables (that one also helps with SRAM)
factor out duplicated code
remove the bootloader altogether (you can gain between 0.5K for a UNO and 2 or 4K for other Arduino models); this has some downsides though

SRAM (ie stack, heap and static data); for this you can:

remove unused variables
optimize the size of each variable (eg don't use long -4 bytes- if you need only int -2 bytes)
use the right scope for your variables (and prefer stack to static data when possible)
reduce buffers size to the strict minimum
move constant data to PROGMEM (ie your static data will stay in Flash memory and won't get copied to SRAM at program start); that also applies to constant strings for which you can use F() macro)
avoid dynamic allocation if it is not absolutely necessary; you will avoid a fragmented heap that may not shrink even after freeing memory

An additional approach to reduce SRAM usage is also described (but seldom used, because it is a bit heavy when coding and not very efficient), it consists in using EEPROM to store data built by your program, but not used until later when some conditions occur, when data can be loaded back from EEPROM.

Removing dead code-- the compiler is really good about handling this for you- it won't make any difference if you have lots of code that's not ever called. If you accidentally call code that you don't need, then that's different, of course.

There are two things to do if you run out of storage:

Somehow "optimize" your code so it needs less storage; or at least uses less of the particular kind of storage that you ran out of (and uses more of the kind of storage that you still have plenty of). Or,
Add more storage.

There are lots of tips online on how to do the first (and for the vast majority of things people do with the Arduino, the build-in storage is more than enough after "optimizing").
So I'll focus on the second:
There are 3 things that use up flash or SRAM; each one needs a slightly different approach to adding storage:

variable storage: it is possible to expand SRAM, as sachleen has already pointed out.
SRAM, FRAM, and NVSRAM are all appropriate for rapidly-changing variables.
(While in principle you could use flash to store variables, then you have to worry about flash wear-out).
SPI (a serial protocol) is the easiest to connect to the Arduino.
The SpiRAM library works with the Microchip 23K256 serial SRAM chip.
The Ramtron FM25W256 serial FRAM chip (now owned by Cypress) also uses SPI.
The Cypress CY14B101 NVSRAM also uses SPI.
Etc.
constant data that needs to still be there the next time the power comes on: this is almost as simple as expanding SRAM. There are many external EEPROM, FRAM, NVSRAM, and FLASH storage devices available.
Currently the lowest cost per MB are SD flash cards (which can accessed via SPI).
The Ramtron FM25W256 (see above), the Cypress CY14B101 (see above), etc. can also store constant data.
Many expansion shields include a SD card slot,
and several libraries and tutorials support reading and writing to (flash) SD cards.
(We can't use SRAM for this, because SRAM forgets everything when the power goes out).
executable code: Unfortunately, expanding an Arduino's Flash memory to increase program space isn't possible. However, a programmer can always refactor a sketch to reduce code size at the expense of increasing data size and making it run slightly slower. (In theory, you could go so far as translate your entire sketch into some interpreted language, store that version of your sketch on a SD card, and then write a interpreter for that language that runs on the Arduino to fetch and execute instructions from the SD card -- Forth on Arduino, a BASIC interpreter, a Tom Napier Picaro interpreter, some application-specific language, etc.).


text:
Is it possible to program an Arduino Pro Mini using an Arduino Uno R3?
I've recently received an Arduino Pro Mini as a gift, and I don't have an external USB programmer to program the Pro Mini. However, I do own an Arduino Uno R3, and I think it would be possible because they both have the same clock speed and micro-controller (16Mhz with an atmega328).
Is it possible to program an Arduino Pro Mini using an Arduino Uno?
If yes, how does one do so?

Which Pro Mini is it, 3.3V or 5V? I guess this must be the 5V one as I think the other one (3.3V) works only at 8MHz.

I use this method for my Leonardo..
http://forum.arduino.cc/index.php?PHPSESSID=15s79rlhp4mobav6canqahon54&topic=159904.msg1200578#msg1200578

Just hook up the pins (RX, TX, reset, Power, and Ground) to the corresponding pins on your Uno.
You may have to take the ATMega328 out of your Uno for this to work.
Keep in mind that you need to hook it up to the correct power pin! If your pro mini is running at 3.3v then you must hook it up to the 3.3 pin on your Uno.
Check out the ArduinoToBreadboard page for a bit more info. Scroll down to "Uploading Using an Arduino Board". Although it shows you how to program an Arduino on a breadboard, the wiring is the same.

You should remove the ATmega328 from the board. There is a vague chance that it would work without doing so, but chances are even if it superficially worked, you would get errors.

I've gotten it to work consistently as I have the SMD uno. Had to manually reset, though.

This one did not work for me.

you can program with an SMD board, you dont link the reset line, hold down the reset on the uno throughout the whole process, and tap the reset on the mini soon as the ide says upload to upload the sketch, by holding the uno in reset it doesn't interfere with the serial comms

Worked like a charm. I kept pressing on RESET for the whole duration of uploading, from before plugging Arduino until having finished uploading. Works great. Thanks a lot.

There is another method by which you can upload your sketch programs.  Program the UNO with the "Arduino as ISP" sketch and connect the pro mini via the SPI pins (plus reset line).  See "Upload with Programmer" on the Arduino website and elsewhere on the internet including stack exchange.  This method will allow you to use the full memory of the chip and avoid using the bootloader, but you will need to upload with SPI each time.


text:
What is the real lifetime of EEPROM?
ATMEL says the cell lifetime of an EEPROM cell is about 100,000 write cycle/ cell.
Is this actually how the EEPROM performs in the wild?
If I do not change the value of a cell, does this stress the lifetime? For example, if I write the value 0xFF to the same cell again and again, is this any different to writing 0x00, 0xFF, 0x00 etc.

As you state, the internal EEPROM has a lifetime of 100,000 write cycles. This isn't a guess - a very significant proportion of ATmega328 will reach this number with no issues. I have tested three processors before, and all reached 150,000 cycles with no issues.
It is important to note the failure mode of EEPROM. Most "EEPROM destroyer" projects repeatedly read/write until the data is not written at all. Before this point, the EEPROM will still be damaged. This would be manifested by data not being retained for a reasonable period. It is unwise to rely on anything more than 100,000 write cycles for this reason.
EEPROM is different to the RAM on an ATmega. Writing to it is not simple or quick, but it is wrapped up in a friendly Arduino library, hiding this complexity from the user.
The first level of indirection is the EEPROM library, which is trivially simple], just calling two other functions for read and write. This calls eeprom_write_byte, found here.
This function uses inline assembly, so might not be easily understood. There is a comment that is easily understood though:

Set programming mode: erase and write

This hints to one of the complexities of dealing with EEPROM - to write to
it, you first need to erase it. This means that if you call EEPROM.write(), it will perform a write cycle regardless of the value you are writing.
This means that repeatedly writing 0xFF will likely have the same effect as writing 0xFF,0x00,0xFF,0x00 etc.
There are ways to work around this - you can try calling EEPROM.read() before EEPROM.write() to see if the value is already the same, but this takes additional time.
There are other techniques to avoid excessive EEPROM wear, but their use depends on your application.

Wear leveling for EEPROM: http://electronics.stackexchange.com/questions/60342/wear-leveling-on-a-microcontrollers-eeprom

@Cybergibbons I am trying to determine why an EEPROM in a system is only retaining a value for seconds. E.g. if I read the value back immediately it looks like the write was successful. If I read it back seconds later I start seeing bits go from 1 to 0. You mentioned above "Before this point, the EEPROM will still be damaged. This would be manifested by data not being retained for a reasonable period." Does the failure mode I am describing sounds like something that could occur from a high number of erase/write cycles to a particular EEPROM location?

I once ran an experiment on an external EEPROM with 1 million max rated cycles. It took about 6 million cycles to become majorly corrupted, and before that it had progressed having sporadic amounts of corruption.
When you say you do not change the value, i am assuming you are writing the same data to an address multiple times. This almost certainly would stress the life, although it would probably not stress the surrounding cells.

The magic solution - if you dont want to code what Cybergibbons said about reading before writing, is the EEPROM.update() function. It does exactly that:
EEPROM.update(address, value);
will only write and stress the memory if value is different from that already stored.

http://hackaday.com/2011/05/16/destroying-an-arduinos-eeprom/

The Arduino was plugged into a wall wart and sat, “behind a couch for a couple of months.” The EEPROM saw it’s first write error after 47 days and 1,230,163 cycles. This is an order of magnitude better than the spec on the atmel datasheet, but similar to the results of similar experiments.

This seems far too high. I had heard of 150k to 200k before, but never this :o

The problem is that this doesn't detect all the failure modes. When EEPROM becomes damaged, what happens is the length of time that it will retain data is gradually decreased. At 100,000 cycles, Atmel guarantee 20 years data retention. Beyond this, the data retention reduces. When 1.2m cycles are reached, and you see an error, this is an immediate error. at 1,230,160 cycles, there may not have been an immediate error, but the data might only have been retained for days.

Couple years ago I made run time logger for piece of equipment.  Memory got corrupted after 6 months 40 hours logged with 1s resolution => 144000 writes.
My solution was to spread writes over entire eeprom.

Can you provide more details about how you did this?

My 2ct: clear the memory (write all zeroes or 0xFF; something you can recognise). Then: every time you want to restore: find the first occurrence of the identifier, load from the address before it and save the new value to the spot you found. This way you move over the entire address space. Rise and repeat when you reach the end of the address space.


text:
Are there any good and maintained libraries for using DS2482 I2C to 1-Wire bridge?
The DS2482-100 and DS2482-800 are I2C to 1-Wire bridges which are useful for driving complex 1-Wire networks.
These are natively supported by a number of packages in Linux so you can interface easily with them on a Raspberry Pi.
I was surprised to find there is not an obvious library for accessing them on an Arduino however.
I have found the following:

An Arduino library - has some quirks and not-maintained.
Part of AVR-Liberty - less quirks, not sure if maintained, not "Arduino" as
such, more AVR.

It is helpful to be able to rely on maintained libraries to deal with any changes to the Arduino environment.
Arduino libraries are often easier to use than ones designed for AVR in general, which means more people are able to use the software.
Is there a better library available?

The only thing i know of is the wire library, but I2c to TWI. There are some teensy onewire libraries out there as well, but it looks like that is not what you are looking for. This may be a good time to start your own library :-)

An unmaintained library does not necessarily mean a bad library. If it is feature-complete and flawless, then it does not have to be maintained. Also, the fact that no commit occurs for a long time does not always mean that there's nobody to maintain it.

At least, with an open source library you can easily change the code yourself if it is buggy or does not fit your needs. The DS2482 datasheet can help for that.

No, unmaintained doesn't always mean bad, but when there are issues with it and it hasn't been updated for several years, it generally is bad.

@Cybergibbons have you tried it? Some issues may not be relevant to all library users. As far as I see, there's only one issue open on the mentioned Arduino library, and it is just one month old; I would not consider that unmaintained (yet).

Yes, it isn't very reliable - seems to miss readings periodically, and needed modifying to deal with that issue. Also not fully implemented feature set of DS2482.

The library didn't deal with parasitic power, hence the unreliability.

Used CyberGibbon's fork of library with fixes of Search bug, described above - it working fine for me. Thank you, both!

I use this library to communicate with the DS2482 but I can not subsequently communicate with a DS2401+ via 1-Wire. I use the I2C 1-Wire Click (DS2482-800) and on the 8 channels a DS2401+. https://www.mikroe.com/i2c-1-wire-click -> I2C 1-Wire Click (DS2482-800) https://pdfserv.maximintegrated.com/en/ds/DS2401.pdf -> DS2401+. Can you please explain me ? Thank you

I have implemented a library, based on the Paeaetech one linked to above, but tidying up defines, fixing the listed issue, adding lookup table based CRC and support for passively powered sensors.

I believe the library linked by Cybergibbons has a bug in
uint8_t OneWire::wireSearch(uint8_t *address)
A discrepancy at i = 0 (bit zero in this library, id_bit_number = 1 in a Maxim example) only follows the direction = 1 path and fails to find ROM addresses where bit zero = 0 (i.e. even family codes are missed when mixed devices, some with even and others with odd family codes, are present on the 1-wire bus).
A fix I have just implemented and appears to work is to modify the library to declare searchLastDiscrepancy and last_zero as int8_t (not uint8_t), initialise/reset them to -1 (not zero) and, near the end of the method
    if (!last_zero)
            searchLastDeviceFlag = 1;

becomes
    if (last_zero == -1)
            searchLastDeviceFlag = 1;

I hope that helps.


text:
Controlling mains (230 V) supply up to 5/10 amps using Arduino
I am looking for a simple, low cost solution to control on/off of mains supply to certain equipment. The control will be done using one of the output pin of Arduino Uno.
The input trigger and how to control it is application dependent.  e.g. controlling an equipment or controlling supply to section of home but in principle mains control module implementation remains same. So looking for solution which is safe while doing connections as well as while in use in  indoor conditions for years.

Your question brings up an important point: make sure you know what you're doing because anything that involves mains is potentially deadly. While you are specifically looking for something safe, you will likely have to tweak and debug it, which won't ever qualify as safe. If you're just trying to do something useful or didatic with your Arduino, please choose something else to play with. Prefer to power your stuff with a quality wall wart or ready-made power supply.

I don't mean to be rude, but your question seems to lack research. Have you google for a solution? Did you find anything similar to what you're looking for? If you found something but it doesn't quite serve your purpose, show us and tell us why. Share your research with us.

I second Ricardo's comment. Handling mains in any way can be extremely dangerous. Do not do so on your own just for the sake of experimentation or if you haven't handled mains before. The smallest mistake can result in major damage, in more ways than one.

Have you google for a solution?      OK I should have mentioned it in first place. The googled solutions where on the lines of http://playground.arduino.cc/uploads/Main/relays.pdf. Which I thought not safe while assembling as well as in use, as typically putting everything in box in home might not be temperproof.  So looking for solution which is actually takes care of issue pointed  by Ricordo and Asheesh.

The PowerSwitch Tail 2 is a great way for experimenters to control mains voltages. It is insulated and internally decoupled, so you only have to hook up 5v, gnd, and a signal line to control it.
This model supports only 120V, but there are also kits for 230V.

image from sparkfun

Safe but not cheap. But +1 for addressing safety over cost.

Note that this model supports only 120V (US) whereas the OP needs a solution for 230V. Might be good to look for an equivalent for European market.

Oh, right. EU version here

Thanks TheDoctor, I am looking for this kind of solution.

That link points to a page with US and EU kits

Playing with mains is dangerous - so best to use a kit designed for that purpose. Be careful with units designed in the US - their safety requirements are a bit different from UK and Europe.
For example the Power Switch Tail kits do not include a fuse - if the appliance being controlled goes faulty and starts drawing a bigger current, the switch could burn up.
Here is one designed with Uk safety features in mind:
http://www.sf-innovations.co.uk/mains-switch-widget.html


text:
How to power Arduino externally for long term?
For a robotic project, I need to keep an Arduino powered up for a long time in an outdoor environment. What can I use to power the board?
If battery is the only solution, can the device tell me remotely that battery is getting low?
It needs to be powered for at least few days ( at least). The unit monitors an outdoor sensor that is shaded from sun but still exposed to wind and moisture. The unit does not move.

This is very vague. How long do you need your system up? Are the circuits unprotected? Is it in a sunny environment (allowing for the possibility of a solar panel)? For the second part of the question: How far will the robot be? What communication interfaces do you have in mind? Do you have existing interfaces in your robot? Lastly, have you done any research starting from a basic Google search? The more detailed the question, the better the answers you will get.

Yes, this needs a lot more detail. Is it a mobile robot, static, how much power does it consume, what kind of voltage do the motors need, what kind of life do you need. Etc.

And robot definition is vague too... a robotic arm could be a robot.

Power requirements? 1W? 10W? Other than the Arduino and "sensor", do you have other components?

There are several options for Arduino power in an external environment.

Wall wart: Connects to a wall socket, provides a great long-term source of power
Rechargeable battery: Doesn't last long, but they can be recharged and monitored with a low cost board
Alkaline Battery: Last longer, there are some monitoring systems available.
Solar: Only works when the sun is out, unless you combine it with a rechargable battery (example)
Nuclear power: NOT RECOMMENDED!!!

Nuclear power is the best option. The OP should totally go nuclear.

Don't forget about hydrogen fuel cells, hydroelectric, or even wind energy.  Geothermal might be an option depending on what/where the device is. Gasoline engines/generators are an option as well.  Most renewable sources should be coupled with a battery to store excess energy when the source ceases for a time period.  (I'm being totally serious, with the possible exception of hydrogen fuel cells.)

Come one, go for the fusion power (The sun have been using it successfully for a long time now). I think that with fusion on a robot it will go near eternally.

@Faux_Clef - Fusion power is nuclear power.

@FakeName: yes, nuclear as in fusion of atomic nucleus into new elements ie. the sun. Nuclear power is also fission, the kind used in nuclear reactors/power stations.

@Faux_Clef - Fission and fusion are both types of nuclear power.

Depending on the project, an RTG might very well be a reasonable option; if you can get your hands on one.

Nuclear isn't really a joke - you could use a nuclear battery... http://en.wikipedia.org/wiki/Atomic_battery