From Wikibooks, open books for an open world
Jump to navigation Jump to search

Pulse Width Modulation

[edit | edit source]

Pulse-Width Modulation (PWM) is the use of the length of an electric signal to represent a value, instead of a large bit pattern. To display the number 12, as an example, we could send a +5V pulse for 12 milliseconds (ms), instead of sending out the binary number 1100. The most common use for PWM is in digital servo motors, especially for robotics. However, other external devices operate using PWM communications as well. To send a PWM signal, instead of a regular binary signal, we use the PULSIN and PULSOUT commands.

Clock Speed

[edit | edit source]

The units of time for PULSIN and PULSOUT are 2 microseconds (μs). A microsecond is 10-6 seconds. For instance, if we sent a PULSOUT with a value of 25, we would have the length of the pulse be:

The reason why we make the conversion above from microseconds to milliseconds is that many devices display their requirements in terms of milliseconds. It is always important for the programmer to be able to convert between different units.


[edit | edit source]

To send a PWM signal, you need to specify the port and the amount of time. For example, to send a pulse on port 10 with a length of 4 microseconds, we would write:


Length Between Pulses

[edit | edit source]

The PAUSE function, as we have seen before, can be used to delay operation of the next command. When using PAUSE to insert a delay between PWM pulses, keep in mind that it uses milliseconds, not Microseconds (μs). Remember that PAUSE 1 takes the same amount of time as PULSOUT 12, 500.


[edit | edit source]

In a similar manner to sending a PWM signal, we can also read a PWM signal from an external device. We must specify which port we are reading from, and we must also provide a variable to receive the length of the pulse. For instance, if we wanted to read a PWM pulse on port 5, we could write:

MyByte VAR Byte
PULSIN 5, MyByte

Like with PULSOUT, the units of time are 2 μs.

One common device that uses PWM input like this is the Parallax ultrasonic sensor. These sensors return a pulse for a length of time equal to the amount of time it takes sound waves to travel to an object and bounce back. Using some simple arithmetic, if we know the speed of sound and if we know the amount of time, we can calculate the distance of the object.