用户工具

站点工具


learing:examples:switchcase2

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录前一修订版
后一修订版
前一修订版
learing:examples:switchcase2 [2017/04/07 10:03] – 外部编辑 127.0.0.1learing: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的效果
 +</WRAP>
 +
 +
 +==== 硬件 ====
 +  * [[ocrobot:alpha:parallelexpansion:index|ALPHA 并行扩展板]]
 +  * [[ocrobot:alpha:mega328-u:main|ALPHA MEGA328-U]]
 +  * [[ocrobot:alpha:11led:index|ALPHA 11 LED模块]]
 +
 +==== 搭建电路 ====
 +
 +  - ALPHA 11 LED模块插入并行扩展版1号槽位。
 +  - ALPHA MEGA328-U模块插入并行扩展板2号槽位。
 +  - USB线连接计算机与ALPHA MEGA328-U。
 +
 +
 +
 +==== 代码 ====
 +
 +<code cpp>/*
 +  Switch statement  with serial input
 +*/
 +
 +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();
 +    //基于接收到的字符来作出不同的反应
 +    // 使用单引号来得到字符的ascii值,例如 'a' = 97, 'b' = 98,等等:
 +
 +    switch (inByte) {
 +      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:
 +        // 熄灭所有LED:
 +        for (int thisPin = 2; thisPin < 7; thisPin++) {
 +          digitalWrite(thisPin, LOW);
 +        }
 +    }
 +  }
 +}</code>
learing/examples/switchcase2.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1