#include <Toggle.h>
const byte speedPin = A0;
const byte buttonPin = A5;
Toggle button;
struct TrafficLight {
enum {GREEN, YELLOW, RED};
const uint8_t pins[3]; // green yellow, red
void begin() {
for (uint8_t aPin : pins) pinMode(aPin, OUTPUT);
}
void off() {
for (uint8_t aPin : pins) digitalWrite(aPin, LOW);
}
void red() {
off();
digitalWrite(pins[RED], HIGH);
}
void yellow() {
off();
digitalWrite(pins[YELLOW], HIGH);
}
void green() {
off();
digitalWrite(pins[GREEN], HIGH);
}
};
TrafficLight lights[] = {
{2, 3, 4},
{5, 6, 7},
{8, 9, 10}
};
const size_t lightsCount = sizeof lights / sizeof * lights;
void chase();
void cycle();
void noAnimation();
typedef void (*FunctionPtr)();
FunctionPtr animations[] = {noAnimation, chase, cycle};
const size_t animationsCount = sizeof animations / sizeof * animations;
void noAnimation() {}
void chase() {
static unsigned long lastUpdate;
unsigned long updatePeriod = analogRead(speedPin) + 10;
static byte lightIndex = lightsCount - 1;
static byte pinIndex = 2;
if (millis() - lastUpdate > updatePeriod ) {
lastUpdate = millis();
digitalWrite(lights[lightIndex].pins[pinIndex], LOW);
if (++pinIndex == 3) {
pinIndex = 0;
if (++lightIndex == lightsCount) lightIndex = 0;
}
digitalWrite(lights[lightIndex].pins[pinIndex], HIGH);
}
}
void cycle() {
static unsigned long lastUpdate;
unsigned long updatePeriod = analogRead(speedPin) + 10;
static byte pinIndex = 2;
if (millis() - lastUpdate > updatePeriod ) {
lastUpdate = millis();
for (TrafficLight& aTrafficLight : lights) digitalWrite(aTrafficLight.pins[pinIndex], LOW);
if (++pinIndex == 3) pinIndex = 0;
for (TrafficLight& aTrafficLight : lights) digitalWrite(aTrafficLight.pins[pinIndex], HIGH);
}
}
void stateMachine() {
static byte animation = 0;
button.poll();
if (button.onPress()) {
for (TrafficLight& aTrafficLight : lights) aTrafficLight.off();
if (++animation == animationsCount) animation = 0;
}
animations[animation]();
}
void setup() {
button.begin(buttonPin);
for (TrafficLight& aTrafficLight : lights) aTrafficLight.begin();
}
void loop() {
stateMachine();
}
lights[0]
lights[1]
lights[2]
speed
change animation