Lemoi
Lemoi

Reputation: 149

avr-gcc array with pointers to functions in program (flash) memory

How can I move an array with pointers to functions into flash? In normal RAM, the code looks something like:

MCU = ATMega628P, AVR-GCC 4.3.3 (WinAVR 20100110)

typedef void (*func_ptr_t)(void);

const func_ptr_t cli_func_list[] = {
        &funcA,
        &funcB
};

...
(*cli_func_list[j])(); // execute
...

I did try something like

const func_ptr_t cli_func_list[] PROGMEM = {
        &cmd_OT,
        &cmd_TT
};

but have no clue how to make this work. Any suggestions?

Upvotes: 2

Views: 1889

Answers (1)

emacs drives me nuts
emacs drives me nuts

Reputation: 3898

You got is almost right, but you have to use pgm_read_xxx from avr/pgmspace.h to read from flash. This applies to C++ and to avr-gcc older than v4.7:

#include <avr/pgmspace.h>

typedef void (*func_t)(void);

void funcA (void) {}
void funcB (void) {}

const func_t funcs[] PROGMEM =
{
    &funcA,
    &funcB
};

void call_func (int i)
{
    func_t fun = (func_t) pgm_read_word (&funcs[i]);
    fun();
}

With avr-gcc v4.7+, you can use the __flash qualifier, are type-save and no need for avr/pgmspace.h:

// With avr-gcc v4.7+
const __flash func_t funcs2[] =
{
    &funcA,
    &funcB
};

void call_func2 (int i)
{
    funcs2[i] ();
}

Upvotes: 0

Related Questions