User Tools

Site Tools


workaround_for_-1_case

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

workaround_for_-1_case [2019/04/08 20:11] (current)
Line 1: Line 1:
 +Using -1 as one of the case values for a switch statement doesn'​t compile as expected on the EDK because the compiler appears to be using an unsigned type for the declaration of the enum variable. Still, it can be useful to use a special value such as -1 to represent the idea that the state machine is being reset. I have a suggested usage strategy below. To summarize, the tick method checks to see if the incoming state value is -1. If it is, it assumes that the state machine is being "​reset"​ and returns the next state value to be the initial state. The tick method will also execute the state action for the initial state as expected because the state-action switch is outside of the if-then-else.
 +
 +
 +<​code>​
 +
 +
 +unsigned short Go = 0;
 +unsigned short SepTime = 0;
 +
 +enum UB_states {UB_init, UB_WaitA0, UB_WaitSepTime};​
 +int UB_tick(int state) {
 +  static unsigned char cnt;
 +  if (state == -1) {
 +    state = UB_init;
 +  } else {
 +    // State Transition.
 +    switch(state) {
 +    case UB_init:
 +      state = UB_WaitA0;
 +      break;
 +    case UB_WaitA0:
 +      if (A0) {
 + state = UB_WaitSepTime;​
 + B++;
 + cnt = 0;
 + Go = 1;
 +      }
 +      break;
 +    case UB_WaitSepTime:​
 +      if (!A0) {
 + state = UB_WaitA0;
 +      } else if (A0 && (cnt*100 < SepTime)) {
 + cnt = 0;
 +      } else {
 + B++;
 + cnt = 0;
 +      }
 +      break;
 +    default:
 +      break;
 +    }
 +  }
 +  // State Action.
 +  switch(state) {
 +  case UB_init:
 +    B = 0;
 +    break;
 +  case UB_WaitA0:
 +    Go = 0;
 +    break;
 +  case UB_WaitSepTime:​
 +    break;
 +  default:
 +    break;
 +  }
 +  return state;
 +}
 +
 +enum CST_states {CST_Wait, CST_s1};
 +int CST_tick(int state) {
 +  static const unsigned char numSepTimes = 5;
 +  static const unsigned short sepTimes[5] = {1000, 1000, 700, 400, 100};
 +  static unsigned char i;
 +  if (state == -1) {
 +    state = CST_Wait;
 +  } else {
 +    // State transition.
 +    switch(state) {
 +    case CST_Wait:
 +      if (Go) {
 + i = 1;
 + state = CST_s1;
 +      }
 +      break;
 +    case CST_s1:
 +      if (!Go) {
 + state = CST_Wait;
 +      } else if (Go && (i < numSepTimes)) {
 + SepTime = sepTimes[i];​
 + i++;
 +      }      ​
 +      break;
 +    }
 +  }
 +  // State action.
 +  switch(state) {
 +  case CST_Wait:
 +    SepTime = sepTimes[0];​
 +    break;
 +  case CST_s1:
 +    break;
 +  }
 +  return state;
 +}
 +
 +</​code>​
  
workaround_for_-1_case.txt ยท Last modified: 2019/04/08 20:11 (external edit)