const int ledpin = 10
bool ledon = false
void setup() {
// put your setup code here, to run once:
pinMode(buttpin, INPUT_PULLUP)//输入模式,内部上拉
pinMode(ledpin, OUTPUT)
digitalWrite(ledpin, LOW)//关灯
//Serial.begin(9600)
}
int Keydown()
static int keyflag = 0
if ((keyflag == 0) &&digitalRead(buttpin) == LOW)//按钮负逻辑,按钮被按下
{
delay(100)//延时除颤
if (digitalRead(buttpin) == LOW)
{
//Serial.println("Down")
keyflag = 1//置1,避免持续按下按键时再次进入此函数体。
return 1
}
}
if (digitalRead(buttpin) == HIGH)//按钮断开
{
//Serial.println("UP")
keyflag = 0
}
return 0
}
void loop() {
// put your main code here, to run repeatedly:
if (Keydown())
{
ledon=!ledon//状态取反
//呼吸效果用循环次数和延时控制
if (ledon)
{//真,开灯
for (int i = 0i <255i += 5)
{
analogWrite(ledpin, i)//PWM输出
delay(50)
}
}
else
{//假,关灯
for (int i = 255i >= 0i -= 5)
{
analogWrite(ledpin, i)//PWM输出
delay(50)
}
}
}
}
使用按键(PUSHBUTTON)控制LED灯号的开关,当按键被按下时打开LED灯号,按键放开时关闭LED灯号。材料
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条)