-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrafficlight.cpp
113 lines (90 loc) · 2.41 KB
/
trafficlight.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdexcept>
#include "pico/stdlib.h"
#include "trafficlight.h"
TrafficLight::TrafficLight(uint redPin, uint yellowPin, uint greenPin, LedType ledType)
{
setUpForStandardLights(redPin, yellowPin, greenPin);
setLedType(ledType);
}
TrafficLight::TrafficLight(uint redCrossingPin, uint greenCrossingPin, LedType ledType)
{
setUpForCrossingLights(redCrossingPin, greenCrossingPin);
setLedType(ledType);
}
TrafficLight::TrafficLight(uint redPin, uint yellowPin, uint greenPin, uint redCrossingPin, uint greenCrossingPin, LedType ledType)
{
setUpForStandardLights(redPin, yellowPin, greenPin);
setUpForCrossingLights(redCrossingPin, greenCrossingPin);
setLedType(ledType);
}
void TrafficLight::setUpForStandardLights(uint redPin, uint yellowPin, uint greenPin)
{
setPin(Light::Red, redPin);
setPin(Light::Yellow, yellowPin);
setPin(Light::Green, greenPin);
_hasLights = true;
}
void TrafficLight::setUpForCrossingLights(uint redPin, uint greenPin)
{
setPin(Light::RedCrossing, redPin);
setPin(Light::GreenCrossing, greenPin);
_hasCrossingLights = true;
}
void TrafficLight::setLedType(LedType ledType)
{
_ledType = ledType;
}
void TrafficLight::turnAllLightsOff()
{
turnLightsOff(Light::All);
}
void TrafficLight::turnLightsOn(Light lights)
{
setLightsState(lights, true);
}
void TrafficLight::turnLightsOff(Light lights)
{
setLightsState(lights, false);
}
void TrafficLight::setLightsState(Light lights, bool on)
{
for (auto pinMapping : _lightPinMap) {
if ((lights & pinMapping.first) != 0 && hasValidPin(pinMapping.first)) {
gpio_put(pinMapping.second, shouldInvertOnOff() ? !on : on);
}
}
}
void TrafficLight::setPin(Light light, uint pin)
{
_lightPinMap[light] = pin;
initPin(pin);
}
bool TrafficLight::hasLights() const
{
return _hasLights;
}
bool TrafficLight::hasCrossingLights() const
{
return _hasCrossingLights;
}
bool TrafficLight::hasValidPin(Light light) const
{
return _lightPinMap.find(light) != _lightPinMap.end();
}
uint TrafficLight::getPin(Light light) const
{
auto foundPin = _lightPinMap.find(light);
if (foundPin != _lightPinMap.end()) {
return foundPin->second;
}
return 0;
}
void TrafficLight::initPin(uint pin)
{
gpio_init(pin);
gpio_set_dir(pin, GPIO_OUT);
}
bool TrafficLight::shouldInvertOnOff() const
{
return _ledType == LedType::CommonAnode;
}