arduino
开关,下拉电阻,板载小灯,按开关灯亮
const int ledPin=13; const int inputPin=2; void setup() { // put your setup code here, to run once: pinMode(ledPin, OUTPUT); pinMode(inputPin, INPUT); //digitalWrite(inputPin, HIGH); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int val=digitalRead(inputPin); Serial.println(val); if(val==HIGH){ digitalWrite(ledPin, HIGH); }else{ digitalWrite(ledPin, LOW); } }
下拉电阻作用,开关不按时,引脚2读的是接地
开关按下,电流从5v,走过开关,走到电阻,走到接地
开关,上拉电阻,板载小灯,按开关灯亮,这里inputPin读出来的2号引脚一直是high,所以把led关闭。当按下按钮,val读出来变为0,那么把led打开设成1.
const int ledPin=13; const int inputPin=2; void setup() { // put your setup code here, to run once: pinMode(ledPin, OUTPUT); pinMode(inputPin, INPUT); //digitalWrite(inputPin, HIGH); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int val=digitalRead(inputPin); Serial.println(val); if(val==HIGH){ digitalWrite(ledPin, LOW); }else{ digitalWrite(ledPin, HIGH); } }
不用外部上拉电阻,用引脚内置的上拉电阻简化布线配置,按下按钮才会关闭led灯:
关键在一个被设置成输入模式的引脚上,写入high值,自动激活该引脚的电阻,达到2w欧
const int ledPin=13; const int inputPin=2; void setup() { // put your setup code here, to run once: pinMode(ledPin, OUTPUT); pinMode(inputPin, INPUT); digitalWrite(inputPin, HIGH); //这句,在input上打开内置电阻 Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int val=digitalRead(inputPin); //按下变为0,不按为1 Serial.println(val); if(val==HIGH){ digitalWrite(ledPin, HIGH); }else{ digitalWrite(ledPin, LOW); } }
开关去抖:
const int BUTTON = 2; // the input pin where the // pushbutton is connected int val = 0; // val will be used to store the state // of the input pin int old_val = 0; // this variable stores the previous // value of "val" int state = 0; // 0 = LED off and 1 = LED on void setup() { pinMode(LED, OUTPUT); // tell Arduino LED is an output pinMode(BUTTON, INPUT); // and BUTTON is an input } void loop(){ val = digitalRead(BUTTON); // read input value and store it // yum, fresh // check if there was a transition if ((val == HIGH) && (old_val == LOW)){ state = 1 - state; delay(10); } old_val = val; // val is now old, let's store it if (state == 1) { digitalWrite(LED, HIGH); // turn LED ON } else { digitalWrite(LED, LOW); } }