Questionsfunction pointer as statemachine for ESP8266 does not work in Adruino IDE
cheungbx Staff asked 5 years ago

I have been porting games written for the Arduboy (Atmega 32U4 devices with OLED) over to a game board i designed with ESP8266 (Node MCI D1 mini).

I came across several games recently that used the function pointer a state machines to pass control to different functions in the game as the game progresses to the different stage. an array of function pointer was used to store the starting program memory addresses of each function indexed by a gamestate variable that starts from 0.

See the codes as follows.

const FunctionPointer PROGMEM mainGameLoop[] = {
stateIntro, // 0
stateMenu, // 1
statePlay, // 2
};

 

((FunctionPointer) pgm_read_word (&mainGameLoop[gameState]))();

 

When I run it and turn on the serial monitor to observe, I found that this line failed to pass control to the right function, instead the program derailed and the ESP8266 rebooted itself.

I ended up replacing the above statement with a switch statement to call up each function.

switch (gameState) {

case 0:
stateIntro();
break;

case 1:
stateMenu();
break;
case 2:
statePlay();
break;
}

 

But that make the code clumsy, and I have ten or more such function pointer statements in the program. Anyone has an experience on how to write proper codes using the function pointer in ESP8266 in the Arduino IDE environment that will work ?