Is there an alternative to 38 Switch-case statements?

Hi all,

I'm using a rotary encoder and assigning values to each encoder position up to 38. Each case assigns two variable values, one int and one string.

Are there a more memory friendly method? This one takes around 5K.

Thanks

switch(encoderPos){
      case 0:
        trigval = 0;
        trigdisp = ("0");        
      case 1:
        trigval = 250;
        trigdisp = ("1/4000");
        break;
      case 2:
        trigval = 313;
        trigdisp = ("1/3200");
        break;
...
      case 37:
        trigval = 10000000;
        trigdisp = ("10");
        break;
      case 38:
        trigval = 30000000;
        trigdisp = ("30");
        break;

Lookup table(s)? (though that's probably what the compiler makes the switch statement into)

I know this isn't related to your question, but did you mean to miss a "break;" on case 0?

Good eye James.

Thanks AWOL.

Would this help any, or does use of sprintf make it worse?

const unsigned long times[] = {4000,3200,1600,1000,500,250,125,60,30,15,8,4,2,1,10,30};
char trigdisp[8];

if(encodepos==0)
  {
  trigval=0;
  sprintf(trigdisp,"%d",0);
  }
else if(encoderpos<13)
  {
  trigval=1000000UL/times[encoderpos-1];
  sprintf(trigdisp,"1/%d",times[encoderpos-1]);
  }
else
  {
  trigval=1000000UL*times[encoderpos-1];
  sprintf(trigdisp,"%d",times[encoderpos-1]);
  }

I have fewer shutter speeds (assuming that’s what they are) than you of course.
Not tested, not even compiled.

Use an array of structures to hold the data which are then easily accessed directly through an array reference. It gets rid of the switch or if statements entirely.

struct triggers {
	long trigval;
	char *trigdisp;
} trigger_tab[5] = {
	0, "0",
	250,"1/4000",
	313,"1/3200",
	// ...
	10000000L,"10",
	30000000L,"30"
};

void setup(void)
{
  Serial.begin(9600);
  for(int i=0;i<5;i++) {
    Serial.print(trigger_tab[i].trigval);
    Serial.print(" ");
    Serial.println(trigger_tab[i].trigdisp);
  }
  
}

void loop(void)
{
}

Just fill in all the other values and change [5] to [39]
This particular code is 2476 bytes.
Pete

Have you looked at PROGMEM?
http://www.arduino.cc/playground/Main/PROGMEM

A simple table lookup with the table in flash could be your best bet.

RandallR: Have you looked at PROGMEM? A simple table lookup with the table in flash could be your best bet.

Code is stored in progmem...

The select-case statements are code for a type of look-up table...

So isn't a lookup table in flash what the original code already accomplishes?