Electronic – arduino – AVR program code location

arduinoatmegaavr-gccmicrocontrollernon-volatile-memory

I'm working with an ATmega328P and I wanted to interface with the flash memory writing data to it with the macros provided by avr-libc. This is the memory map for my chip:

ATmega memory map
(source: avr-tutorials.com)

I don't understand where the program code is exactly located when compiled. What I mean is: How can I be sure the address I use in boot_page_fill and boot_page_write is not used for the program code? Do I need to use the "–section-start" linker option to move the program code to a specific location and be sure the flash page I'm going to use doesn't overwrite that code?

NOTE: The data to write in the flash is unknown at compile time.

Best Answer

Unless you tune your linker, the program will always start at address 0 and grow up. Additionally, if you have a bootloader, it will start at one of predefined addresses (either 0xF80, 0xF00, 0E00 or 0xC00, see table 26-7 in datasheet), and usually go to the top of the memory.

When people use flash memory for data, they usually put it as high as they can. So:

(1) Determine the memory top -- this depends on bootloader that you have. If you have Optiboot, it usually takes 512 or 256 words: https://code.google.com/p/optiboot/wiki/HowOptibootWorks , so we will assume it starts at 0xE00.

(2) Determine how much data you need. Lets say you need 256 (0x100) bytes. This means you will place your datablock at 0xE00 - 0x100 = 0xD00. You can pass values between 0xD00 and 0xDFE to boot_page_* functions.

(3) Write your program.

(4) Check how much space it occupies. It can take up to (0xD00 - 1) = 3328 bytes. When I compile from command-line, I use 'avr-size' for that:

$ avr-size -C --mcu=atmega328 firmware.elf
AVR Memory Usage
----------------
Device: atmega328

Program:     904 bytes (2.8% Full)
(.text + .data + .bootloader)

Data:          2 bytes (0.1% Full)
(.data + .bss + .noinit)

Look at 'program' section -- only 904 bytes are used, plenty of space left. If you see a number of 3328 or more there, make your program shorter. Otherwise, the program will compile and upload, but it will crash randomly.