Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Power and Debugging

Debugging Sketches and Managing Memory

Find and fix Arduino bugs: a systematic method, serial and LED debugging, millis rollover, integer overflow, RAM, flash and EEPROM limits, F() and PROGMEM, and heap fragmentation.

Arduino bugs fall into two families. In the first, the program is wrong: a condition is inverted, a variable overflows, a pin number is mistyped. In the second, the hardware or the environment is wrong: a loose wire, a weak power supply, a floating input. Good debugging starts by working out which family you are in, then narrowing the problem down instead of guessing.

The Arduino IDE and boards cannot run on this site, so sketches are read-only. The C programs are labelled stand-ins that reproduce the numeric bugs (overflow, rollover) and a trace buffer exactly as an AVR with 16-bit int would see them, using fixed-size integer types.

A method that works

  1. Reproduce the problem reliably. If it happens "sometimes", find what changes.
  2. Divide and conquer. Remove parts until it works, or test each part alone (a sensor example sketch, a display example sketch).
  3. Check the basics: power, ground, wiring, correct board and port selected, correct pin numbers.
  4. Make one change at a time and test.
  5. Write down what you tried; the answer often appears when you do.

Also compile with warnings enabled (File, Preferences, Compiler warnings: All). The compiler catches assignments in conditions (if (x = 5)), missing returns and unused variables.

Debugging by output

The cheapest tools are the serial port and an LED.

C++
void setup() {
  Serial.begin(115200);
  Serial.println(F("boot"));
}

void loop() {
  int reading = analogRead(A0);
  Serial.print(F("reading="));
  Serial.println(reading);
  if (reading > 512) {
    Serial.println(F("branch: high"));
  }
  delay(200);
}

Print values and which code path ran. Use unique, searchable labels. For timing-critical code, printing itself changes the timing; set a pin high at the start of a function and low at the end instead, and watch it with a logic analyzer or an oscilloscope. If there is no serial port at all (a sleeping or standalone design), blink an LED a coded number of times for each state.

The Arduino IDE 2 has a debugger (breakpoints, stepping) for supported boards such as the ARM-based ones; classic AVR Unos usually do not support it without extra hardware, so prints remain the main tool.

Classic bugs

1. millis() rollover. millis() is an unsigned long (32 bits) counting milliseconds; it wraps to 0 after 4,294,967,295 ms, about 49.7 days. The safe pattern subtracts: if (millis() - last >= interval). Unsigned arithmetic wraps exactly as needed. The unsafe pattern, if (millis() >= last + interval), fails at the wrap.

2. Integer overflow. On AVR boards int is 16 bits (-32768 to 32767). int seconds = 60 * 1000; overflows. Use long (or unsigned long) and mark constants with L: 60L * 1000L.

3. Integer division. int average = total / count; truncates; float math needs a float operand.

4. Missing volatile on variables changed in an ISR.

5. = instead of ==.

6. Floating inputs. A pin with nothing connected reads random values; use INPUT_PULLUP or a pull-down resistor.

7. Array out of bounds. Writing data[10] in a 10-element array corrupts a neighboring variable; there is no error message.

C Stand-in: millis() rollover and unsigned subtraction (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The unsafe check is already broken in the first two rows: last + interval wraps around to 704, so it fires after only 200 ms. The safe check waits until a full second has really passed (at now=1100 the elapsed time is 1396 ms), even though the counter wrapped in between.

C Stand-in: 16-bit int overflow like an Uno (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Memory on an Uno

The ATmega328P has three memories:

Memory Size on Uno Holds
Flash 32 KB (about 0.5 KB used by the bootloader) your program and constants stored with PROGMEM
SRAM 2 KB global and local variables, stack, heap
EEPROM 1 KB data that survives power loss

The IDE reports flash and RAM use after compiling: "Global variables use 1,420 bytes (69%)". Above about 75 to 80 percent, trouble starts, because the stack (local variables and function calls) and the heap (malloc, and String objects) grow toward each other in the leftover space. When they collide the sketch behaves erratically or resets, with no error message.

Ways to save SRAM:

  • Wrap text in F(): Serial.println(F("Sensor error"));.
  • Store large constant tables in flash with PROGMEM and read them with pgm_read_byte() or pgm_read_word().
  • Use the smallest types: byte or uint8_t instead of int where it fits.
  • Avoid the String class in long-running sketches; it allocates on the heap and fragments it. Use char arrays and functions like snprintf.
  • Do not allocate big local arrays inside functions that are called deeply.
  • Reuse buffers.

You can measure free memory (the gap between heap and stack) with a small function:

C++
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}

Print it at startup and in suspicious places; if the number drops over time, you have a leak or fragmentation.

EEPROM stores settings across power cycles using the EEPROM library: EEPROM.update(address, value) writes only if the value changed, which matters because each cell survives about 100,000 writes. Never write to EEPROM in a fast loop.

C++
#include <EEPROM.h>

void setup() {
  byte lastMode = EEPROM.read(0);
  if (lastMode > 3) lastMode = 0;       // blank cells read 255
  // ... use lastMode ...
  EEPROM.update(0, lastMode);
}
void loop() { }

A trace buffer

When prints would disturb timing, record events in a small array in RAM and print them later. A ring buffer keeps the latest N entries, so after a crash or odd behavior you can see what happened just before.

C Stand-in: ring buffer trace log (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

When the hardware is the problem

Odd symptoms with correct code: random resets (power sag when a motor starts: see power supplies), garbled serial (baud rate), I2C devices not found (see the I2C lesson), uploads failing (wrong board or port, or pins 0 and 1 in use), readings that drift (floating inputs, noise, a weak reference). A multimeter solves many mysteries: check 5 V and ground where the part actually is.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which comparison survives millis() wrapping around after 49.7 days?

    Unsigned subtraction wraps the same way the counter does, so the elapsed time stays correct across the rollover.
  2. 2. What does int ms = 60 * 1000; produce on an Uno?

    An AVR int holds at most 32767, so the product overflows. Use 60L * 1000L with a long.
  3. 3. Why is heavy use of the String class risky on a 2 KB board?

    Repeated String allocation and concatenation fragments the tiny heap; use char arrays for long-running code.
  4. 4. Why prefer EEPROM.update() to EEPROM.write()?

    Each EEPROM cell survives roughly 100,000 writes; update() avoids needless writes.

Summary

  • Debug systematically: reproduce, isolate, change one thing at a time, and check power and wiring first.
  • Print values and code paths, use pin toggles or trace buffers when timing matters.
  • Watch for millis() rollover, 16-bit int overflow, integer division, missing volatile, floating inputs and out-of-range arrays.
  • Respect 2 KB of SRAM: use F() and PROGMEM, avoid String, and use EEPROM sparingly.

Next: Project: Traffic Light State Machine