| 1 |
/* |
| 2 |
Switch statement with serial input |
| 3 |
|
| 4 |
Demonstrates the use of a switch statement. The switch statement allows you |
| 5 |
to choose from among a set of discrete values of a variable. It's like a |
| 6 |
series of if statements. |
| 7 |
|
| 8 |
To see this sketch in action, open the Serial monitor and send any character. |
| 9 |
The characters a, b, c, d, and e, will turn on LEDs. Any other character will |
| 10 |
turn the LEDs off. |
| 11 |
|
| 12 |
The circuit: |
| 13 |
- five LEDs attached to digital pins 2 through 6 through 220 ohm resistors |
| 14 |
|
| 15 |
created 1 Jul 2009 |
| 16 |
by Tom Igoe |
| 17 |
|
| 18 |
This example code is in the public domain. |
| 19 |
|
| 20 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/SwitchCase2 |
| 21 |
*/ |
| 22 |
|
| 23 |
void setup() { |
| 24 |
// initialize serial communication: |
| 25 |
Serial.begin(9600); |
| 26 |
// initialize the LED pins: |
| 27 |
for (int thisPin = 2; thisPin < 7; thisPin++) { |
| 28 |
pinMode(thisPin, OUTPUT); |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
void loop() { |
| 33 |
// read the sensor: |
| 34 |
if (Serial.available() > 0) { |
| 35 |
int inByte = Serial.read(); |
| 36 |
// do something different depending on the character received. |
| 37 |
// The switch statement expects single number values for each case; in this |
| 38 |
// example, though, you're using single quotes to tell the controller to get |
| 39 |
// the ASCII value for the character. For example 'a' = 97, 'b' = 98, |
| 40 |
// and so forth: |
| 41 |
|
| 42 |
switch (inByte) { |
| 43 |
case 'a': |
| 44 |
digitalWrite(2, HIGH); |
| 45 |
break; |
| 46 |
case 'b': |
| 47 |
digitalWrite(3, HIGH); |
| 48 |
break; |
| 49 |
case 'c': |
| 50 |
digitalWrite(4, HIGH); |
| 51 |
break; |
| 52 |
case 'd': |
| 53 |
digitalWrite(5, HIGH); |
| 54 |
break; |
| 55 |
case 'e': |
| 56 |
digitalWrite(6, HIGH); |
| 57 |
break; |
| 58 |
default: |
| 59 |
// turn all the LEDs off: |
| 60 |
for (int thisPin = 2; thisPin < 7; thisPin++) { |
| 61 |
digitalWrite(thisPin, LOW); |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
} |