// Wokwi is wonderful.
// This Wokwi project: https://wokwi.com/projects/403246479725060097
// Based on: https://wokwi.com/projects/403242669970467841
// For forum: https://forum.arduino.cc/t/is-wokwi-just-busted/1281059
#define BUTTON_PIN_F 16
#define BUTTON_PIN_R 4
#define LED_NUMBER 5
byte LEDPinArray[LED_NUMBER] = { 18, 17, 25, 26, 27 };
unsigned long debounceDuration = 50; // millis
unsigned long lastTimeButtonStateChanged_F = 0;
unsigned long lastTimeButtonStateChanged_R = 0;
byte lastButtonState_F = HIGH;
byte lastButtonState_R = HIGH;
int LEDIndex = 0;
void initAllLEDs()
{
for (int i = 0; i < LED_NUMBER; i++)
pinMode(LEDPinArray[i], OUTPUT);
}
void powerOnSelectedLEDOnly(int index)
{
for (int i = 0; i < LED_NUMBER; i++)
{
if (i == index)
digitalWrite(LEDPinArray[i], HIGH);
else
digitalWrite(LEDPinArray[i], LOW);
}
}
void setup()
{
initAllLEDs();
pinMode(BUTTON_PIN_F, INPUT_PULLUP);
pinMode(BUTTON_PIN_R, INPUT_PULLUP);
digitalWrite(LEDPinArray[LEDIndex], HIGH);
}
void loop()
{
unsigned long timeNow = millis();
bool forward = false;
bool reverse = false;
// ---------------------------------------
// Gather all the information
// ---------------------------------------
if (timeNow - lastTimeButtonStateChanged_F > debounceDuration)
{
byte buttonState_F = digitalRead(BUTTON_PIN_F);
if (buttonState_F != lastButtonState_F)
{
lastTimeButtonStateChanged_F = timeNow;
lastButtonState_F = buttonState_F;
if (buttonState_F == LOW) // button was pressed just now
forward = true;
}
}
if (timeNow - lastTimeButtonStateChanged_R > debounceDuration)
{
byte buttonState_R = digitalRead(BUTTON_PIN_R);
if (buttonState_R != lastButtonState_R)
{
lastTimeButtonStateChanged_R = timeNow;
lastButtonState_R = buttonState_R;
if (buttonState_R == LOW) // button was pressed just now
reverse = true;
}
}
// ---------------------------------------
// Process the information
// ---------------------------------------
if(forward)
{
LEDIndex++;
if (LEDIndex >= LED_NUMBER)
LEDIndex = 0;
powerOnSelectedLEDOnly(LEDIndex);
}
if(reverse)
{
LEDIndex--;
if (LEDIndex < 0)
LEDIndex = LED_NUMBER - 1;
powerOnSelectedLEDOnly(LEDIndex);
}
}
Wokwi is wonderful