Sub topic 1
Three kinds of memory: flash, SRAM and EEPROM
The ATmega328P microcontroller on an Arduino Uno has three separate memories. Each has a different job and a different size.
Prerequisites
You should already be able to write and upload a basic sketch, use C/C++ variables and arrays, and open the Serial Monitor.
Three kinds of memory
- Flash holds your compiled program and any constants kept there. The Uno has 32 KB, and sketches can use 32,256 bytes. Flash keeps its contents without power.
- SRAM holds variables that change while the sketch runs. The Uno has 2 KB. SRAM is cleared when power is removed.
- EEPROM keeps small values across power cycles. The Uno has 1 KB. Writes are slow and wear the cells, so use it sparingly.
How a sketch uses SRAM
A sketch divides SRAM into three areas:
- Static data: global and
staticvariables, sized at compile time. - Heap: memory requested at run time with
malloc(),newor theStringclass. It grows upward. - Stack: local variables and function return addresses. It grows downward from the top of SRAM.
When the heap and stack meet, the sketch fails in unpredictable ways.
Reading the memory report after compiling
The IDE prints two lines after each compile:
Sketch uses 4102 bytes (12%) of program storage space. Maximum is 32256 bytes.
Global variables use 312 bytes (15%) of dynamic memory, leaving 1736 bytes for local variables. Maximum is 2048 bytes.The first line reports flash. The second reports SRAM used by globals and the space left for the heap and stack. A low global count does not prove the sketch is safe, because heap and stack use the remaining space at run time.
Choosing the smallest data type that fits
On AVR boards, int is 2 bytes, while long and float are 4 bytes. If a value stays between 0 and 255, uint8_t needs only one byte.
#include <stdint.h>
uint8_t percent = 0; // 1 byte, range 0 to 255
int16_t offset = -300; // 2 bytes, range -32768 to 32767
uint16_t adc = 0; // 2 bytes, range 0 to 65535Exercise
The global array uint16_t readings[200]; uses how many bytes of SRAM? How many bytes would uint8_t readings[200]; save?
Show answer
The array uses 400 bytes (200 × 2). Switching to uint8_t uses 200 bytes, saving 200 bytes, if every value fits from 0 to 255.