Switch Case: How to use a word not just a single letter

Hi,

I'm following a beginner tutorial about "Switch Case" with this code:

if (Serial.available() > 0) {
char inByte = Serial.read();
// do something different depending on the character received.
// The switch statement expects single number values for each case;
// in this exmaple, though, you're using single quotes to tell
// the controller to get the ASCII value for the character. For
// example 'a' = 97, 'b' = 98, and so forth:

switch (inByte) {
case 'a':
digitalWrite(2, HIGH);
break;
case 'b':
digitalWrite(3, HIGH);
break;
case 'c':
digitalWrite(4, HIGH);
break;
case 'd':
digitalWrite(5, HIGH);
break;
case 'e':
digitalWrite(6, HIGH);
break;
case 'on':
for (int thisPin = 2; thisPin < 8; thisPin++) {
digitalWrite(thisPin, HIGH);
delay (100);
}
break;

What I don't understand is that on the video, when the guy enter the last paragraph of the code:
" case 'on': "
the character 'on' goes blue on the IDE, like it does with 'a' 'b' etccc
But on my IDE, it doesnt change the color to blue...
And then when I use the serial monitor to send 'on', it doesnt work....

Does it make sense ?

The guy is using the example named "switchcase2" , and simply changes "int inByte" by "char inByte" on lign 35 and then add a case with the ascii 'on'...

So why on my IDE, case 'on' doesnt get the color blue ^ ??

Thanks for your help

I am not clear what you are asking, but as inByte will only ever hold a single character it will never match 'on'

Thanks for quick reply.

Ok I thought "inByte" was just a custom name we gave to the variable (int or char in this case)

Yep my message was not very clear... I gonna try post printscreens :

On the video, as we can see 'on' in in blue

On my IDE, it is not:

On the video, his code is the same as mine, and he can send 'on' from the serial monitor and it is working:

here a better screenshot with all the code of the void loop from the video:

So you found an error in a video. Probably there are plenty of them.

A few things to note.
If you have more than one character it is no longer a char it is a string and needs to be in double quotes "on" instead of 'on'

Serial.read() only reads the first single byte. So in your case it would just return 'o' not 'on'

Switch statements work with primitive types and aren't suitable if you want to compare strings.

I would use a serial read method that fetches all the characters then use if else blocks instead of a switch.

That said one quick solution is to just substitute 'on' with a single character.

Well given the code in the image the case of int 'ON' can never be reached as the switch is based of a 'char' so case closed.

On the other hand you'll notice the case 'ON' is in single quotes meaning it's at lease a 2 byte integer.

Take a look at the following a see if you can understand what's going on!

const uint8_t   LED_OFF = LOW;
const uint8_t   LED_ON  = HIGH;


void loop()
{    }

void setup()
{
    uint32_t  value;

    value     = 'OFF';
    value     = 'ON';

    switch ( value )
    {
        case 'ON':    digitalWrite(13, LED_OFF);  break;
        case 'OFF':   digitalWrite(13, LED_ON);   break;
    }
}

Better yet compile it and test it!

Then the guy in the video doesn't know much about coding...

'on' will appear to work, but it won't work as expected: it will have the same effect as just 'n', because it will discard anything else than the last character inside the quotes.

'on' will just become 'o', as long as it is not used anywhere else, it should be fine.

KeithRB:
'on' will just become 'o', as long as it is not used anywhere else, it should be fine.

Well not quite, single quotes tell the compiler to treat it as, in this case, an uint16_t 2 byte integer.

As the value tested is a char, it will only compare the last character.

Pretty much what I indicated above.

'ON' is valid integer is all I'm saying, and WON'T match anything give the byte as the switch parameter!

lloyddean:
Well not quite, single quotes tell the compiler to treat it as and uint16_t 2 byte integer

True, I overlooked this fact when I stated that multiple characters must be in double quotes.

The blue appearance of the word 'on' means that somewhere it is defined as keyword which resolves to a case value accepted by switch.

That is not standard in the Arduino ide. My experience is like yours. The word is not in blue, and the switch case does not respond to "on" entered in the Serial Monitor.

Can you post the complete code and a link to the video?

I agree with @ whandall

So you found an error in a video. Probably there are plenty of them.

You can try this, but keep in mind it is not perfect.

(More traditional switch statement because it needs break to work properly, not anymore)

#define _switch(C) for(char dec=1, *condition=C; dec; dec--)
#define _case(str) if(!strcmp(str,condition))
#define _default(str) if(!strcmp(str,condition))

void setup() 
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  _switch("hello")
  {
    _case("test")
    {
      Serial.println(F("1"));
      break;
    }
    
    _case("hello")
    {
      Serial.println(F("Hello"));
      break;
    }
    
    _default("")break;
  }
  
}

void loop() {
  // put your main code here, to run repeatedly:

}

This one IMO works better. (no break needed)

#define _switch(C) if(char*condition = C)
#define _case(str) if(!strcmp(str,condition))
#define _default(str) else _case(str)

void setup() 
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  _switch("test")
  {
    _case("test")
    {
      Serial.println(F("1"));
    }
    
    _case("hello")
    {
      Serial.println(F("Hello"));
    }
    
    _default("")
    {
       Serial.println(F("Default"));
    }
  }
  
}

