So I have a pushbutton and I want it to return "TRUE" whenever I push it with debounce. Here is my code, yet whenever I push it, it returns TRUE twice, everytime I press it and release it. I only want it to return true when its pressed and not released. Any help would be great.
#include <Servo.h>
Servo myservo;
int init_pos = 90; //Positions for servo to sort nuts
int pos1 = 30;
int pos2 = 70;
int pos3 = 110;
int pos4 = 150;
int buttonPin = 8; //Variables for push button
int buttonState = LOW;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(buttonPin, INPUT);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
myservo.write(init_pos);
}
void loop() {
// put your main code here, to run repeatedly:
if (button() == true){
Serial.println("TRUE");
}
}
boolean button(){
int reading = digitalRead(buttonPin);
if (reading != lastButtonState){ //If the button state changed, start a timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState){
buttonState = reading;
return true;
}
else{
return false;
}
}
lastButtonState = reading;
}
LarryD:
if (reading != buttonState && reading == HIGH){
Naw, he'll need a second if, because he wants to set buttonState = reading regardless of whether the button was pressed or released, but he only wants to return true if it was pressed.
#include <Servo.h>
Servo myservo;
int init_pos = 90; //Positions for servo to sort nuts
int pos1 = 30;
int pos2 = 70;
int pos3 = 110;
int pos4 = 150;
int buttonPin = 8; //Variables for push button
int buttonState = LOW;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
myservo.write(init_pos);
}
void loop() {
// put your main code here, to run repeatedly:
if (button() == true){
Serial.println("TRUE");
}
}
boolean button(){
int reading = digitalRead(buttonPin);
if (reading != lastButtonState){ //If the button state changed, start a timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState){
buttonState = reading;
if(reading == LOW) //for push = LOW OR if(reading == HIGH) //for push = HIGH
{
return true;
}
}
//else{
return false;
//}
}
lastButtonState = reading;
}
Saving the current state as the previous state happens only at the end of the function. The end of the function is never reached, because a return statement has already been executed.