Menu
CoddyTech

旋钮阈值

本课属于 Coddy Arduino 学习旅程的“输入”单元。第 12 课,共 22 课。

阈值是在某个范围内画出的一条线:高于这条线时,程序会执行一种操作;低于这条线时,则会执行另一种操作。

const int threshold = 600;

if (reading > threshold) {
  digitalWrite(13, HIGH);
} else {
  digitalWrite(13, LOW);
}

把这条线的值放在 const 中,可以为它命名,也能让你只需在一个地方修改它。

else 很重要:没有它,读数一旦高于这条线,LED 就会亮起,而且再也不会熄灭。

challenge icon

挑战

简单

旋钮连接在 A0,LED 连接在引脚 13。当读数高于 600 时点亮 LED:

  • 将 600 存入 const int threshold
  • 读取 A0,当读数高于阈值时点亮 LED,否则将其熄灭

按“运行”,让旋钮从线的两侧转过这条线,然后按“检查”。

亲手试试

const int ledPin = 13;
// const int threshold = ...

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int reading = analogRead(A0);
  // 高于阈值时点亮 LED,低于阈值时将其关闭
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

输入中的所有课

自己练习: Arduino 在线编辑器