问题
I have a simple Arduino Project, 2 buttons and face a strange case that in the beginning status of buttons are 0, but after click on the button and release the status becomes 1 for long a time then back to 0, please what is the wrong??
Code:
int const BTN1_PIN=2;
int const BTN2_PIN=4;
void setup(){
pinMode(BTN1_PIN, INPUT);
pinMode(BTN2_PIN, INPUT);
Serial.begin(9600);
}
void loop(){
int status1=digitalRead(BTN1_PIN);
Serial.print("BTN1 Status :");
Serial.println(status1);
int status2=digitalRead(BTN2_PIN);
Serial.print("BTN2 Status :");
Serial.println(status2);
delay(250);
}
in the begining, the values is :
BTN1 Status :0
BTN2 Status :0
.
.
But after click on the button1 and release the status of button1 take long time to back to 0, the output like:
BTN1 Status :1
BTN2 Status :0
BTN1 Status :1
BTN2 Status :0
BTN1 Status :1
BTN2 Status :0
BTN1 Status :1
BTN2 Status :0
BTN1 Status :1
BTN2 Status :0
BTN1 Status :1
BTN2 Status :0
BTN1 Status :1
BTN2 Status :0
BTN1 Status :1
BTN2 Status :0
BTN1 Status :0
BTN2 Status :0
BTN1 Status :0
BTN2 Status :0
BTN1 Status :0
BTN2 Status :0
BTN1 Status :0
BTN2 Status :0
BTN1 Status :0
BTN2 Status :0
回答1:
The problem with your design is that, when no push button is pressed, your I/O pins are not connected to anything. This causes their values to kind of "float" around meaning they jump between 1 and 0. Usually you would connect the I/O pin directly to +5v via a high value resistor (i.e. 10K ohms) and then also connect the I/O pin to ground through a push button. This way, when you read the pin without the push button pressed, you get a solid +5v (and hardly any current because of the resistor), but when you press the button, you short to ground (through the resistor) and get a solid 0v. This gives you a very clean "on" and "off" where your pressed button state is 0v.
Arduinos are cool because they have these resistors to +5v built into the board itself. You just have to turn them on using pinMode(pinBUTTON, INPUT_PULLUP);
. I have included a design of what your circuit layout should be above.
An important thing to remember with arduinos is you ALWAYS have to set your pinModes. This is an easy step to forget, and the arduino will "kind of" work without it, but it is a common source of odd results in your projects.
const int pinBUTTONONE = 2;
const int pinBUTTONTWO = 4;
void setup(){
pinMode(pinBUTTONONE, INPUT_PULLUP);
pinMode(pinBUTTONTWO, INPUT_PULLUP);
}
void setup(){
if(digitalRead(pinBUTTONONE) == LOW){
// Execute button one pressed code.
}
if(digitalRead(pinBUTTONTWO) == LOW){
// Execute button two pressed code.
}
}
来源:https://stackoverflow.com/questions/25657310/arduino-switch-button