材料:
1.SAGOO UNO 1块;
2.按键模块 1块;
3.杜邦线若干。
步骤:
1.按照下图连接按键模块和UNO;
SAGOO UNO引脚 按键模块引脚
3V3 <------------------------------------> V(电源)
GND <------------------------------------> G(电源)
Pin2 <------------------------------------> S(信号)
2.启动Arduino IDE软件,打开File->Examples->Digital->Button,编译并下载到UNO主板;
3.默认UNO板上LED灯是亮的,按下按键LED灭,放开LED灯亮。
演示视频:http://v.youku.com/v_show/id_XMTI4NjM2NTg0MA==.html
原理图:
代码:
// constants won‘t change. They‘re used here to
// set pin numbers:
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);
}
}
说明:
硬件:UNO主板通过Digital Pin2读取按键模块的状态,当按键输出为高电平,点亮LED灯,反之,熄灭LED灯。按键模块默认输出高电平,按下按键输出低电平。
软件:
const int buttonPin = 2; --定义常量button为数字2;
const int ledPin = 13; -- 定义常量ledPin为数字13;
int buttonState = 0;---定义引脚变量的默认状态为0;
buttonState = digitalRead(buttonPin);--读数字脚2的状态值给变量buttonstate;
/*----------------------------------------------------
if...else...语句,判断按键状态并执行对应的动作
-----------------------------------------------------*/
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}