Sub topic 2
The microcontroller at the center
This chapter explains what the chip on the Uno actually is and what it contains. It assumes you know what voltage, current and resistance are, that you have uploaded a sketch from the Arduino IDE, and that you understand the setup()/loop() structure. It also assumes you can read a simple breadboard diagram.
What a microcontroller is
A microcontroller is a small computer on one chip. It combines a processor, program storage, working memory and input/output hardware. The Uno R3 is built around an ATmega328P, made by Microchip (formerly Atmel). Everything else on the board supports this chip. That support includes the regulators that give it clean 5V, the USB interface that talks to your computer, the clock source, the reset button and the pin headers that expose its pins.
The ATmega328P is not a desktop-style processor. It has no operating system, no file system and no way to load a second program. It runs one program, your sketch, starting at power-up or reset, and keeps running it until power is removed.
The key specifications
| Property | ATmega328P on the Uno R3 |
|---|---|
| Architecture | 8-bit AVR |
| Clock | 16 MHz |
| Flash (program storage) | 32 KB, of which 0.5 KB holds the bootloader |
| SRAM (variables) | 2 KB |
| EEPROM (saved data) | 1 KB |
| Operating voltage | 5V |
| Digital I/O | 14 pins (D0 to D13), 6 of them PWM-capable |
| Analog inputs | 6 (A0 to A5), 10-bit ADC |
"8-bit" means the processor works on one byte at a time. Larger values take several instructions. One consequence is that int is only 16 bits on the Uno, so it holds -32768 to 32767. A long is 32 bits. Boards with 32-bit processors use a 32-bit int, so arithmetic that works on those boards can overflow on the Uno.
The 16 MHz clock means 16 million cycles per second, or 62.5 ns per cycle. Most AVR instructions finish in one or two cycles, so the chip executes roughly 16 million simple instructions per second. A call to digitalWrite() still costs a few microseconds. The Arduino library looks up the pin, checks whether it has PWM running and only then changes the output.
Inside the chip
The chip combines a processor core, three kinds of memory and a set of peripherals. Peripherals are hardware blocks that do a job alongside the processor.
The peripherals matter because they do work without CPU time:
- GPIO ports drive pins HIGH or LOW and read their state. The Arduino numbering (D0 to D13, A0 to A5) is a layer on top of the chip's own port names such as PB5.
- Timers count clock cycles in hardware. Timer0 backs
millis()anddelay(). The timers also generate the PWM signals behindanalogWrite(). - The ADC (analog-to-digital converter) measures a voltage and returns a number from 0 to 1023.
- The USART, SPI and TWI blocks implement serial, SPI and I2C communication. Chapter 15 covers how they share pins with ordinary I/O.
Three memories with different jobs
The Uno has three memories, and mixing them up causes many confusing bugs.
- Flash holds your compiled sketch. It keeps its contents without power. It is written only when you upload, and it wears out after roughly 10,000 write cycles. Your sketch cannot treat it as normal variable storage.
- SRAM holds variables, the call stack and the heap while the sketch runs. It is fast and unlimited in rewrites, but it is erased when power is removed. At 2 KB it is the scarcest resource on the board.
- EEPROM keeps small amounts of data across power loss, such as a calibration value. It is rated for roughly 100,000 writes per cell.
The chip uses a Harvard architecture, which means code and data live in separate address spaces. A plain const char* string is copied from flash into SRAM at startup, so text you print can use up your working memory. The F() macro keeps a string literal in flash and reads it when needed.
After a successful compile, the IDE reports usage like this:
Sketch uses 1444 bytes (4%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.The flash maximum is 32256 bytes, not 32768, because the bootloader reserves 512 bytes. The second line covers only global variables. Local variables, function-call frames and any String objects that grow at runtime also need SRAM, so staying well under the limit matters.
Seeing the specifications from a sketch
This sketch checks the sizes described above on your own board. It prints type sizes, the EEPROM length and the compiled-in clock frequency.
#include <EEPROM.h>
void setup() {
Serial.begin(9600);
Serial.print(F("sizeof(int) = "));
Serial.println(sizeof(int));
Serial.print(F("sizeof(long) = "));
Serial.println(sizeof(long));
Serial.print(F("EEPROM bytes: "));
Serial.println(EEPROM.length());
Serial.print(F("F_CPU = "));
Serial.println(F_CPU);
}
void loop() {
// Nothing to repeat.
}On an Uno R3 the Serial Monitor at 9600 baud shows 2, 4, 1024 and 16000000. The F() macro keeps the labels out of SRAM. The empty loop() is required, because every sketch must define both functions.
The next sketch uses EEPROM to count how many times the board has started.
#include <EEPROM.h>
void setup() {
Serial.begin(9600);
uint8_t boots = EEPROM.read(0); // a fresh chip reads 255
boots++; // 255 wraps around to 0
EEPROM.update(0, boots); // writes only if the value changed
Serial.print(F("Boot count: "));
Serial.println(boots);
}
void loop() {
}The count survives power loss. Because a new chip's EEPROM is filled with 255, the first run prints 0 after the 8-bit wrap-around. EEPROM.update() skips the write when the stored byte already matches, which saves wear. Never call EEPROM.write() inside a fast loop(), because you can reach 100,000 writes within minutes.
What happens at reset
When power is applied or the reset pin is pulled low, the processor jumps to the start of the bootloader. The bootloader waits a moment for an upload from the computer. If none arrives, it hands control to your program. Arduino's startup code then initializes the timers and other hardware and sets up your global variables. The hidden main() function then calls setup() once and calls loop() repeatedly. A later chapter covers the upload step in detail.
Two consequences follow:
- A variable declared with an initial value is set again after every reset. Only EEPROM carries values across a restart.
- If
loop()ever returns without doing blocking work, it is called again immediately. Code that never waits runs as fast as the chip allows.
Failure modes and gotchas
- Running out of SRAM. The compiler checks static usage only. A sketch that compiles fine can still crash or behave oddly if the stack grows into the heap at runtime. Typical symptoms are random resets and garbled output. Reduce long strings, use
F(), avoid repeatedStringconcatenation and use the smallest data type that fits. - Integer overflow.
intwraps at 32767 on the Uno. For millisecond timing useunsigned long, as the return type ofmillis()does. - Expecting floating-point speed. The chip has no floating-point hardware, so
floatmath is done in software and is slow compared with integer math. - Assuming a bigger chip. Code that works on a 32-bit board with much more RAM can run out of memory or change behavior on the Uno.
Exercise
A sketch compiles and uploads, but it resets at random after you add many long Serial.println("...") messages. The IDE reports only 40% of flash used. What is the likely cause, and what is the fix?
Show answer
The string literals are copied into SRAM at startup, and the Uno has only 2 KB of it. Flash usage is not the limit here. Wrap each literal in F() so it stays in flash and is read from there when printed, then check the "Global variables" line of the compile output.
Exercise
You want to remember the last brightness setting after the board loses power. Which memory should you use, and how should you write it so you do not wear it out?
Show answer
Use EEPROM, because flash is not available to your running sketch and SRAM is erased on power loss. Call EEPROM.update() only when the user changes the setting, so unchanged values are never rewritten.
Exercise
A sketch computes int total = 20000 + 20000; and prints a negative number. Why does this happen on the Uno, and how do you fix it?
Show answer
An int on the Uno is 16 bits and holds at most 32767, so the sum overflows and wraps to a negative value. Declare total as long and write one operand as 20000L so the addition is done in 32 bits.