As usual with programming, there are many solutions, for example:
- You can use a bitmask, put 4 variables in an array with binary values 1000, 0100, 0010 and 0001 and when the switch is pressed, you store the value into each LED pin by comparing the value.
- However, a more simpler solution is just use a counter from 0 to 4, if the value is 1, the first LED should be one, then after a switch increase the value, and use modulo 5 (% 5) to go back to 0.
To check if a button is clicked, use a boolean, which check against the previous value. Also implement the debounce algorithm which can be found at the Arduino site.
Without debouncing it could look like this:
#include "stdlib.h"
int buttonPin = 7;
int buttonState = LOW;
int led1Pin = 8;
int led2Pin = 9;
int led3Pin = 10;
int led4Pin = 11;
int ledMode = 0; // All off, 1-4 means LED 1-4 is on
void setup()
{
}
void loop()
{
// Add debouncing yourself
if ((buttonState == LOW) && (digitalRead(buttonPin) == HIGH))
{
buttonState = HIGH;
ledMode = (ledMode + 1) % 5;
}
else if ((buttonState == HIGH) && (digitalRead(buttonPin) == LOW))
{
buttonState = LOW;
}
digitalWrite(led1Pin, ledMode == 1 ? HIGH : LOW);
digitalWrite(led2Pin, ledMode == 2 ? HIGH : LOW);
digitalWrite(led3Pin, ledMode == 3 ? HIGH : LOW);
digitalWrite(led4Pin, ledMode == 4 ? HIGH : LOW);
}
If you put the LEDs on subsequent pins, you can use the following code which is more simpler and works for any number of LEDs:
#include "stdlib.h"
int buttonPin = 7;
int buttonState = LOW;
int nrOfLeds = 4;
int startLed = 8;
int ledMode = 0; // All off, 1 means led on pin startLed, 2 means led on pin startLed + 1 etc.
void setup()
{
}
void loop()
{
// Add debouncing yourself
if ((buttonState == LOW) && (digitalRead(buttonPin) == HIGH))
{
buttonState = HIGH;
ledMode = (ledMode + 1) % (nrOfLeds + 1);
}
else if ((buttonState == HIGH) && (digitalRead(buttonPin) == LOW))
{
buttonState = LOW;
}
for (int led = 0; led < nrOfLeds; ledPin++)
{
digitalWrite(startLed + led, ledMode == led + 1 ? HIGH : LOW);
}
}