learing:examples:whileloop
差别
这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录前一修订版 | |||
learing:examples:whileloop [2017/10/05 03:41] – 弘毅 | learing:examples:whileloop [2023/06/07 04:23] (当前版本) – 外部编辑 127.0.0.1 | ||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== While Loop (while循环)====== | ||
+ | |||
+ | |||
+ | 有时候你会想暂停所有的程序当一个给定的条件是真的话。这种情况下你可以使用while循环,这个例子会演示使用while循环校准模拟输入值。 | ||
+ | |||
+ | |||
+ | 主循环中,程序读取连接在A0口的电位器的值,并用它熄灭链接在9号引脚的led灯。当2号引脚的按键被按下后,程序寻找传感器的最大最小值进行校准,按键松开后,继续循环。 | ||
+ | |||
+ | 这个方法使你可以在条件改变的时候更新电位器的最大最小值 | ||
+ | |||
+ | |||
+ | ====== 按键校准电位器 ====== | ||
+ | |||
+ | <WRAP left round info 100%> | ||
+ | 此例程显示了每次按键按下,校准电位器的值,点亮LED来展示效果。 | ||
+ | </ | ||
+ | |||
+ | ===== ALPHA MEGA328-U核心 ===== | ||
+ | ==== 硬件 ==== | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | |||
+ | ==== 搭建电路 ==== | ||
+ | |||
+ | - ALPHA MEGA328-U模块插入并行扩展版1号槽位。 | ||
+ | - ALPHA 11 LED模块插入1号槽位,堆叠于MEGA328-U上。 | ||
+ | - ALPHA 微动开关模块插入并行扩展板2号槽位。 | ||
+ | - USB线连接计算机与ALPHA MEGA328-U。 | ||
+ | |||
+ | ==== 代码 ==== | ||
+ | |||
+ | |||
+ | <code cpp>/* | ||
+ | Conditionals - while statement | ||
+ | */ | ||
+ | |||
+ | |||
+ | // 常量: | ||
+ | const int sensorPin = A2; // 电位器连接的引脚 | ||
+ | const int ledPin = 9; // LED连接的引脚 | ||
+ | const int indicatorLedPin = 13; // | ||
+ | const int buttonPin = 2; // 按键连接的引脚 | ||
+ | |||
+ | |||
+ | // 变量: | ||
+ | int sensorMin = 1023; // 传感器最小值 | ||
+ | int sensorMax = 0; // 传感器最大值 | ||
+ | int sensorValue = 0; // 传感器值 | ||
+ | |||
+ | |||
+ | void setup() { | ||
+ | // 设置LED输出 按键输入: | ||
+ | pinMode(indicatorLedPin, | ||
+ | pinMode(ledPin, | ||
+ | pinMode(buttonPin, | ||
+ | } | ||
+ | |||
+ | void loop() { | ||
+ | // 按键按下 校准读取到的数据: | ||
+ | while (digitalRead(buttonPin) == HIGH) { | ||
+ | calibrate(); | ||
+ | } | ||
+ | // 停止校准的信号 | ||
+ | digitalWrite(indicatorLedPin, | ||
+ | |||
+ | // 读取传感器值: | ||
+ | sensorValue = analogRead(sensorPin); | ||
+ | |||
+ | // 应用校准值到传感器 | ||
+ | sensorValue = map(sensorValue, | ||
+ | |||
+ | // 校准期间保证传感器值在有效范围内 | ||
+ | sensorValue = constrain(sensorValue, | ||
+ | |||
+ | // 使用校准值使LED亮灭: | ||
+ | analogWrite(ledPin, | ||
+ | } | ||
+ | |||
+ | void calibrate() { | ||
+ | // 点亮内置LED表明开始校准: | ||
+ | digitalWrite(indicatorLedPin, | ||
+ | // read the sensor: | ||
+ | sensorValue = analogRead(sensorPin); | ||
+ | |||
+ | // 记录最大值 | ||
+ | if (sensorValue > sensorMax) { | ||
+ | sensorMax = sensorValue; | ||
+ | } | ||
+ | |||
+ | // 记录最小值 | ||
+ | if (sensorValue < sensorMin) { | ||
+ | sensorMin = sensorValue; | ||
+ | } | ||
+ | }</ |