用户工具

站点工具


learing:examples:ifstatement

If Statement (Conditional Statement)(条件声明)

if()声明是所有编程控制结构里最基础的。它允许你基于给定的条件的真或假来决定某事的发生或者不发生。比如

if (someCondition) {
   // do stuff if the condition is true
}

也有另一种演变为if-else的 用法

if (someCondition) {
   // do stuff if the condition is true
} else {
   // do stuff if the condition is false
}

还有else-if,第一个条件为假的时候检查第二个条件

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亮灭

此例程演示了使用电位器来设置阈值,从而控制LED亮灭。

硬件

搭建电路

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

代码

/*
  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);        // 延时,使数据稳定
}
learing/examples/ifstatement.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1