[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[avr-gcc-list] an example using constants in program memory

From: gouy yann
Subject: [avr-gcc-list] an example using constants in program memory
Date: Sun, 7 Nov 2004 12:20:58 +0100 (CET)


Since using constants in program memory is one of the
topics that is recurrent
since I recently struggle with this problem,
here comes an example based on my code.

The code was to make a some command interpreter.
So what I wanted to do was to compare a string read
from the USART with the strings in a table.
Upon a match, a function was to be called.

void fct0(void)
// do whatever you want

void fct1(void)
// once again you're free to do what you want

// function pointer prototype
typedef void (*fct_format_t)(void);

// the table element prototype
typedef struct {
        const u8* name;
        fct_format_t fct;
} func_map_t;

// function name strings
static u8 fct0_name[] PROGMEM = "fct0";
static u8 fct1_name[] PROGMEM = "fct1";

// table
static const func_map_t func_table[] PROGMEM = {
        { fct0_name,    fct0 },
        { fct1_name,    fct1 }

// the parse function
// str is the string to be compared
// against the table entries
void parse(u8* str)
        fct_format_t fct = NULL;
        u8 i;
        PGM_P name;

        // compare found command against available commands
        for ( i = 0; i < sizeof(func_table) /
sizeof(func_map_t); i++) {
                // retrieve command name from table
                name = (PGM_P)pgm_read_word(&(func_table[i].name));
                // compare with typed command
                if ( strncasecmp_P(str, name, 4) == 0 ) {
                        // found!
                        // retrieve function pointer
                        fct = (fct_format_t)

        // call command
        if ( fct != NULL) {

Sorry if some lines aren't quite easy to read in the
80 column format.

The principle is to read the function name from
program memory and, on a fit, to read the function
pointer from program memory (be aware that the
function pointer value is in words not in bytes, hence
its value is the half of the function address given in
the mapping).

Thanks to the fact both fields in the table are
pointers, pgm_read_word() is used.
If longer information should be retrieved, a function
similar to memcpy_P() should be used.

I hope this could help someone.

If it is of interest to put it in the FAQ of avr-libc,
fell free to do it, just put my name somewhere.




Vous manquez d’espace pour stocker vos mails ? 
Yahoo! Mail vous offre GRATUITEMENT 100 Mo !
Créez votre Yahoo! Mail sur http://fr.benefits.yahoo.com/

Le nouveau Yahoo! Messenger est arrivé ! Découvrez toutes les nouveautés pour 
dialoguer instantanément avec vos amis. A télécharger gratuitement sur 

reply via email to

[Prev in Thread] Current Thread [Next in Thread]