Pulse Width Modulation: PWM in Arduino
The PWM is cool technique, in which we can Generate Analog Result means Analog Voltage by Digital Input. Arduino allows us to implement PWM in several ways.
The question is where it can be used; Let me give you one example. We have seen very often to turn LED/Light, ON - OFF. But then what, if we don't want LED to turn ON - OFF. Rather we want to precisely control the brightness of an LED/Light. And this can be done with Pulse Width Modulation Technique (i.e PWM). Using PWM we can control the Duty Cycle of a Clock. Which in result control brightness of an LED/Light.
Let's look at the picture where we have Clock Frequency in the form of Square Wave. This is Period and Pulse Width
Now Let's first understand Period of Clock (Tcycle). It is used to determine speed of our Microcontroller. This Clock is represented as Clock cycle, which is the amount of time between two pulses of an Oscillator. And then Duty cycle is an fraction of time in which signal or system is active.
Arduino PWM Frequency is 500 Hertz ~ 2 milliseconds
Note
This PWM in Arduino doesn't provide any control over Frequency. Even if the name os function is analogWrite(pin, dutyCycle), the output is a digital signal, often referred it as a Square Wave.
We have talked enough. Let’s implement it in live project. Where we will Change the Brightness of an LED Connected to Pin No: 9 of an Arduino Uno
Lets connect an RED LED to Arduino Pin 9, make sure we must conenct longer leg of LED connects to Pin No:9 and Shorter leg goes to Ground
STEP 1:
Let's write a code where we will just write 64 in a function analogWrite(9, 64) in the existing Sketch. With value 64. We will achieve 25% Duty Cycle means LED will glow 1/4th or Quarter of the Highest Brightness.
STEP 2:
Now as soon as we increase the value of Duty Cycle to 127 in analogWrite(9, 127) function. With value 127 we will achieve 50% Duty Cycle means 50% Brightness.
STEP 3:
Let's write value 191 in function analogWrite(9, 191). With this value will achieve 75% Duty Cycle means 75% of an Highest Brightness.
STEP 4:
Let's insert value 255 into function analogWrite(9, 255). With value 255 we will achieve 100% Duty Cycle means Highest possible Brightness.
STEP 5:
Finally Let's write 0 to function analogWrite(9, 0) to the existing Sketch. With value 0 we will achieve 0% Duty Cycle means LED will turn OFF.
So now we have seen how one can change Duty Cycle of a Clock and change the Brightness of an LED. Lets write a program which will vary duty cycle to generate variable voltage with an delay of every 1 Second. This will allows us to create dimming effect with LED.