Pulse width modulation (PWM) allows you to get around the fact that a microcontroller can only send 0 or 5 volts (or “off” and “on”), and nothing in between. For example, you might want to send a voltage of 3.5 that is between 0 and 5, to give yourself finer control over an output, such as turning on a motor or servo at medium speed. You might also want to send the changing signals of an analog input, such as how hard I press my finger onto a sensor. That type of mechanical force can have a much finer range of values than just “on” or “off”.
PWM lets you cut these corners by “faking” a varying voltage while doing two things: very quickly sending regular pulses of 0 and 5 volts to a pin on your microcontroller, and changing the width of the pulses (or the amount of time spent at 0 or 5 volts). The pulse width is the amount of time the pin is high. The duty cycle is the ratio of taking half of the time it takes to go from off to on to off again. And the period is the total time if takes to go from off to on to off again.
Applications of Pulse Width Modulation
Here is an example of using PWM to vary the brightness of an LED. In this circuit, the Arduino’s digital pin 3 using its ability to send different PMW (pulse width modulation signals) to dim or brighten an LED. I’m using analogWrite() to send the LED on pin 3 a duty cycle of 100, then 2, then 0.
DC Motor Speed Control
Below you can see I’ve used a potentiometer to change the speed of the motor. This is done by sending the analogRead value of the potentiometer, mapping it to a value the motor can accept, and then sending that new value by using analogWrite to the motor.
I set up a servo motor but wasn’t able to get it to move using only digitalWrite or analogWrite(), and without an analog input such as a force resistor or potentiometer.
Question: Why is this?
You can see my progress by adding the servo library in the Servo Lab.
Question: For now, I am curious how I would send the voltage suggested in the reading? It says to send a 5-volt, positive pulse between 1 and 2 milliseconds (ms) long, repeated about 50 times per second. What does this look like written as code?
I was able to set up a piezo using the suggested code set to a certain frequency. I struggled for a while because the speaker I bought from Tinkersphere was not working… but the piezo did work!
Question: To confirm, is it the changing period of a PWM signal that changes the frequency coming out of a speaker?