用户工具

站点工具

Action disabled: source

learing:examples:whileloop

While Loop (while循环)

有时候你会想暂停所有的程序当一个给定的条件是真的话。这种情况下你可以使用while循环,这个例子会演示使用while循环校准模拟输入值。

主循环中,程序读取连接在A0口的电位器的值,并用它熄灭链接在9号引脚的led灯。当2号引脚的按键被按下后,程序寻找传感器的最大最小值进行校准,按键松开后,继续循环。

这个方法使你可以在条件改变的时候更新电位器的最大最小值

按键校准电位器

此例程显示了每次按键按下,校准电位器的值,点亮LED来展示效果。

ALPHA MEGA328-U核心

硬件

搭建电路

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

代码

/*
  Conditionals - while statement
*/
 
 
// 常量:
const int sensorPin = A2;       // 电位器连接的引脚
const int ledPin = 9;           // LED连接的引脚
const int indicatorLedPin = 13; //内置LED连接的引脚
const int buttonPin = 2;        // 按键连接的引脚
 
 
// 变量:
int sensorMin = 1023;  // 传感器最小值
int sensorMax = 0;     // 传感器最大值
int sensorValue = 0;         // 传感器值
 
 
void setup() {
  // 设置LED输出 按键输入:
  pinMode(indicatorLedPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}
 
void loop() {
  // 按键按下 校准读取到的数据:
  while (digitalRead(buttonPin) == HIGH) {
    calibrate();
  }
  // 停止校准的信号
  digitalWrite(indicatorLedPin, LOW);
 
  // 读取传感器值:
  sensorValue = analogRead(sensorPin);
 
  // 应用校准值到传感器
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
 
  // 校准期间保证传感器值在有效范围内
  sensorValue = constrain(sensorValue, 0, 255);
 
  // 使用校准值使LED亮灭:
  analogWrite(ledPin, sensorValue);
}
 
void calibrate() {
  // 点亮内置LED表明开始校准:
  digitalWrite(indicatorLedPin, HIGH);
  // read the sensor:
  sensorValue = analogRead(sensorPin);
 
  // 记录最大值
  if (sensorValue > sensorMax) {
    sensorMax = sensorValue;
  }
 
  // 记录最小值
  if (sensorValue < sensorMin) {
    sensorMin = sensorValue;
  }
}
learing/examples/whileloop.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1