Unsigned Long Currentmillis Millis If (Currentmillis - Previouscars Duration (I) ) (
Unsigned Long Currentmillis Millis If (Currentmillis - Previouscars Duration (I) ) (
com/10178/arduinotraffic-light-system/
2 int trafficLights1[] = {2,3,4,5}; // red, yellow, green,
pedestrians led pins
3 int trafficLights2[] = {6,7,8,9}; // red, yellow, green,
pedestrians led pins
4 int situations = 4;
5 int duration[] = {8000,3000,10000,3000}; // duration of each
situation
6 long previousCars = 0;
7 long previousPeds = 0;
8 long interval = 300;
//blink interval for pedestrians
9 int ledState = LOW;
10 int state;
11 int i = 0;
12
13 void setup()
14 {
15
for(int i = 0; i < 4; i++) {
16
pinMode(trafficLights1[i], OUTPUT);
17
pinMode(trafficLights2[i], OUTPUT);
18
}
19
Serial.begin(9600);
20 }
21
22 void loop()
23 {
24
unsigned long currentMillis = millis();
25
if(currentMillis - previousCars < duration[i]) {
26
situation(i);
27
} else {
28
previousCars = currentMillis;
29
if(i >= situations) {
30
i = 0;
31
} else {
32
i++;
33
}
34
}
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
}
void activateTrafficLight1(String lights, int pedestrians)
{
for(int x = 0; x < 3; x++)
{
if(lights[x] == '0') state = LOW;
if(lights[x] == '1') state = HIGH;
digitalWrite(trafficLights1[x], state);
}
if(pedestrians == 1) {
blinkPed(trafficLights1[3]);
} else {
digitalWrite(trafficLights1[3], LOW);
}
}
void activateTrafficLight2(String lights, int pedestrians)
{
for(int x = 0; x < 3; x++)
{
if(lights[x] == '0') state = LOW;
if(lights[x] == '1') state = HIGH;
digitalWrite(trafficLights2[x], state);
}
if(pedestrians == 1) {
blinkPed(trafficLights2[3]);
} else {
digitalWrite(trafficLights2[3], LOW);
}
}
void situation(int i)
{
switch(i){
case 0:
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 void blinkPed(int ped) {
90
unsigned long currentMillis = millis();
91
if(currentMillis - previousPeds > interval) {
92
previousPeds = currentMillis;
93
if (ledState == LOW)
94
ledState = HIGH;
95
else
96
ledState = LOW;
97
digitalWrite(ped, ledState);
98
}
99 }