I am trying to have a switch wired to count number of actuations (that prints to an LCD).
The problem is the switch is held for about 4 seconds and I would like to avoid using the delay for that long. Right now the count just continues to count up while the button/switch is depressed.
How can this be done with code?
I have looked at debouncing but that doesnt seem to work with long button presses.
buttonState = digitalRead(buttonPin); // read the state of the pushbutton value:
if (buttonState == HIGH) { // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
counter++ ; //Add to counter
myEnc.write(0); //This redefines encoder to zero allowing the counter to force other if statement to reprint counter.
delay(500);
lcd.setCursor(0,1); // Cursor Position Col 1 Row 2
lcd.print(counter); // Screen Counter
}
}
Im struggling to understand how to logically get it to only count once, I have looked at a lot of different sources online and on the arduino forums and its not clicking
Check out IDE - File/examples/digital/state change detection. This shows how to sense when a switch (or any Boolean variable) *changes * as opposed to sensing when it's in one or the other stable state. Closely related to debouncing.
Thats excellent, and the example functions exactly as needed but when I use similar code the counter goes up constantly while button is held down and the else portion doesnt clear screen as written.
/Button Variables
//Fixed
const int buttonPin = 13; // the number of the pushbutton pin
//Variable
int buttonState = 0; // Current state of the button
int counter = 0; //Variable for counter function
int lastButtonState = 0; //Previous button state
void setup()
{
pinMode(buttonPin, INPUT_PULLUP); //initialize the pushbutton pin as an input:
}
void loop()
{
Serial.println("Basic Encoder Test:");
// initialize the LCD
lcd.begin(); //Initialize Screen
buttonState = digitalRead(buttonPin); // read the state of the pushbutton value:
if (buttonState != lastButtonState) {
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH){
counter++ ; //Add to counter
myEnc.write(0); //This redefines encoder to zero allowing the counter to force other if statement to reprint counter.
lcd.setCursor(0,2); // Cursor Position Col 1 Row 3
lcd.print("MELTING....");
lcd.setCursor(0,1); // Cursor Position Col 1 Row 2
lcd.print(counter); // Strap Counter
} else {
lcd.setCursor(0,2); // Cursor Position Col 1 Row 3
lcd.print(" "); // Print Blank Spaces to clear out "Melting..."
}
delay(50); //debouncing
}
}