Hello, community. I am trying to run a program in Arduino so one single button can make a led and a dc motor run for five seconds when clicked once. And then run for 10 seconds when clicked two times. And finally, to have it run indefinitely as long as it is been hold down.
The problem I have is that the led and motor will run for five seconds when I press the button once, but if I push it two times it will run for ten seconds, which is fine, but it doesn't respond correctly just because I pushed two times, it will do 5 seconds, and the 10 seconds, and then 5 seconds, and then 10 seconds, and so on. It won't respond to the command of two clicks 10 seconds, or 1 click, 5 second.
int buttonPin = 2; // button connected to digital pin 2
int ledPin = 0; // LED connected to digital pin 0
int motorPin = 1; // motor connected to digital pin 1
int buttonState = 0; // variable to store button state
int buttonPresses = 0; // variable to store number of button presses
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(motorPin, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
buttonPresses++;
delay(200); // debouncing delay to avoid multiple counts for one button press
}
// if button pressed once, run LED and motor for 5 seconds
if (buttonPresses == 1) {
digitalWrite(ledPin, HIGH);
digitalWrite(motorPin, HIGH);
delay(5000);
digitalWrite(ledPin, LOW);
digitalWrite(motorPin, LOW);
}
// if button pressed twice, run LED and motor for 10 seconds
if (buttonPresses == 2) {
digitalWrite(ledPin, HIGH);
digitalWrite(motorPin, HIGH);
delay(10000);
digitalWrite(ledPin, LOW);
digitalWrite(motorPin, LOW);
buttonPresses = 0; // reset buttonPresses after second press
}
}
This is not a very reliable way to debounce and count button presses, because it starts the delay() the instant the button is pressed, and does not sample the button while delay() is being executed.
if (buttonState == HIGH) {
buttonPresses++;
delay(200); // debouncing delay to avoid multiple counts for one button press
}
There are button libraries and tutorials that discuss techniques for more control over counting, distinguishing short and long press, etc. Search phrase something like "arduino button library".
Take a look at the Arduino State Change Detection example to learn how to detect when a button "becomes pressed", and act accordingly. Files>Examples>02.Digital>StateChangeDetection