1

I am trying to read a function pointer from a structure stored in PROGMEM, then passing a value (input) to the corresponding function and save the returned value, but i can not find the correct syntax.

uint8_t (*pStateFunc) (uint8_t);
uint8_t input; 
uint8_t nextstate;

enum MENUSTATES {STATE1, STATE2};

typedef struct PROGMEM {
  unsigned char state;
  uint16_t someNumber;   // Just arbitrary information
  uint8_t (*pFunc) (uint8_t input);
} MENU_STATE;

const MENU_STATE menu_state[] PROGMEM = {
  //  state  someNumber  pFunc
  {STATE1,   2,          NULL}, 
  {STATE2,   4,          doSomething},
  {0,        0,          NULL}
  };


// Get the Function 
pStateFunc = (PGM_VOID_P) pgm_read_byte(&menu_state[1].pFunc); 

// Execute the Function and save the returned state
nextstate = pStateFunc(input);

// Function Definition
uint8_t doSomething(u8int_t input){
    return STATE1;
}

All i get is the following error from the Arduino IDE 1.6.5:

invalid conversion from 'const void*' to 'uint8_t (*)(uint8_t) {aka unsigned char (*)(unsigned char)}' [-fpermissive]

How can i read the function from PROGMEM and execute it correctly?

  • What is this `pStateFunc = (PGM_VOID_P) pgm_read_byte(&menu_state[1].pFunc);` supposed to do? – alk Jan 03 '16 at 13:49
  • The initialiser to `menu_state[]` seems to be missing a closing brace (`}`). – alk Jan 03 '16 at 13:50
  • It should read the `doSomething` Pointer from the `menu_state`struct progmem. I added the missing closing brace... sorry forgot that before. – Catherine Deringer Jan 03 '16 at 13:51

1 Answers1

1

You seem to be reading one byte - I would have thought pgm_read_ptr would be more appropriate. And you need to cast it to the right type:

typedef uint8_t (*StateFunc) (uint8_t);
pStateFunc = (StateFunc) pgm_read_ptr(&menu_state[1].pFunc); 
Alan Stokes
  • 18,815
  • 3
  • 45
  • 64