用户工具

站点工具


learing:examples:switchcase2

Switch (case) Statement, used with serial input(串口输入)

if声明使你可以在两个不相关的事情上做出选择,真或假。当有更多选择的时候,你可以使用复杂的if声明,或者使用switch声明。switch允许你在多个不相关事情上做出选择。

这个例子展示了使用switch基于串口连续接收到的数据点亮几个不同的LED中的一个。程序监听串口输入,收到字符a b c d e分别点亮不同的LED。

输入字母控制LED闪烁

这个例程显示了打开串口监视器,发送字母 a b c d e来点亮对应的LED的效果

硬件

搭建电路

  1. ALPHA 11 LED模块插入并行扩展版1号槽位。
  2. ALPHA MEGA328-U模块插入并行扩展板2号槽位。
  3. USB线连接计算机与ALPHA MEGA328-U。

代码

/*
  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);
        }
    }
  }
}
learing/examples/switchcase2.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1