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?

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!

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();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.