Step 3: Using PWM to control a DC motor
What's PWM, And Why Do We Need It?
To make a robot move smoothly, we'll often want to set a motor to go at speeds other than fully off or fully on. The easiest way to do this is to simply change the voltage that you apply to the motor.
However, most motor drivers and microcontrollers don't provide any way to do this- they're either 100% on or 100% off. To get around this, we can just turn it on and off really, really quickly- somewhere in the order of 20,000 times per second.
We can adjust how much time we spend on vs off, which is called duty cycle. We can refer to this as a percentage from 0-100. For example: 1ms on followed by 1ms off repeating would be 50% duty, 1.5ms on followed by 0.5ms off would be 75% duty, 2ms on followed by 0ms off would be 100% duty.
As we are controlling on and off times, we refer to this as "Pulse Width Modulation"
For this, we'll use the function generator on the VirtualBench. This allows us to generate repeating signals. In this case, we'll create a square wave between 3.3V and 0V- which is what we'll later generate from the microcontroller. To connect the function generator, use another probe like the one for the oscilloscope. They should also come with caps that allow a wire to be grabbed, which can then be plugged into your breadboard.
However, both the microcontroller and the function generator aren't able to run the motor- the motor needs up to 1000mA of current, and the microcontroller can only provide about 40mA. This is where a motor driver comes in- we can use it as an electrical switch, where our 3.3v signal can control our 6v motor. There will also be next to zero current needed to control the motor driver, so our microcontroller will be kept safe.