2009-07-11 02:34:59 +02:00
|
|
|
/*
|
2017-07-12 22:18:23 +02:00
|
|
|
Switch statement with serial input
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-14 21:34:00 +02:00
|
|
|
Demonstrates the use of a switch statement. The switch statement allows you
|
|
|
|
to choose from among a set of discrete values of a variable. It's like a
|
|
|
|
series of if statements.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
To see this sketch in action, open the Serial monitor and send any character.
|
2017-07-14 21:34:00 +02:00
|
|
|
The characters a, b, c, d, and e, will turn on LEDs. Any other character will
|
|
|
|
turn the LEDs off.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
The circuit:
|
2017-07-12 22:18:23 +02:00
|
|
|
- five LEDs attached to digital pins 2 through 6 through 220 ohm resistors
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
created 1 Jul 2009
|
|
|
|
by Tom Igoe
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
This example code is in the public domain.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
http://www.arduino.cc/en/Tutorial/SwitchCase2
|
2017-07-15 00:35:58 +02:00
|
|
|
*/
|
2009-07-11 02:34:59 +02:00
|
|
|
|
|
|
|
void setup() {
|
|
|
|
// initialize serial communication:
|
2013-10-21 09:58:40 +02:00
|
|
|
Serial.begin(9600);
|
|
|
|
// initialize the LED pins:
|
|
|
|
for (int thisPin = 2; thisPin < 7; thisPin++) {
|
|
|
|
pinMode(thisPin, OUTPUT);
|
|
|
|
}
|
2009-07-11 02:34:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void loop() {
|
|
|
|
// read the sensor:
|
|
|
|
if (Serial.available() > 0) {
|
|
|
|
int inByte = Serial.read();
|
2013-10-21 09:58:40 +02:00
|
|
|
// do something different depending on the character received.
|
2017-07-14 21:34:00 +02:00
|
|
|
// The switch statement expects single number values for each case; in this
|
|
|
|
// example, 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:
|
2009-07-11 02:34:59 +02:00
|
|
|
|
|
|
|
switch (inByte) {
|
2013-10-21 09:58:40 +02:00
|
|
|
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;
|
|
|
|
default:
|
|
|
|
// turn all the LEDs off:
|
|
|
|
for (int thisPin = 2; thisPin < 7; thisPin++) {
|
|
|
|
digitalWrite(thisPin, LOW);
|
|
|
|
}
|
|
|
|
}
|
2009-07-11 02:34:59 +02:00
|
|
|
}
|
|
|
|
}
|