材料
Arduino的主薯卖板×1
LED×1
按钮或开关开关×1
10K电阻×1
面包板×1
单心线X N
接线
把LED接到PIN13,长脚(阳极)接到PIN13,短脚(阴极)接到GND;
按钮一支脚接到+5 V;
PIN2接到按钮的另一支脚,同一支脚位接一个10K的电阻连到GND;
源码如下:
const int buttonPin = 2// the number of the pushbutton pin
const int ledPin = 13 //改宴 the number of the LED pin
// variables will change:
int buttonState = 0// variable for reading the pushbutton status
void setup() {
/数歼逗/ initialize the LED pin as an output:
pinMode(ledPin, OUTPUT)
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT)
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin)
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH)
}
else {
// turn LED off:
digitalWrite(ledPin, LOW)
}
说明:
L01〜L02:定义按键与LED的脚位,按键接在PIN2码,而LED接在PIN13;
L16:读取按键的状态并保存到buttonState变数里;
L20〜L26:这支程式的目的是按下按键时要打开LED灯号,放开按键时要关闭的LED灯号,因此,假如buttonState为高,代表按键状态是按下(压制)的,此时要打开LED,反之,假如buttonState为低,代表按键状态是放开的,此时要关闭LED。
注:这支是Arduino的内建的程序,点选
File >Examples >2.Digital >Button
就可以找到。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)