
用 Arduino 和轻触开关实现最简单的“拨动开关”(可以保持和切换开关状态),为了便于理解,没有多余的元件,这里只实现一个最简单的开关来控制LED。
效果如上图。下面是接线图和源代码。

/*********************
Simple toggle switch
Created by: P.Agiakatsikas
*********************/
int button = 8;
int led = 13
int status = false;
void setup(){
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP); // set the internal pull up resistor, unpressed button is HIGH
}
void loop(){
//a) if the button is not pressed the false status is reversed by !status and the LED turns on
//b) if the button is pressed the true status is reveresed by !status and the LED turns off
if (digitalRead(button) == true) {
status = !status;
digitalWrite(led, status);
} while(digitalRead(button) == true);
delay(50); // keeps a small delay
}

发表评论
要发表评论,您必须先登录。