When pushing a button I want to read the value...once. If I push(hold) the button I get a continuous print of button1Pushed
if(button1State == LOW) {
Serial.println("button1Pushed");
}
But if I try to solve it like this, nothing happens, not a single print. What am I missing?
int button1State = digitalRead(button1);
int lastButton1State;
if(button1State != lastButton1State){
if(button1State == LOW){
Serial.println("button1Pushed");
}
}
lastButton1State = button1State;
1 Answer 1
lastButton1State
is not initialized and therefore has no strictly defined value. In your case, it appears to have a value of 0
(which is random, it's not due to implicit initialization, which is only done for global variables). The condition if(button1State != lastButton1State)
becomes true only if the button is released.
You can check that by changing
if(button1State == LOW){
Serial.println("button1Pushed");
}
to
if(button1State == HIGH){
Serial.println("button1 released");
}
The following should work:
int last_button_state=HIGH; // initialize to HIGH, so the button does not teigger on very first iteration
void setup () {
// whatever you want to do here
}
void loop() {
int button_state=digitalRead(button1);
if (button_state!=last_button_state && button_state==LOW) {
Serial.println("button pressed");
}
else if (button_state!=last_button_state && button_state==HIGH) {
Serial.println("button released");
}
last_button_state=button_state;
}
-
your suggestion gives me the same result, still an endless repeat of the serial.printNiles– Niles2020年10月18日 20:24:44 +00:00Commented Oct 18, 2020 at 20:24
-
Did you see the change I made? I forgot to add
last_button_state=button_state;
... if it still doesn't work, please post the entire codeSim Son– Sim Son2020年10月18日 20:26:42 +00:00Commented Oct 18, 2020 at 20:26 -
I tried your suggestion in a blank sketch and it works! There is probably something buggy in the rest of my code (its pretty huge..for me..as a amateur)Niles– Niles2020年10月18日 20:32:40 +00:00Commented Oct 18, 2020 at 20:32
-
Found it! I put int last_button_state=HIGH; in the loop.....pff..time for bedNiles– Niles2020年10月18日 20:36:38 +00:00Commented Oct 18, 2020 at 20:36
-
@Niles please see my commentSim Son– Sim Son2020年10月18日 20:37:25 +00:00Commented Oct 18, 2020 at 20:37