-
Notifications
You must be signed in to change notification settings - Fork 1
/
softpwm.cpp
88 lines (73 loc) · 1.39 KB
/
softpwm.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
#include "softpwm.h"
#include "Arduino.h"
#define OFF (0)
#define ON (1)
void softpwm_reset(struct softpwm_state *state)
{
state->phase = IMPULSE_IDLE;
state->start = 0;
state->value = 0.0f;
}
uint8_t softpwm_step( struct softpwm_state *state,
const struct softpwm_params *params,
float x)
{
uint8_t value = OFF;
uint32_t impulse_duration;
uint32_t pause_duration;
if (x > 1.0f)
x = 1.0f;
else if (x < 0.0f)
x = 0.0f;
impulse_duration = x * (params->period * 1000.0f);
if (impulse_duration < (uint32_t(params->duration_min) * 1000))
{
state->phase = IMPULSE_IDLE;
value = OFF;
goto done;
}
pause_duration = (1.0f - x) * (params->period * 1000.0f);
if (pause_duration < (uint32_t(params->duration_min) * 1000))
{
state->phase = IMPULSE_IDLE;
value = ON;
goto done;
}
if (state->phase == IMPULSE_IDLE)
{
state->start = millis();
state->phase = IMPULSE_HIGH;
}
if (state->phase == IMPULSE_HIGH)
{
if (millis() > state->start + impulse_duration)
{
state->start = millis();
state->phase = IMPULSE_LOW;
value = OFF;
goto done;
}
else
{
value = ON;
goto done;
}
}
if (state->phase == IMPULSE_LOW)
{
if (millis() > state->start + pause_duration)
{
state->start = millis();
state->phase = IMPULSE_HIGH;
value = ON;
goto done;
}
else
{
value = OFF;
goto done;
}
}
done:
return value;
}