heatbed_pwm.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #include <avr/io.h>
  2. #include <avr/interrupt.h>
  3. #include "io_atmega2560.h"
  4. // All this is about silencing the heat bed, as it behaves like a loudspeaker.
  5. // Basically, we want the PWM heating switched at 30Hz (or so) which is a well ballanced
  6. // frequency for both power supply units (i.e. both PSUs are reasonably silent).
  7. // The only trouble is the rising or falling edge of bed heating - that creates an audible click.
  8. // This audible click may be suppressed by making the rising or falling edge NOT sharp.
  9. // Of course, making non-sharp edges in digital technology is not easy, but there is a solution.
  10. // It is possible to do a fast PWM sequence with duty starting from 0 to 255.
  11. // Doing this at higher frequency than the bed "loudspeaker" can handle makes the click barely audible.
  12. // Technically:
  13. // timer0 is set to fast PWM mode at 62.5kHz (timer0 is linked to the bed heating pin) (zero prescaler)
  14. // To keep the bed switching at 30Hz - we don't want the PWM running at 62kHz all the time
  15. // since it would burn the heatbed's MOSFET:
  16. // 16MHz/256 levels of PWM duty gives us 62.5kHz
  17. // 62.5kHz/256 gives ~244Hz, that is still too fast - 244/8 gives ~30Hz, that's what we need
  18. // So the automaton runs atop of inner 8 (or 16) cycles.
  19. // The finite automaton is running in the ISR(TIMER0_OVF_vect)
  20. // 2019-08-14 update: the original algorithm worked very well, however there were 2 regressions:
  21. // 1. 62kHz ISR requires considerable amount of processing power,
  22. // USB transfer speed dropped by 20%, which was most notable when doing short G-code segments.
  23. // 2. Some users reported TLed PSU started clicking when running at 120V/60Hz.
  24. // This looks like the original algorithm didn't maintain base PWM 30Hz, but only 15Hz
  25. // To address both issues, there is an improved approach based on the idea of leveraging
  26. // different CLK prescalers in some automaton states - i.e. when holding LOW or HIGH on the output pin,
  27. // we don't have to clock 62kHz, but we can increase the CLK prescaler for these states to 8 (or even 64).
  28. // That shall result in the ISR not being called that much resulting in regained performance
  29. // Theoretically this is relatively easy, however one must be very carefull handling the AVR's timer
  30. // control registers correctly, especially setting them in a correct order.
  31. // Some registers are double buffered, some changes are applied in next cycles etc.
  32. // The biggest problem was with the CLK prescaler itself - this circuit is shared among almost all timers,
  33. // we don't want to reset the prescaler counted value when transiting among automaton states.
  34. // Resetting the prescaler would make the PWM more precise, right now there are temporal segments
  35. // of variable period ranging from 0 to 7 62kHz ticks - that's logical, the timer must "sync"
  36. // to the new slower CLK after setting the slower prescaler value.
  37. // In our application, this isn't any significant problem and may be ignored.
  38. // Doing changes in timer's registers non-correctly results in artefacts on the output pin
  39. // - it can toggle unnoticed, which will result in bed clicking again.
  40. // That's why there are special transition states ZERO_TO_RISE and ONE_TO_FALL, which enable the
  41. // counter change its operation atomically and without artefacts on the output pin.
  42. // The resulting signal on the output pin was checked with an osciloscope.
  43. // If there are any change requirements in the future, the signal must be checked with an osciloscope again,
  44. // ad-hoc changes may completely screw things up!
  45. // 2020-01-29 update: we are introducing a new option to the automaton that will allow us to force the output state
  46. // to either full ON or OFF. This is so that interference during the MBL probing is minimal.
  47. // To accomplish this goal we use bedPWMDisabled. It is only supposed to be used for brief periods of time as to
  48. // not make the bed temperature too unstable. Also, careful consideration should be used when using this
  49. // option as leaving this enabled will also keep the bed output in the state it stopped in.
  50. ///! Definition off finite automaton states
  51. enum class States : uint8_t {
  52. ZERO_START = 0,///< entry point of the automaton - reads the soft_pwm_bed value for the next whole PWM cycle
  53. ZERO, ///< steady 0 (OFF), no change for the whole period
  54. ZERO_TO_RISE, ///< metastate allowing the timer change its state atomically without artefacts on the output pin
  55. RISE, ///< 16 fast PWM cycles with increasing duty up to steady ON
  56. RISE_TO_ONE, ///< metastate allowing the timer change its state atomically without artefacts on the output pin
  57. ONE, ///< steady 1 (ON), no change for the whole period
  58. FALL, ///< 16 fast PWM cycles with decreasing duty down to steady OFF
  59. FALL_TO_ZERO ///< metastate allowing the timer change its state atomically without artefacts on the output pin
  60. };
  61. ///! Inner states of the finite automaton
  62. static States state = States::ZERO_START;
  63. bool bedPWMDisabled = 0;
  64. ///! Fast PWM counter is used in the RISE and FALL states (62.5kHz)
  65. static uint8_t slowCounter = 0;
  66. ///! Slow PWM counter is used in the ZERO and ONE states (62.5kHz/8 or 64)
  67. static uint8_t fastCounter = 0;
  68. ///! PWM counter for the whole cycle - a cache for soft_pwm_bed
  69. static uint8_t pwm = 0;
  70. ///! The slow PWM duty for the next 30Hz cycle
  71. ///! Set in the whole firmware at various places
  72. extern unsigned char soft_pwm_bed;
  73. /// fastMax - how many fast PWM steps to do in RISE and FALL states
  74. /// 16 is a good compromise between silenced bed ("smooth" edges)
  75. /// and not burning the switching MOSFET
  76. static const uint8_t fastMax = 16;
  77. /// Scaler 16->256 for fast PWM
  78. static const uint8_t fastShift = 4;
  79. /// Increment slow PWM counter by slowInc every ZERO or ONE state
  80. /// This allows for fine-tuning the basic PWM switching frequency
  81. /// A possible further optimization - use a 64 prescaler (instead of 8)
  82. /// increment slowCounter by 1
  83. /// but use less bits of soft PWM - something like soft_pwm_bed >> 2
  84. /// that may further reduce the CPU cycles required by the bed heating automaton
  85. /// Due to the nature of bed heating the reduced PID precision may not be a major issue, however doing 8x less ISR(timer0_ovf) may significantly improve the performance
  86. static const uint8_t slowInc = 1;
  87. ISR(TIMER0_OVF_vect) // timer compare interrupt service routine
  88. {
  89. switch(state){
  90. case States::ZERO_START:
  91. if (bedPWMDisabled) return; // stay in the OFF state and do not change the output pin
  92. pwm = soft_pwm_bed << 1;// expecting soft_pwm_bed to be 7bit!
  93. if( pwm != 0 ){
  94. state = States::ZERO; // do nothing, let it tick once again after the 30Hz period
  95. }
  96. break;
  97. case States::ZERO: // end of state ZERO - we'll either stay in ZERO or change to RISE
  98. // In any case update our cache of pwm value for the next whole cycle from soft_pwm_bed
  99. slowCounter += slowInc; // this does software timer_clk/256 or less (depends on slowInc)
  100. if( slowCounter > pwm ){
  101. return;
  102. } // otherwise moving towards RISE
  103. state = States::ZERO_TO_RISE; // and finalize the change in a transitional state RISE0
  104. break;
  105. // even though it may look like the ZERO state may be glued together with the ZERO_TO_RISE, don't do it
  106. // the timer must tick once more in order to get rid of occasional output pin toggles.
  107. case States::ZERO_TO_RISE: // special state for handling transition between prescalers and switching inverted->non-inverted fast-PWM without toggling the output pin.
  108. // It must be done in consequent steps, otherwise the pin will get flipped up and down during one PWM cycle.
  109. // Also beware of the correct sequence of the following timer control registers initialization - it really matters!
  110. state = States::RISE; // prepare for standard RISE cycles
  111. fastCounter = fastMax - 1;// we'll do 16-1 cycles of RISE
  112. TCNT0 = 255; // force overflow on the next clock cycle
  113. TCCR0B = (1 << CS00); // change prescaler to 1, i.e. 62.5kHz
  114. TCCR0A &= ~(1 << COM0B0); // Clear OC0B on Compare Match, set OC0B at BOTTOM (non-inverting mode)
  115. break;
  116. case States::RISE:
  117. OCR0B = (fastMax - fastCounter) << fastShift;
  118. if( fastCounter ){
  119. --fastCounter;
  120. } else { // end of RISE cycles, changing into state ONE
  121. state = States::RISE_TO_ONE;
  122. OCR0B = 255; // full duty
  123. TCNT0 = 254; // make the timer overflow in the next cycle
  124. // @@TODO these constants are still subject to investigation
  125. }
  126. break;
  127. case States::RISE_TO_ONE:
  128. state = States::ONE;
  129. OCR0B = 255; // full duty
  130. TCNT0 = 255; // make the timer overflow in the next cycle
  131. TCCR0B = (1 << CS01); // change prescaler to 8, i.e. 7.8kHz
  132. break;
  133. case States::ONE: // state ONE - we'll either stay in ONE or change to FALL
  134. OCR0B = 255;
  135. if (bedPWMDisabled) return; // stay in the ON state and do not change the output pin
  136. slowCounter += slowInc; // this does software timer_clk/256 or less
  137. if( slowCounter < pwm ){
  138. return;
  139. }
  140. if( (soft_pwm_bed << 1) >= (255 - slowInc - 1) ){ //@@TODO simplify & explain
  141. // if slowInc==2, soft_pwm == 251 will be the first to do short drops to zero. 252 will keep full heating
  142. return; // want full duty for the next ONE cycle again - so keep on heating and just wait for the next timer ovf
  143. }
  144. // otherwise moving towards FALL
  145. state = States::ONE;//_TO_FALL;
  146. state=States::FALL;
  147. fastCounter = fastMax - 1;// we'll do 16-1 cycles of RISE
  148. TCNT0 = 255; // force overflow on the next clock cycle
  149. TCCR0B = (1 << CS00); // change prescaler to 1, i.e. 62.5kHz
  150. // must switch to inverting mode already here, because it takes a whole PWM cycle and it would make a "1" at the end of this pwm cycle
  151. // COM0B1 remains set both in inverting and non-inverting mode
  152. TCCR0A |= (1 << COM0B0); // inverting mode
  153. break;
  154. case States::FALL:
  155. OCR0B = (fastMax - fastCounter) << fastShift; // this is the same as in RISE, because now we are setting the zero part of duty due to inverting mode
  156. //TCCR0A |= (1 << COM0B0); // already set in ONE_TO_FALL
  157. if( fastCounter ){
  158. --fastCounter;
  159. } else { // end of FALL cycles, changing into state ZERO
  160. state = States::FALL_TO_ZERO;
  161. TCNT0 = 128; //@@TODO again - need to wait long enough to propagate the timer state changes
  162. OCR0B = 255;
  163. }
  164. break;
  165. case States::FALL_TO_ZERO:
  166. state = States::ZERO_START; // go to read new soft_pwm_bed value for the next cycle
  167. TCNT0 = 128;
  168. OCR0B = 255;
  169. TCCR0B = (1 << CS01); // change prescaler to 8, i.e. 7.8kHz
  170. break;
  171. }
  172. }