void loop() {
  // put your main code here, to run repeatedly:

}

You could also build a table of acceptable commands, along with a corresponding constant, then have a function that returns the constant for any command parsed. Then, you can use the constant in a switch statement.

const byte COMMAND_UNKNOWN = 0;
const byte COMMAND_ON = 1;
const byte COMMAND_OFF = 2;
const byte COMMAND_STOP = 3;

int getCommandValue(char *command)
{
    typedef struct 
    {
        char* command;
        int value;
    } _command;
    
    static _command commands[3] = 
    {
        {"on", COMMAND_ON},
        {"off", COMMAND_OFF},
        {"start", COMMAND_START}
    };
    
    for (int i=0; i < sizeof(commands)/sizeof(command); i++)
    {
        if (strcmp(commands[i].command, command) == 0)
        {
            return commands[i].value;
        }
    }
    return COMMAND_UNKNOWN;
}

void loop()
{
    char command[] = "on";

    switch (getCommandValue(command))
    {
        case COMMAND_ON:
            break;
        default:
            break;
    }
}

Also see this thread:

http://forum.arduino.cc/index.php?topic=378836.0

Waouu !! :slight_smile: Thank you for all those replies.. for a first time coming here on this forum, it feels pretty great.

So from your replies, what I understand it's that with the variable char , it should be impossible to use a two characters command.

That the serial port and so the serial.read will just look at the last character so the n on that case

But it doesnt explain why it is working on the video and why it changes to blue on his IDE as soon as he types the word 'on' ( And he is not using a single keystroke that would be 'on' on his keyboard ??? he is writing the letter o then the letter n )

So as cattledog says, it must be that "means that somewhere it is defined as keyword which resolves to a case value accepted by switch. "

So as demanded here a link to the video (I just shared it on Hubic):

http://ovh.to/1As8Wmg

its happen at 2min20 on the video.

The code he uses is the code "Switchcase2" from the Arduino IDE examples:

http://s7.postimg.org/ygc03a5uz/Screen_Shot_2016_02_14_at_9_43_08_AM.png

jopoulos:
Waouu !! :slight_smile: Thank you for all those replies.. for a first time coming here on this forum, it feels pretty great.

So from your replies, what I understand it's that with the variable char , it should be impossible to use a two characters command.

That the serial port and so the serial.read will just look at the last character so the n on that case

But it doesnt explain why it is working on the video and why it changes to blue on his IDE as soon as he types the word 'on' ( And he is not using a single keystroke that would be 'on' on his keyboard ??? he is writing the letter o then the letter n )

So as cattledog says, it must be that "means that somewhere it is defined as keyword which resolves to a case value accepted by switch. "

So as demanded here a link to the video (I just shared it on Hubic):

http://ovh.to/1As8Wmg

its happen at 2min20 on the video.

The code he uses is the code "Switchcase2" from the Arduino IDE examples:

http://s7.postimg.org/ygc03a5uz/Screen_Shot_2016_02_14_at_9_43_08_AM.png

Yeah, he doesn't know what he's doing.

Here's an example compiled on an online compiler:

#include <iostream>

using namespace std;

int main()
{
   cout << "Hello World" << endl; 
   
   char t = 'on';
   
   cout << t << endl;
   
   return 0;
}

and here's the output from compile and run:

sh-4.3$ g++ -std=c++11 -o main *.cpp                                                                                                                 
main.cpp:9:13: warning: multi-character character constant [-Wmultichar]                                                                             
    char t = 'on';                                                                                                                                   
             ^                                                                                                                                       
main.cpp: In function 'int main()':                                                                                                                  
main.cpp:9:13: warning: overflow in implicit constant conversion [-Woverflow]                                                                        
sh-4.3$ main                                                                                                                                         
Hello World                                                                                                                                          
n                                                                                                                                                    
sh-4.3$

So, it gives an overflow warning, and interprets it is the character 'n'.

Thanks arduinodlb

Though i dont really understand your example compile and output as im a total beginner in Arduino (just 2 days i know it)

Also, i just want to understand how come it turns to blue when he types 'on' and also that its actually working when he does it....