I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?
Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?
Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.
Here's my code at the moment (sorry, it's not very clean):
int ledpins[] = {4, 5, 6};
int buttonpin = 3;
int buttonstate = 0;
void setup() {
Serial.begin(9600);
for (int pin = 6; pin > 3; pin--) {
pinMode(ledpins[pin], OUTPUT);
}
pinMode(buttonpin, INPUT);
}
void loop() {
buttonstate = digitalRead(buttonpin);
if (buttonstate == HIGH) {
digitalWrite(ledpins, HIGH);
}
if (buttonstate == LOW) {
for (int pin = 4; pin < 7; pin++) {
digitalWrite(pin, HIGH);
delay(200);
digitalWrite(pin, LOW);
}
for (int pin = 6; pin > 3; pin--) {
digitalWrite(pin, HIGH);
delay(200);
digitalWrite(pin, LOW);
}
}
}
2 Answers 2
The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button. You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing. In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons. And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.
I would just use a pin interrupt and if the button is pressed the interrupt routine sets a flag (ie flag=1). Then in you loop just have a statement that says calls a function that is just a while loop which waits until flag variable is 0 again. The interrupt function just toggles the flag variable every time the button is pushed. So first time button is pressed the program loops and the second time the button is pressed program execution leaves the routine and goes back to your loop().
setup()
, you are accessingledpins[6]
, which is out of bounds. 2) Inloop()
,digitalWrite(ledpins, HIGH)
makes no sense, asledpins
is not an integer.