按下亮灯,松开灭灯
int Red = 2; // 红灯
int Button = 13; // 按钮
int buttonStatus = 0;
void setup() {
pinMode(Red, OUTPUT);
pinMode(Button, INPUT_PULLUP);
}
void loop() {
buttonStatus = digitalRead(Button);
// 按下亮灯,松开灭灯
if (buttonStatus == HIGH) {
digitalWrite(Red, HIGH);
} else {
digitalWrite(Red, LOW);
}
}
按一下亮,再按来,依次循环
int Red = 2; // 红灯
int Button = 13;
int buttonStatus = LOW;
void setup() {
pinMode(Red, OUTPUT);
pinMode(Button, INPUT_PULLUP);
}
void loop() {
int s = digitalRead(Button);
if (s == HIGH) {
delay(100); // 等100毫秒后手按稳了再读取按钮状态
if (s == digitalRead(Button)) {
buttonStatus = !buttonStatus;
}
}
if (buttonStatus == HIGH) {
digitalWrite(Red, HIGH);
} else {
digitalWrite(Red, LOW);
}
}