如何用arduino来用按钮控制RGB LED

如何用arduino来用按钮控制RGB LED,第1张

 使用按键(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

就可以找到。

arduino按钮按一下是开始程序。对按键按下和抬起判宽尺州断,定义一个开关变量记录状态。Arduino是一款便捷灵活、方便上手的开慎蔽源电子原型平台。包含硬件(各种型号的Arduino板)和软件(ArduinoIDE)。由一困数个欧洲开发团队于2005年冬季开发。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12353988.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存