6.27.2013

Convert IF to CASE statements

The results bellow, from IF:
/*IDLE RUN STATE*/  
void idleRunUpdate(){
  //Conditions for transition to a Line Avoid State
  if((sensorSum>=16 && sensorSum<=63)||(sensorSum>=80 && sensorSum<=127)||(sensorSum>=208 && sensorSum<=255)){
    stateMachine.transitionTo(lineAvoidState);
  }
  //Conditions for transition to a Attack State
  if(sensorSum==2||sensorSum==4||sensorSum==6||sensorSum==7||sensorSum==14){
    stateMachine.transitionTo(attackState);
  }
  //Conditions for transition to a Spin State
  if(sensorSum==1||sensorSum==3||sensorSum==8||sensorSum==12){
    stateMachine.transitionTo(spinState); 
  }
  //Conditions for transition to a Overfall Avoid State
  if((sensorSum>=64 && sensorSum<=79)||(sensorSum>=128 && sensorSum<=143)||(sensorSum>=192 && sensorSum<=207)){
    stateMachine.transitionTo(overfallAvoidState);
  }
}

to CASE statements:
/*IDLE RUN STATE*/  
void idleRunUpdate(){
//  Serial.println("idleRunUpdate");
  switch(sensorSum){
    //Conditions for transition to a Line Avoid State
    case 16 ... 63:
    case 80 ... 127:
    case 208 ... 255:
      stateMachine.transitionTo(lineAvoidState);
      break;
    //Conditions for transition to a Attack State
    case 2:
    case 4:
    case 6:
    case 7:
    case 14:
      stateMachine.transitionTo(attackState);
      break;
    //Conditions for transition to a Spin State
    case 1:
    case 3:
    case 8:
    case 12:
      stateMachine.transitionTo(spinState);
      break;
    //Conditions for transition to a Overfall Avoid State
    case 64 ... 79:
    case 128 ... 143:
    case 192 ... 207:
      stateMachine.transitionTo(overfallAvoidState);
      break;
  }
}
The result has saved 12 bytes of memory

No comments:

Post a Comment