What is PWM?PWM or Pulse Width Modulation is a way of varying power into a pulsing signal. This lets us control how much power is sent to the motors by controlling the pulse. When we talk about duty cycle we mean the portion of 'on' time compared to the total time; a low duty cycle corresponds to low power because the power is off for most of the time. Duty cycle is expressed in percent, 100% being fully on.
Writing The Code:In this example, we're going to use two microbits. One, the handset, is going to be used to send various commands to the other, the motor controller. We're going to simply send a different value from the handset based upon if button A, B, or both are pressed. We'll add an on shake command to bring the unit back to a stop. Using the MakeCode editor create this code or download it from the bottom of this guide.
In Action:As you can see from this quick video the buggy goes through three different speed cycles as we change the options on the handset.
New Blocks:To make it even easier for you, we've created an Extension that lets you add our Motor Driver blocks to the editor. Click cog in the top right of the Editor. The select Extensions from the menu and it will open the extensions window. Type Kitronik into the search bar and enter on your keyboard. The extensions window should now appear as shown below. Then, select the Motor Driver blocks and the code blocks will now be available to us in the editor. Note: We used this for our line following buggy in the video above but we did swap the wires around on the motor to set the buggy in line with "forward" in the block as can be seen below. Note: The blocks go from a speed of 0 to 100, not 1023 as with an analogue pin write. here and the motor controller code here.
©Kitronik Ltd – You may print this page & link to it, but must not copy the page or part thereof without Kitronik's prior written consent.