Pulse Width Modulation is a technique used to simulate an analog signal by using a digital signal.
So how does PWM work? The objective is that we need to convert a square wave which oscillates between HIGH (1) and LOW (0), to a continuously varying signal. Pulse Width Modulation allows us to vary how much time the signal is HIGH (1) to get a wave that closely resembles an analog signal. We can change the proportion of time the signal is HIGH compared to when it is LOW over a consistent time interval. By doing this, the width of the wave (or pulse) can be changed. Hence, this process is called Pulse Width Modulation (where modulation refers to the continuously changing width of the pulse). The duration of HIGH (1) time is called the pulse width.
To describe the amount of HIGH time, we use the concept of ‘duty cycle’. Duty cycle is expressed as a percentage. The percentage duty cycle specifically describes the percentage of time a digital signal is HIGH over an interval of time. This period is the inverse of the frequency of the waveform. For example, if the digital signal spends 25% of the time in the HIGH state and the other 75% in the LOW state, we would say the digital signal has a duty cycle of 25%. The graph below illustrates three scenarios.
If you look at your Arduino Uno board, you can see some digital I/O pins with the symbol ‘~’ marked next to it. This symbol indicates that it is a PWM pin. There are six such pins on the Arduino Uno, which are digital pins 3,5,6,9,10 & 11. The use of these pins to generate PWM signals is hence a type of DAC ( digital to analog converter).
PWM is used in a variety of applications particularly for control. It can be used to control the brightness of LEDs, angle of servo motors, speed of DC motors, etc.
Let us construct a simple circuit to demonstrate the use of PWM pins to brighten and fade an LED gradually.
- Components required:
1) Arduino Uno
2) LED
3) Breadboard
4) 220 ohm resistor
5) Connecting wires
- Circuit:
Note: Connect the anode (the longer, positive leg) of your LED to digital output pin 9 on your board through a 220 ohm resistor. Connect the cathode (the shorter, negative leg) directly to ground.
CODE:
int led = 9; // the PWM pin the LED is attached to int brightness = 0; // how bright the LED is int fadeAmount = 10; // how many points to fade the LED by void setup() { // declare pin 9 to be an output: pinMode(led, OUTPUT); } 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 50 milliseconds to see the dimming effect delay(50); }
No comments:
Post a Comment