Pulse width modulation (PWM) for variable speed control #
Here is some sample CircuitPython code that uses PWM to run a motor first at full speed, then at half speed, and then at quarter speed. Note that we have to import the pwmio library to run this code, and we have to initiate a pin as a pwmio.PWMOut pin.
import board
import pwmio
import time
control_pin = pwmio.PWMOut(board.D6, frequency=500, duty_cycle=0)
# creates a new object called “control_pin” that will hold all
# the information about sending out
# pulse-width modulation at pin D6
while True:
control_pin.duty_cycle = 65535
time.sleep(3)
control_pin.duty_cycle = 32770
time.sleep(3)
control_pin.duty_cycle = 16400
time.sleep(3)
Frequency: This CircuitPython parameter refers to the number of voltage pulse initiations per second.
- Set this to 500 for the KB2040, because its main processing chip can handle outputting that many cycles per second.
Duty_cycle: This CircuitPython parameter refers to the length of each voltage pulse. It’s the duration of time, within each very brief control cycle, at which the voltage is ON or HIGH (i.e., 3.3 V).
- For the KB2040, a duty cycle value of 65535 corresponds to the voltage being turned on for 100% of each very short PWM cycle, which means the motor gets 100% of the voltage available to it.
- Because 50% of 65535 is about 32770, a duty cycle of about 32770 corresponds to the voltage being set high for 50% of the cycle, or the motor getting about 50% of the voltage available to it. The motor will spin at half speed.
- A duty cycle of about 6550 corresponds to the voltage being set high for 10% of the cycle, or the motor getting about 10% of the voltage available to it. The motor would spin at 10% speed IF that is enough voltage to overcome its internal friction (you’ll probably find that it’s not enough voltage for the motor to turn at all).
The plot below depicts three PWM cycles, and x represents the duration of each cycle (the inverse of the PWM frequency). It should be set to 500 for the KB2040.
From top to bottom, the duty cycles shown would spin the motor at approximately:
- 50% speed (corresponding to
control_pin.duty_cycle = 32770in CircuitPython for the KB2040) - 75% speed (corresponding to
control_pin.duty_cycle = 49151in CircuitPython for the KB2040) - 25% speed (corresponding to
control_pin.duty_cycle = 16384in CircuitPython for the KB2040)
