Lessons |
Pulse Width Modulation (PWM)PWM stands for pulse width modulation, and it’s important because your Arduino controller can’t actually output analog voltages. It can output only digital voltages, either 0 or 5 volts. To output analog voltages, the computer uses averaged voltages, flipping between 0 and 5 volts at an appropriate interval to simulate the desired output voltage.
Pulse Width Modulation, is a technique for getting analog results with digital means. Its a fancy way of allowing you to change the ratio in the amount of time a signal is on vs the time that it is off. Digital control is used to create a square wave, a signal switched between on and off. This on-off pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends off. The duration of "on time" is called the pulse width. To get varying analog values, you change, or modulate, that pulse width. If you repeat this on-off pattern fast enough with an LED for example, the result is as if the signal is a steady voltage between 0 and 5v controlling the brightness of the LED. Duty CycleA duty cycle is the percentage of one period in which a signal is active. A period is the time it takes for a signal to complete an on-and-off cycle.
In the graphic above, the green lines represent a regular time period. A call to analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (on half the time) for example.
Example SketchAgain we can use the fading sketch to demonstrate the concept of PWM.
* Fade This example shows how to fade an LED on pin 9 using the analogWrite() function. This example code is in the public domain. */ int led = 9; // the pin that the LED is attached to int brightness = 0; // how bright the LED is int fadeAmount = 5; // how many points to fade the LED by // the setup routine runs once when you press reset: void setup() { // declare pin 9 to be an output: pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { // set the brightness of pin 9: analogWrite(led, brightness); // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = fadeAmount ; } // wait for 30 milliseconds to see the dimming effect delay(30); } |