Commit | Line | Data |
---|---|---|
11f8ba4e MM |
1 | #include "Pwm.h" |
2 | ||
3 | #include "nuts_bolts.h" | |
4 | ||
5 | #define PID_PWM_MAX 256 | |
6 | ||
7 | Pwm::Pwm() | |
8 | { | |
9 | _max = PID_PWM_MAX - 1; | |
10 | _pwm = -1; | |
11 | pin = this; | |
12 | } | |
13 | ||
14 | Pwm* Pwm::attach(Pin* new_pin) | |
15 | { | |
16 | pin = new_pin; | |
17 | return this; | |
18 | } | |
19 | ||
20 | void Pwm::pwm(int new_pwm) | |
21 | { | |
22 | _pwm = confine(new_pwm, 0, _max); | |
23 | } | |
24 | ||
25 | Pwm* Pwm::max_pwm(int new_max) | |
26 | { | |
27 | _max = confine(new_max, 0, PID_PWM_MAX); | |
28 | return this; | |
29 | } | |
30 | ||
31 | int Pwm::max_pwm() | |
32 | { | |
33 | return _max; | |
34 | } | |
35 | ||
36 | void Pwm::set(bool value) | |
37 | { | |
38 | _pwm = -1; | |
39 | pin->Pin::set(value); | |
40 | } | |
41 | ||
42 | uint32_t Pwm::on_tick(uint32_t dummy) | |
43 | { | |
44 | if ((_pwm < 0) || (_pwm >= PID_PWM_MAX)) | |
45 | return dummy; | |
46 | ||
47 | _sd_accumulator = confine(_sd_accumulator, -PID_PWM_MAX, PID_PWM_MAX << 1); | |
48 | ||
49 | if (_sd_direction == false) | |
50 | { | |
51 | _sd_accumulator += _pwm; | |
52 | if (_sd_accumulator >= (PID_PWM_MAX >> 1)) | |
53 | _sd_direction = true; | |
54 | } | |
55 | else | |
56 | { | |
57 | _sd_accumulator -= (PID_PWM_MAX - _pwm); | |
58 | if (_sd_accumulator <= 0) | |
59 | _sd_direction = false; | |
60 | } | |
61 | pin->Pin::set(_sd_direction); | |
62 | ||
63 | return dummy; | |
64 | } |