## **Switch和Case條件語句2**
If語句允許你根據條件的真假(真(TRUE)或假(FALSE))進行兩個分支操作。當需要進行多個判斷時,你就必須使用If嵌套。不過其實還有一種更為簡潔的處理多條件判斷的方法,那就是使用switch語句,switch語句允許你一次對多種情況進行區分。本例向你展示如何使用switch語句來根據串口收到的命令打開、關閉指定的LED。命令是一系列字符:a、b、c、d、e,分別對應5個LED。
### **所需硬件**
* Arduino或Genuino板
* 5個LED
* 5個220Ω電阻
* 跳線
* 面包板
* 連接線
### **電路**
?
5個LED分別串接一個220Ω電阻并且分別連接到**2**、**3**、**4**、**5**、**6**引腳。板子應該與電腦,并且確保Arduino 串口監視器已經打開。你可以發送**a**、**b**、**c**、**d**、**e**來點亮指定LED,發送其他任意字符關閉所有LED。
### **原理圖**

### **代碼**
~~~
/*
Switch和Case條件語句2
展示switch語句的使用,switch語句讓你能夠一次對變量的多個可能值進行分支處理,這和使用一系列if語句嵌套的功效相同。但使用switch將使代碼更加簡潔。
為了看到效果,請打開串口監視器。發送a b c d e中的任意一個字符可以打開指定LED。發送其他字符關閉所有LED。
電路搭建:
* 5個LED串接220Ω電阻連接到2-6引腳
代碼公開
*/
void setup() {
// 初始化串口通信:
Serial.begin(9600);
// 初始化LED引腳:
for (int thisPin = 2; thisPin < 7; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// 讀取傳感器:
if (Serial.available() > 0) {
int inByte = Serial.read();
// 根據收到的字符進行不同處理:
// case后應緊跟符合的條件(某個字符)
// 下面代碼使用了單引號來告訴單片機:給我ASCII值,比如
// 'a' = 97, 'b' = 98 以此類推
switch (inByte) {
case 'a':
digitalWrite(2, HIGH);
//譯者注:這個break很重要。如果不加,那么程序就會在執行這個case之后一路執行下去。例如:如果這里不加break而inByte又是‘a’,則b也會被執行。由于b后面有break,所以switch case就結束了。如果b也沒有。那么程序就會 a->b->c 以此類推。所以一般case最后都要有break。讀者可以全部不加break,然后在每一個case中輸出調試信息來親身體會。
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:
// 將所有LED關閉:
//如果所有的case都沒有匹配上,default后面就會被執行
for (int thisPin = 2; thisPin < 7; thisPin++) {
digitalWrite(thisPin, LOW);
}
}
}
}
~~~
### **相關資料**
[serial.begin()](https://www.arduino.cc/en/Serial/Begin)?
[serial.read()](https://www.arduino.cc/en/Serial/Read)?
[serial.available()](https://www.arduino.cc/en/Serial/Available)?
[switch() case](https://www.arduino.cc/en/Reference/SwitchCase)?
[digitalWrite()](https://www.arduino.cc/en/Reference/DigitalWrite)?
[原文連接](http://www.arduino.cc/en/Tutorial/SwitchCase2)
- 說明
- 系統示例文件目錄結構及說明
- 01.Basics
- AnalogReadSerial
- BareMinimum
- Blink
- DigitalReadSerial
- Fade
- ReadAnalogVoltage
- 02.Digital
- BlinkWithoutDelay
- Button
- Debounce
- DigitalInputPullup
- StateChangeDetection
- toneKeyboard
- toneMelody
- toneMultiple
- tonePitchFollower
- 03.Analog
- AnalogInOutSerial
- AnalogInput
- AnalogWriteMega
- Calibration
- Fading
- Smoothing
- 04.Communication
- ASCIITable
- Dimmer
- Graph
- Midi
- MultiSerial
- PhysicalPixel
- ReadASCIIString
- SerialCallResponse
- SerialCallResponseASCII
- SerialEvent
- SerialPassthrough
- VirtualColorMixer
- 05.Control
- Arrays
- ForLoopIteration
- IfStatementConditional
- switchCase
- switchCase2
- WhileStatementConditional
- 06.Sensors
- ADXL3xx
- Knock
- Memsic2125
- Ping
- 07.Display
- barGraph
- RowColumnScanning
- 08.Strings
- CharacterAnalysis
- StringAdditionOperator
- StringAppendOperator
- StringCaseChanges
- StringCharacters
- StringComparisonOperators
- StringConstructors
- StringIndexOf
- StringLength
- StringLengthTrim
- StringReplace
- StringStartsWithEndsWith
- StringSubstring
- StringToInt
- 09.USB
- Keyboard
- KeyboardLogout
- KeyboardMessage
- KeyboardReprogram
- KeyboardSerial
- KeyboardAndMouseControl
- Mouse
- ButtonMouseControl
- JoystickMouseControl
- 10.StarterKit_BasicKit (與特定硬件相關,暫無)
- p02_SpaceshipInterface
- p03_LoveOMeter
- p04_ColorMixingLamp
- p05_ServoMoodIndicator
- p06_LightTheremin
- p07_Keyboard
- p08_DigitalHourglass
- p09_MotorizedPinwheel
- p10_Zoetrope
- p11_CrystalBall
- p12_KnockLock
- p13_TouchSensorLamp
- p14_TweakTheArduinoLogo
- p15_HackingButtons
- 11.ArduinoISP(暫無)
- ArduinoISP