3 #include "nuts_bolts.h"
5 #define PID_PWM_MAX 256
11 _max
= PID_PWM_MAX
- 1;
15 void Pwm::pwm(int new_pwm
)
17 _pwm
= confine(new_pwm
, 0, _max
);
20 Pwm
* Pwm::max_pwm(int new_max
)
22 _max
= confine(new_max
, 0, PID_PWM_MAX
- 1);
23 _pwm
= confine( _pwm
, 0, _max
);
32 void Pwm::set(bool value
)
38 uint32_t Pwm::on_tick(uint32_t dummy
)
40 if ((_pwm
< 0) || (_pwm
>= PID_PWM_MAX
))
44 * Sigma-Delta PWM algorithm
46 * This Sigma-Delta implementation works by increasing _sd_accumulator by _pwm until we reach _half_ of max,
47 * then decreasing by (max - target_pwm) until we hit zero
49 * While we're increasing, the output is 0 and while we're decreasing the output is 1
51 * For example, with pwm=128 and a max of 256, we'll see the following pattern:
53 * 0 128 1 // after the add, we hit 256/2 = 128 so we change direction
54 * 128 -128 0 // after the add, we hit 0 so we change direction again
59 * with a pwm value of 192 (75%) we'll see this:
61 * 0 192 0 // after the add, we are beyond max/2 so we change direction
62 * 192 -64 1 // haven't reached 0 yet
63 * 128 -64 1 // haven't reached 0 yet
64 * 64 -64 1 // after this add we reach 0, and change direction
72 * with a pwm value of 75 (about 29%) we'll see this pattern:
95 * etcetera. This pattern has 6 '1's over a total of 21 lines which is on 28.57% of the time. If we let it run longer, it would get closer to the target as time went on
98 // this line should never actually do anything, it's just a sanity check in case our accumulator gets corrupted somehow.
99 // If we didn't check and the accumulator is corrupted, we could leave a heater on for quite a long time
100 // the accumulator is kept within these limits by the normal operation of the Sigma-Delta algorithm
101 _sd_accumulator
= confine(_sd_accumulator
, -PID_PWM_MAX
, PID_PWM_MAX
<< 1);
103 // when _sd_direction == false, our output is 0 and our accumulator is increasing by _pwm
104 if (_sd_direction
== false)
106 // increment accumulator
107 _sd_accumulator
+= _pwm
;
108 // if we've reached half of max, flip our direction
109 if (_sd_accumulator
>= (PID_PWM_MAX
>> 1))
110 _sd_direction
= true;
112 // when _sd_direction == true, our output is 1 and our accumulator is decreasing by (MAX - _pwm)
115 // decrement accumulator
116 _sd_accumulator
-= (PID_PWM_MAX
- _pwm
);
117 // if we've reached 0, flip our direction
118 if (_sd_accumulator
<= 0)
119 _sd_direction
= false;
121 Pin::set(_sd_direction
);