-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathled.cpp
153 lines (123 loc) · 2.69 KB
/
led.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/*
*
*/
#include <Arduino.h>
#include <math.h>
#include "led.h"
extern uint32_t MILLIS;
/*
*
*/
led::led(int ledPin) {
ledInit(ledPin, 255);
}
/*
*
*/
led::led(int ledPin, int pwmMax) {
ledInit(ledPin, pwmMax);
}
void led::loop() {
switch (mode) {
case BLINK:
if (MILLIS - timer >= period >> 1) { // Quick divide by 2
timer = MILLIS;
duty = pwmMax * not duty;
}
break;
/*
* This is sorta complicated. We flash flashes times with
* the given period. Then we turn off for wait ms. Then we
* start over by resetting the timer.
*
* Uses the fact that odd multiples of half period should be ON
*/
case FLASH:
if (MILLIS - timer >= period * flashes + wait) {
timer = MILLIS;
} else if (MILLIS - timer >= period * flashes) {
duty = 0;
} else if ((2 * (MILLIS - timer) / period) % 2) {
duty = pwmMax;
} else {
duty = 0;
}
break;
/* "Breathe" by half the cycle of sin(x */
case PULSE:
duty = pwmMax * sin(fmod(MILLIS, period) * PI / (float)period);
break;
case SOLID:
duty = pwmMax;
break;
case STOP:
duty = 0;
break;
} // switch
analogWrite(ledPin, duty);
}
/*
*
*/
bool led::isOn() {
return duty > 0;
}
/*
* mode
* One of the led modes enumerated in led.h
*/
void led::setMode(mode_t mode) {
setMode(mode, this->period, this->flashes, this->wait);
}
/*
* mode
* One of the led modes enumerated in led.h
*
* period
* Period of cyclic functions, in milliseconds
*/
void led::setMode(mode_t mode, uint32_t period) {
setMode(mode, period, this->flashes, this->wait);
}
/*
* mode
* One of the led modes enumerated in led.h
*
* period
* Period of cyclic functions, in milliseconds
*
* flashes
* Number of flashes during FLASH mode
*
* wait
* Time between each burst of flashes in FLASH mode (ms)
*/
void led::setMode(mode_t mode, uint32_t period, int flashes, uint32_t wait) {
this->mode = mode;
this->period = period;
this->flashes = flashes;
this->wait = wait;
}
/*
*
*/
void led::setOff() {
setMode(STOP);
}
/*
*
*/
void led::phaseInvert() {
timer += period / 2;
}
void led::ledInit(int ledPin, int pwmMax) {
this->ledPin = ledPin;
this->pwmMax = pwmMax;
this->mode = mode;
this->period = 1000;
this->flashes = 1;
this->wait = 0;
timer = 0;
duty = 0;
pinMode(ledPin, OUTPUT);
}