Post topics, source code that relate to the Arduino Platform

User avatar
By cheungbx
#83465 I am trying to port games programmed in Arduino Pro Micro ATMega 32u4 for Arduboy to my game board built with ESP8266. I encountered an issue that some games using the function pointer to pass controls to different functions within the game based on a gameState byte variable, did not work.

e.g. ((FunctionPointer) pgm_read_word (&mainGameLoop[gameState]))();

I have to change that simple one line code to a switch statement which make the code more complex.
Any one with experience using function pointer in ESP8266 as state machine in the Arduino IDE? Any idea to make the function pointer work in ESP8266 ?

Here is the simplified code. The actual code is much more complex and a lot of repeated use of this statement.
((FunctionPointer) pgm_read_word (&mainGameLoop[gameState]))();



Code: Select all

typedef void (*FunctionPointer) ();



void   stateIntro () {
  Serial.println ("Intro");
}
void   stateMenu () {
  Serial.println ("Menu");
}
void   statePlay () {
  Serial.println( "Play");
}

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

void setup () {
  Serial.begin(74880);
  Serial.println ("game starated");
}


byte gameState = 0;

void loop() {
Serial.println (pgm_read_word (&mainGameLoop[gameState]));
Serial.print (gameState);
Serial.print ("   ");

// this is the original ATMega32U4 that doe snot work in ESP8266
 ((FunctionPointer) pgm_read_word (&mainGameLoop[gameState]))();

// I hve to replace with this complex switch statement.
  switch (gameState) {

    case 0:
      stateIntro();
      break;

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


  if (++ gameState > 2) gameState = 0;
 delay (1000);
}