Created
May 20, 2020 15:41
-
-
Save ahokinson/53d057867dab6a71090946adb1a9d8b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
struct State { | |
int previous; | |
int current; | |
}; | |
class Button { | |
public: | |
explicit Button(int); | |
int pin; | |
State state{}; | |
bool pressed(); | |
}; | |
Button::Button(int p) { | |
pin = p; | |
state = State{1, 1}; | |
} | |
bool Button::pressed() { | |
state.previous = state.current; | |
state.current = digitalRead(pin); | |
return ((state.current == 0) && (state.previous != state.current)); | |
} | |
struct Light { | |
int pin; | |
}; | |
class LightSeries { | |
public: | |
explicit LightSeries(Light[]); | |
Light lights[3]{}; | |
int lightIndex; | |
void cycle(); | |
}; | |
LightSeries::LightSeries(Light *l) { | |
memcpy(lights, l, 3 * sizeof(Light)); | |
lightIndex = -1; | |
} | |
void LightSeries::cycle() { | |
for (Light light : lights) { | |
digitalWrite(light.pin, LOW); | |
} | |
lightIndex++; | |
if (lightIndex < 3) { | |
digitalWrite(lights[lightIndex].pin, HIGH); | |
} else { | |
lightIndex = -1; | |
} | |
} | |
Light green{9}; | |
Light yellow{10}; | |
Light red{11}; | |
Button button = Button(5); | |
Light lights[]{green, yellow, red}; | |
LightSeries lightSeries = LightSeries(lights); | |
void setup() { | |
for (Light light : lightSeries.lights) { | |
pinMode(light.pin, OUTPUT); | |
digitalWrite(light.pin, LOW); | |
} | |
pinMode(button.pin, INPUT); | |
Serial.begin(9600); | |
} | |
void loop() { | |
if (button.pressed()) { | |
lightSeries.cycle(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment