Arduino Switch Case Example


I wanted to share something before I get into the example…

if (you.likeMovies && you.areInterestedInMormons) {

you.should.watch('http://www.hulu.com/watch/543302');

} else if (you.areInterestedInMormons) {

you.should.read('http://www.mormon.org');

}

Now, on to the example –

I wrote a program a little while ago that translated (hard-coded) messages into light emissions on the Arduino. The program iterates through each character in the message and uses a switch case statement to determine how many times the light should blink (or pause) for that character. I thought I’d share the relevant code as a switch case example (full code on github).

Specifically, this is a switch case statement that is testing a char. I had to use char instead of string because I wanted to iterate through each letter of the message. That was possible with C-style chars but not with Arduino-style strings.

// I normalized the characters coming in because I didn't want to
// test for 'a' and 'A'

char characterLwr = tolower(character);

// characterLwr is the variable that will be tested in the cases
switch(characterLwr) {

case ‘a’:

// the psignal[0], etc. is a pointer to an array I created earlier. But that’s not important.

// This is what happens if characterLwr == ‘a’
psignal[0] = dot;
psignal[1] = dash;

// After the block is done running, it is important to break out of the loop.
// Otherwise, the case will continue evaluating against the other cases.
// I guess you might want that, but you probably don’t.
break;

case ‘b’:

// this is what happens if characterLwr == ‘b’
psignal[0] = dash;
psignal[1] = dot;
psignal[2] = dot;
psignal[3] = dot;
break;

case ‘c’:

// this is what happens if characterLwr == ‘c’
psignal[0] = dash;
psignal[1] = dot;
psignal[2] = dash;
psignal[3] = dot;
break;

default:

// defaults are optional; the code in the default block is run if the variable
// being evaluated doesn’t meet any of the cases


Leave a Reply

Your email address will not be published. Required fields are marked *