Innleveringsoppgave Januar 2019:

Oppgave 8: Basic trafikklys
This commit is contained in:
Alex Thomassen 2019-01-24 14:15:14 +01:00
parent e7ce4cff5c
commit 0b30e79d4a
Signed by: Alex
GPG Key ID: 10BD786B5F6FF5DE

View File

@ -0,0 +1,135 @@
// "ped" = Pedestrian
// Fotgjengerlys og bryter.
int pedGreen = 6;
int pedRed = 7;
int pedSwitch = 11;
// Trafikklys
int trafficRed = 8;
int trafficYellow = 9;
int trafficGreen = 10;
void setup() {
// Pins som skal være output, brukes bare i setup.
int outputPins[] = {
pedGreen,
pedRed,
trafficGreen,
trafficRed,
trafficYellow
};
// Antall output pins for LED
int outputCount = sizeof(outputPins) / sizeof(int);
// Sett alle output pins til å være output.
for(int i = 0; i < outputCount; i++)
{
pinMode(outputPins[i], OUTPUT);
}
pinMode(pedSwitch, INPUT_PULLUP);
}
/**
* Lengde hvor lenge hvert trafikklys, i millisekunder.
*/
int redLength = 5000;
int redYellowLength = 2000;
int greenLength = 10000;
int yellowLength = 2000;
/**
* Trafficstates er:
* - 0: Rødt lys (5 sek)
* - 1: Rødt + gult (2 sek)
* - 2: Grønt (10 sek)
* - 3: Gult (2 sek)
*/
int trafficState = -1;
int redState = 0;
int redYellowState = 1;
int greenState = 2;
int yellowState = 3;
/**
* Lengder som kan refereres basert array index
* Array index vil være det samme som "trafficState"
*/
int trafficLightLengths[] = {
// redState
redLength,
// redYellowState
redYellowLength,
// greenState
greenLength,
// yellowState
yellowLength
};
/**
* Antall millisekunder siden "trafficState" var sist endret.
*/
unsigned long lastStateChange = millis();
void loop() {
unsigned long currentTime = millis();
/**
* Starte med rødt lys.
* Denne "staten" vil bare være ved oppstart.
*/
if (trafficState == -1) {
digitalWrite(trafficRed, HIGH);
lastStateChange = currentTime;
trafficState = 0;
return;
}
int lightLength = trafficLightLengths[trafficState];
if (currentTime - lastStateChange >= lightLength)
{
trafficState++;
lastStateChange = currentTime;
/**
* Trafikklys er ferdig med syklus, tilbake til rødt.
*/
if (trafficState > 3)
{
trafficState = 0;
}
switch (trafficState)
{
// Rødt lys
case 0:
digitalWrite(trafficRed, HIGH);
digitalWrite(trafficYellow, LOW);
digitalWrite(trafficGreen, LOW);
break;
// Rødt + gult lys
case 1:
digitalWrite(trafficRed, HIGH);
digitalWrite(trafficYellow, HIGH);
digitalWrite(trafficGreen, LOW);
break;
// Grønt lys
case 2:
digitalWrite(trafficRed, LOW);
digitalWrite(trafficYellow, LOW);
digitalWrite(trafficGreen, HIGH);
break;
// Gult lys
case 3:
digitalWrite(trafficRed, LOW);
digitalWrite(trafficYellow, HIGH);
digitalWrite(trafficGreen, LOW);
break;
}
}
}