heatbed_pwm.cpp 10 KB

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