Last active
July 27, 2019 13:02
-
-
Save roman-mazur/180f7be51b888d679f5ffefafcd1daa3 to your computer and use it in GitHub Desktop.
Arduino - simple lights switch example
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
#define RED 4 | |
#define GREEN 3 | |
#define BLUE 2 | |
#define COUNT (RED-BLUE+1) | |
#define BUTTON 7 | |
int state[] = {LOW, LOW, LOW}; | |
int toStateIndex(int pin) { | |
return pin - BLUE; | |
} | |
void writeState(int pin) { | |
digitalWrite(pin, state[toStateIndex(pin)]); | |
} | |
void applyState() { | |
writeState(RED); | |
writeState(BLUE); | |
writeState(GREEN); | |
} | |
long long int lastSwitchTime; | |
void setup() { | |
pinMode(RED, OUTPUT); | |
pinMode(GREEN, OUTPUT); | |
pinMode(BLUE, OUTPUT); | |
lastSwitchTime = millis(); | |
applyState(); | |
Serial.begin(9600); | |
} | |
int currentLight = 0; | |
void updateState() { | |
for (int i = 0; i < COUNT; i++) { | |
state[i] = LOW; | |
} | |
state[currentLight] = HIGH; | |
} | |
int currentDelay = 0; | |
int delays[] = {2000, 1000, 500, 250, 500, 1000}; | |
int delaysCount = sizeof(delays)/sizeof(int); | |
void loop() { | |
if (millis() - lastSwitchTime >= delays[currentDelay]) { | |
currentLight = (currentLight + 1) % COUNT; | |
updateState(); | |
applyState(); | |
lastSwitchTime = millis(); | |
} | |
// Button input handler. | |
int value = analogRead(BUTTON); | |
bool high = value > 1000; | |
if (high) { | |
delay(300); | |
value = analogRead(BUTTON); | |
high = value > 1000; | |
if (!high) { | |
currentDelay = (currentDelay + 1) % delaysCount; | |
delay(1000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment