这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录前一修订版 | |||
learing:examples:switchcase2 [2017/10/05 03:43] – 弘毅 | learing:examples:switchcase2 [2023/06/07 04:23] (当前版本) – 外部编辑 127.0.0.1 | ||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== Switch (case) Statement, used with serial input(串口输入) ====== | ||
+ | if声明使你可以在两个不相关的事情上做出选择,真或假。当有更多选择的时候,你可以使用复杂的if声明,或者使用switch声明。switch允许你在多个不相关事情上做出选择。 | ||
+ | |||
+ | 这个例子展示了使用switch基于串口连续接收到的数据点亮几个不同的LED中的一个。程序监听串口输入,收到字符a b c d e分别点亮不同的LED。 | ||
+ | |||
+ | ====== 输入字母控制LED闪烁====== | ||
+ | |||
+ | <WRAP left round info 100%> | ||
+ | 这个例程显示了打开串口监视器,发送字母 a b c d e来点亮对应的LED的效果 | ||
+ | </ | ||
+ | |||
+ | |||
+ | ==== 硬件 ==== | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | |||
+ | ==== 搭建电路 ==== | ||
+ | |||
+ | - ALPHA 11 LED模块插入并行扩展版1号槽位。 | ||
+ | - ALPHA MEGA328-U模块插入并行扩展板2号槽位。 | ||
+ | - USB线连接计算机与ALPHA MEGA328-U。 | ||
+ | |||
+ | |||
+ | |||
+ | ==== 代码 ==== | ||
+ | |||
+ | <code cpp>/* | ||
+ | Switch statement | ||
+ | */ | ||
+ | |||
+ | void setup() { | ||
+ | // 初始化串口通讯 | ||
+ | Serial.begin(9600); | ||
+ | // LED引脚: | ||
+ | for (int thisPin = 2; thisPin < 7; thisPin++) { | ||
+ | pinMode(thisPin, | ||
+ | } | ||
+ | } | ||
+ | |||
+ | void loop() { | ||
+ | // 读取串口: | ||
+ | if (Serial.available() > 0) { | ||
+ | int inByte = Serial.read(); | ||
+ | // | ||
+ | // 使用单引号来得到字符的ascii值,例如 ' | ||
+ | |||
+ | switch (inByte) { | ||
+ | case ' | ||
+ | digitalWrite(2, | ||
+ | break; | ||
+ | case ' | ||
+ | digitalWrite(3, | ||
+ | break; | ||
+ | case ' | ||
+ | digitalWrite(4, | ||
+ | break; | ||
+ | case ' | ||
+ | digitalWrite(5, | ||
+ | break; | ||
+ | case ' | ||
+ | digitalWrite(6, | ||
+ | break; | ||
+ | default: | ||
+ | // 熄灭所有LED: | ||
+ | for (int thisPin = 2; thisPin < 7; thisPin++) { | ||
+ | digitalWrite(thisPin, | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | }</ |