learing:examples:ifstatement
差别
这里会显示出您选择的修订版和当前版本之间的差别。
| 两侧同时换到之前的修订记录前一修订版 | |||
| learing:examples:ifstatement [2017/10/05 03:40] – 弘毅 | learing:examples:ifstatement [2025/10/11 02:55] (当前版本) – 外部编辑 127.0.0.1 | ||
|---|---|---|---|
| 行 1: | 行 1: | ||
| + | ====== If Statement (Conditional Statement)(条件声明) ====== | ||
| + | |||
| + | if()声明是所有编程控制结构里最基础的。它允许你基于给定的条件的真或假来决定某事的发生或者不发生。比如 | ||
| + | |||
| + | <code cpp>if (someCondition) { | ||
| + | // do stuff if the condition is true | ||
| + | }</ | ||
| + | |||
| + | 也有另一种演变为if-else的 用法 | ||
| + | |||
| + | <code cpp>if (someCondition) { | ||
| + | // do stuff if the condition is true | ||
| + | } else { | ||
| + | // do stuff if the condition is false | ||
| + | }</ | ||
| + | |||
| + | 还有else-if, | ||
| + | |||
| + | <code cpp>if (someCondition) { | ||
| + | // do stuff if the condition is true | ||
| + | } else if (anotherCondition) { | ||
| + | // do stuff only if the first condition is false | ||
| + | // and the second condition is true | ||
| + | }</ | ||
| + | |||
| + | |||
| + | |||
| + | ====== 设置电位器阈值来控制LED亮灭 ====== | ||
| + | <WRAP left round info 100%> | ||
| + | 此例程演示了使用电位器来设置阈值,从而控制LED亮灭。 | ||
| + | </ | ||
| + | ==== 硬件 ==== | ||
| + | * [[ocrobot: | ||
| + | * [[ocrobot: | ||
| + | * [[ocrobot: | ||
| + | * [[ocrobot: | ||
| + | ==== 搭建电路 ==== | ||
| + | |||
| + | - ALPHA MEGA328-U模块插入并行扩展板1号槽位。 | ||
| + | - ALPHA 11LED器模块插入并行扩展版1号槽位堆叠于MEGA328-U上。 | ||
| + | - ALPHA 电位器模块插入并行扩展版2号槽位。 | ||
| + | - USB线连接计算机与ALPHA MEGA328-U。 | ||
| + | ==== 代码 ==== | ||
| + | |||
| + | <code cpp>/* | ||
| + | Conditionals - If statement | ||
| + | analogValue变量是用来存储接在A0口的电位器的数据的。这些数据之后就要和设定的阈值作比较。如果数据大于阈值,就点亮LED,反之熄灭。 | ||
| + | |||
| + | */ | ||
| + | |||
| + | // 常量: | ||
| + | const int analogPin = A0; // 传感器连接的引脚 | ||
| + | const int ledPin = 1; // LED连接的引脚d1 | ||
| + | const int threshold = 400; // 随意的设置在模拟值之间的阈值 | ||
| + | |||
| + | void setup() { | ||
| + | // 设置引脚为输出: | ||
| + | pinMode(ledPin, | ||
| + | // 初始化串口通讯 | ||
| + | Serial.begin(9600); | ||
| + | } | ||
| + | |||
| + | void loop() { | ||
| + | // | ||
| + | int analogValue = analogRead(analogPin); | ||
| + | |||
| + | // 如果模拟值足够大,点亮LED | ||
| + | if (analogValue > threshold) { | ||
| + | digitalWrite(ledPin, | ||
| + | } else { | ||
| + | digitalWrite(ledPin, | ||
| + | } | ||
| + | |||
| + | // 显示模拟值 | ||
| + | Serial.println(analogValue); | ||
| + | delay(1); | ||
| + | }</ | ||
| + | |||
