Go Down

Topic: Take action based on string (Read 497 times) previous topic - next topic

trialex

Looking for some help, but don't really know what it's called, so not sure how to search for it!

OK so I get sent a string, say "ABCFL"

For each item in the string, I want to take a unique action. For each possible string value, I've got a function that changes the state of a number of digital pins.

Is there anyway to call a function based on a character without looking through every possible value using if & ifelse statements?

Is there a way to like, put multiple commands into an array? Like could I somehow put
Code: [Select]
digitalWrite(13,HIGH);
digitalWrite(12,HIGH);
delay(100);
digitalWrite(13,LOW);
digitalWrite(12,LOW);


into an array at position 48, so that if the character in the position of the string I am looking at was "0", I could use 0 as a value to look up the sequence in the array, it would perform that sequence of lines?

Obviously I can write a function that wraps those lines up into a small function.

The only way I can think to do it is to write a big, long in-elligant function that says
Code: [Select]

if(string_value=='0'){
zero();
elseif(string_value=='A'){
a();
elseif(string_value=='B'){
b();
...



I'm obviously no programmer, and this is badly explained, so thanks for your help.

Alex




mike_pa

Hi,
here is a short exampe:

Code: [Select]

// array of pointer to function
void (*funcArr[3])() = {NULL};

void setup()
{
 // fill array with function pointers
  funcArr[0] = &a;
  funcArr[1] = &b;
  funcArr[2] = &c;
 
}

void loop()
{
 // this string contains the characters
 char string_value[10];
 ...
 // scan all characters in the string
 // call a() for 'a', b() for 'b' and so on
 for (int i=0; i<10; i++) {
   int index = string_value[i]-'a';
   // only 'a'..'c' is allowed
   if (index > 0 && index < 3)
     (*funcArr[index])();
 }
}

// here are the functions to call
void a()
{
}

void b()
{
}

void c()
{
}



Mike

trialex

Awesome!

Thanks heaps - will try to digest now...

Go Up