用户工具

站点工具


learing:examples:ifstatement

差别

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


前一修订版
learing:examples:ifstatement [2023/06/07 04:23] (当前版本) – 外部编辑 127.0.0.1
行 1: 行 1:
 +====== If Statement (Conditional Statement)(条件声明) ======
 +
 +if()声明是所有编程控制结构里最基础的。它允许你基于给定的条件的真或假来决定某事的发生或者不发生。比如
 +
 +<code cpp>if (someCondition) {
 +   // do stuff if the condition is true
 +}</code>
 +
 +也有另一种演变为if-else的 用法
 +
 +<code cpp>if (someCondition) {
 +   // do stuff if the condition is true
 +} else {
 +   // do stuff if the condition is false
 +}</code>
 +
 +还有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
 +}</code>
 +
 +
 +
 +====== 设置电位器阈值来控制LED亮灭 ======
 +<WRAP left round info 100%>
 +此例程演示了使用电位器来设置阈值,从而控制LED亮灭。
 +</WRAP>
 +==== 硬件 ====
 +  * [[ocrobot:alpha:parallelexpansion:index|ALPHA 并行扩展板]]
 +  * [[ocrobot:alpha:mega328-u:main|ALPHA MEGA328-U]]
 +  * [[ocrobot:alpha:potentiometer:main|ALPHA 电位器模块]]
 +  * [[ocrobot:alpha:11led:index|ALPHA 11 LED模块]]
 +==== 搭建电路 ====
 +
 +  - 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, OUTPUT);
 +  // 初始化串口通讯
 +  Serial.begin(9600);
 +}
 +
 +void loop() {
 +  //读取电位器值
 +  int analogValue = analogRead(analogPin);
 +
 +  // 如果模拟值足够大,点亮LED
 +  if (analogValue > threshold) {
 +    digitalWrite(ledPin, HIGH);
 +  } else {
 +    digitalWrite(ledPin, LOW);
 +  }
 +
 +  // 显示模拟值
 +  Serial.println(analogValue);
 +  delay(1);        // 延时,使数据稳定
 +}</code>
 +