Arduino内置教程-控制结构-if声明条件
if声明(条件声明)
- 这个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
}
- 你任何时候都可以用到if声明。下面的例子如果模拟输入引脚读取的值超过阈值,就会打开pin13的LED灯(内置在很多Arduino上)。
硬件要求
- Arduino or Genuino 开发板
- 电位计 或者 变阻器
电路
图由Fritzing软件绘制。
原理图
样例代码
在下面的代码里,一个叫analogValue的变量用来保存从电位计(连接到开发板的模拟引脚pin0)读取的数据。然后对比这个数据和阈值。如果模拟值在设置的阈值上面,打开pin13的内置LED灯。如果低于阈值,LED保持关闭。
/*
Conditionals - If statement
This example demonstrates the use of if() statements.
It reads the state of a potentiometer (an analog input) and turns on an LED
only if the potentiometer goes above a certain threshold level. It prints the analog value
regardless of the level.
The circuit:
* potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 13 to ground
* Note: On most Arduino boards, there is already an LED on the board
connected to pin 13, so you don't need any extra components for this example.
created 17 Jan 2009
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/IfStatement
*/
// These constants won't change:
const int analogPin = A0; // pin that the sensor is attached to
const int ledPin = 13; // pin that the LED is attached to
const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communications:
Serial.begin(9600);
}
void loop() {
// read the value of the potentiometer:
int analogValue = analogRead(analogPin);
// if the analog value is high enough, turn on the LED:
if (analogValue > threshold) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
// print the analog value:
Serial.println(analogValue);
delay(1); // delay in between reads for stability
}
更多
- if()
- if...else
- analogRead()
- digitalWrite()
- serial.begin()
- serial.print()
- 数组:一个在For循环的变量举例了怎样使用一个数组。
- IfStatementConditional:通过for循环来控制多个LED灯
- If声明条件:使用一个‘if 声明’,通过改变输入条件来改变输出条件
- Switch Case:怎样在非连续的数值里选择。
- Switch Case 2:第二个switch-case的例子,展示怎样根据在串口收到的字符来采取不同的行为
- While 声明条件:当一个按键被读取,怎样用一个while循环来校准一个传感器。