1

I want to have a loop of 4 colours which runs constantly (i.e. red -> green -> blue -> white) each of the colours having their own LED and pin on the Arduino board. There is a 7 second delay between switching the colour and this cycle should run continuously. When I press a button, I want the cycle to immediately switch back to green and continue the cycle (i.e. -> blue -> white -> red) again.

How should I go about this? Can you have a listener for a button press going at the same time as a delay? How do you interrupt the timer and change the active LED?

asked Mar 28, 2016 at 13:30

2 Answers 2

1

You could start with the attachInterrupt example sketch and work from there. Here is a possible solution:

enum { GREEN = 0, BLUE = 1, WHITE = 2, RED = 3};
const int buttonPin = 2;
const int ledPin[] = { 4, 5, 6, 7 };
volatile bool reset = false;
int state = GREEN;
void setup() {
 pinMode(buttonPin, INPUT_PULLUP);
 for (int i = 0; i < 4; i++) pinMode(ledPin[i], OUTPUT);
 attachInterrupt(digitalPinToInterrupt(buttonPin), doResetState, FALLING);
}
void loop() {
 digitalWrite(ledPin[state], HIGH);
 delay(7000);
 digitalWrite(ledPin[state], LOW);
 if (state == RED || reset) {
 state = GREEN;
 reset = false;
 }
 else {
 state = state + 1;
 }
}
void doResetState () {
 reset = true;
}

This will not immediately cycle back to GREEN when pressing the button but you can fix that by modifying the doResetState().

Cheers!

answered Mar 29, 2016 at 14:27
0

The SimpleTimer library would be ideal for this. One timer callback function, the present contents of the loop() function, would advance the lighting state, called by a 7 second timer. Another, your present doResetState() with the modification noted by @MikaelPatel, would read (and debounce) the button on, say, a 100ms timer. The main loop would be reduced to Timer.run();

answered Mar 29, 2016 at 14:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.