代码分析
定义变量
const int buttonPin = 12; //the button connect to pin 12
const int ledPin = 13; //the led connect to pin13
int buttonState = 0; // variable for reading the pushbutton status
将按键连接到引脚12,LED已经连接到引脚 13。定义一个变量 buttonState 来存储按键的值。
设置引脚的输入输出状态
pinMode(buttonPin, INPUT); //initialize thebuttonPin as input
pinMode(ledPin, OUTPUT); //initialize the led pin as output
本次实验我们需要知道按键的状态,所以这里设置 buttonPin 为 INPUT ;要设置 LED 的高/低,我们将 LedPin 设置为 OUTPUT。
读取按键状态
buttonState = digitalRead(buttonPin);
buttonPin``(Pin12) 是数字引脚;这里是读取按键的值并将其存储在 ``buttonState 中。
按键按下时让LED点亮
if (buttonState == HIGH )
{
digitalWrite(ledPin, HIGH); //turn the led on
}
else
{
digitalWrite(ledPin, LOW); //turn the led off
}
在这部分代码中,当 buttonState 为 HIGH 时,让 ledPin 为 HIGH ,LED会被点亮。
由于按键的一端已连接至 5V,另一端已连接至引脚 12,因此按下按键时,引脚 12 为 5V(高电平)。
然后用 if () 判断;如果条件为真,则 LED 将亮起。
else 意味着当 if(conditional) 被确定为 false 时,运行 else。