4 Flash Variables
The C language was not designed for processors with separate memory spaces. This means that there are various non-standard ways to define a variable whose data resides in the Program Memory (Flash).
AVR GCC uses Variable Attributes to declare a variable in Program Memory:
int mydata[] __attribute__((__progmem__))
AVR-Libc also provides a convenient macro for the Variable Attribute:
#include <avr/pgmspace.h>
int mydata[] PROGMEM = ...
IAR uses a non-standard keyword to declare a variable in Program Memory:
__flash int mydata[] = ...
There is also a way to create a method to define variables in Program Memory that is common between the two compilers (AVR GCC and IAR). Create a header file that has these definitions:
#if (defined __GNUC__)
#define FLASH_DECLARE(x) x __attribute__((__progmem__))
#elif (defined __ICCAVR__)
#define FLASH_DECLARE(x) __flash x
#endif
This code snippet checks if GCC or IAR is the compiler being used and defines a macro FLASH_DECLARE(x) that will declare a variable in Program Memory using the appropriate method based on the compiler that is being used. Then you would use it as follows:
FLASH_DECLARE(int mydata[] = ...);
In AVR GCC, to read back flash data, use the pgm_read_∗() macros defined in <avr/pgmspace.h >. All Program Memory handling macros are defined there.
In IAR, flash variables can be read directly because the IAR compiler will generate LPM instruction automatically.
There is also a way to create a method to read variables in Program Memory that is common between the two compilers (AVR GCC and IAR). Create a header file that has these definitions:
#if (defined __GNUC__)
#define PROGMEM_READ_BYTE(x) pgm_read_byte(x)
#define PROGMEM_READ_WORD(x) pgm_read_word(x)
#elif (defined __ICCAVR__)
#define PROGMEM_READ_BYTE(x) *(x)
#define PROGMEM_READ_WORD(x) *(x)
#endif