if statement... How many levels?? any other options?

02 Jul 2012

Does anyone know a simple solution for an issue I'm having regarding the number of levels you can have in an if statement??

I'm trying to receive a serial string, and do something based on the command received... And I want to have several commands.... I've seemed to run into a limit of levels that I can have...at around 14 or 15...

My code goes a little something like this...

    if (device.readable()) {
        device.scanf("%s", &string);
        if (!strcmp(string, "led1")) {
            led1 = !led1;
        } else if (!strcmp(string, "led2")) {
            led2 = !led2;
        } else if (!strcmp(string, "led3")) {
            led3 = !led3;
        } else if (!strcmp(string, "led4")) {
            led4 = !led4;

etc...etc....

I've tried figuring out how to use a switch statement, but get tripped up on the strcmp part... I'd love to have 30 or 40 commands and if anyone has any suggestions I'd be very happy to hear them!!

Thanks!!

02 Jul 2012

If all your commands have format of led<N>, then you can use sscanf to parse them:

char cmd[20];
int no;
// read 3 characters into 'cmd' and then an integer into 'no'
if ( sscanf(string, "%3c%d", cmd, &no) == 2 )
{
  if ( cmd[0] == 'l' && cmd[1] == 'e' && cmd[2] == 'd' )
  {
    // this is a "led" command
  }
}

sscanf can be somewhat tricky to use so I'd recommend making a test program on PC to try out various inputs before doing it on mbed.

02 Jul 2012

Update: I found an example on the web... http://www.cplusplus.com/forum/beginner/6526/ But I'm either not implementing it properly, or something....

void recvCMD() {
    if (device.readable()) {
        device.scanf("%s", &string);
    const char *options[]={
        "led1",
        "led2",
        "led3",
        "led4",
        "ledAll",
        0
    };
    long option=-1;
        for (long a=0; options[a] && option<0; a++)
        if (!strcmp(string,options[a])) {
                option=a;
            switch (option) {
                case 0:
                    led1 = !led1;
                case 1:
                    led2 = !led2;
                default:
                    pc.printf("NULL Command.");
            }
        }
    }
}

I get random results... I type led1 and both leds toggle, I type led2 and only led2 toggles... I'm obviously not too great at this yet... =/ Any help would be really appreciated!!!!

02 Jul 2012

You forgot break statements after each case.

02 Jul 2012

Thanks Igor... You're absolutely right... I got it working and was just gonna post that I forgot those... LOL.. This works great btw, for anyone who needs something like this!!!