The Pico In MicroPython: PWM |
Written by Harry Fairhead & Mike James | ||||
Monday, 26 July 2021 | ||||
Page 3 of 3
Duty Cycle ResolutionIt seems as if you can set the duty cycle to a 16-bit value giving you 65535 different settings, however, this is only true in a few cases. The Pico’s PWM hardware implements the following algorithm: set GPIO line high for count in range(wrap): wait one clock cycle if count>level: set GPIO line low In other words, the frequency of the PWM signal depends on the value of wrap and the clock frequency and duty cycle depend on level. When you set the frequency of the PWM signal that you want, the software works out the best value for the clock frequency and wrap value. In an ideal wold the wrap would always be the maximum 16-bit value, 65535, but to achieve the desired frequency it often has to be less. Clearly you can only set the duty cycle between 0 and wrap and this can limit the precision that you can set. In other words, the frequency you select affects the accuracy of the setting of the duty cycle. In most cases the wrap value is large enough to ignore the problem, but sometimes it is important. MicroPython doesn’t provide any way to explicitly set or get the wrap value, but it is easy to add a function to get it: def pwm_get_wrap(sliceNo): Addr = 0x40050000 +0x10+0x14*sliceNo return (machine.mem32[Addr]) Problems with small wrap values usually occur at high frequencies. The reason is that the clock runs at 125MHz and so if you want a PWM frequency of say 30MHz then the wrap value has to be 4 and hence the duty cycle can only be 0,1,2,3. You can see that this is the case in the following example: pwm16 = PWM(Pin(16)) pwm16.freq(125000000//4) print(pwm_get_wrap(0)) pwm16.duty_u16(65535//2) You will see the wrap is 2 and if you examine the output using a logic analyzer you will see that the duty cycle is not 50%. At lower frequencies the duty cycle precision is usually close to 16-bits. Also notice that the duty cycle is always set as if it was a full 16-bit value and MicroPython scales this into the range that wrap makes possible. There is an additional effect related to the clock that you need to consider. The clock divider can be fractional and in this case the fractional division is achieved by varying the division between two integer dividers so that the average frequency is as requested. This can lead to jitter in the pulse positions. In Chapter But Not In This Extract
Summary
Programming the Raspberry Pi Pico/W In MicroPython Second EditionBy Harry Fairhead & Mike JamesBuy from Amazon. Contents
Also of interest: <ASIN:B0BR8LWYMZ> <ASIN:B0BL1HS3QD> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
||||
Last Updated ( Monday, 26 July 2021 ) |