Type Here to Get Search Results !

Pulse Width Modulation (PWM) In Arduino Project For Analog Input Output

In the previous step we just turned the leds on/off rapidly using the digitalwrite() function, it seems that we can define the level of brightness of an led. By adjusting the amount of time between each led on and off states using pulse-width modulation (pwm).

Pwm can be used to create the illusion of an led being on at different levels of brightness. By turning the led on and off very rapidly, at around 500 cycles per second. The brightness we perceive in our eyes is actually determined by the amount of time the digital output pin is on, versus the amount of time it is off. This is also called "duty cycle". Because our eyes can’t see flickers faster than 50 cycles per second, so the led appears to have a constant brightness.


This method is also used for driving dc motors, (something that we will see in next courses) at variable speeds, by switching the motor on and off very quickly. So the logic is simple, the greater the duty cycle, meaning  the longer the pin is on compared to off in each cycle, the greater the perceived brightness of the led connected to the digital output pin.

As we mentioned before, only specific digital pins support pwm and they are marked on the arduino board with a tilde (~) mark beside the number and that’s is the reason i decided at the first place to use specific pin numbers for connected our leds. So i will be able to use the pwm option in this step. Now the next question will be how we are using the pwm method in our program ? In the sketch. A duty cycle is the percentage of one period in which a signal is on/active. We can provide the percentage of a duty cycle as input parameter to a function called: "analogwrite()" the function analogwrite() will allow us to access the pulse width modulation harware on the arduino microcontroller. Now the basic syntax for this function is with two parameters:
  1. The first parameter is the pin number, which can only include one of the pins which support pwm and the second parameter is the duty cycle expressed as an 8-bit integer number ranging between the values of 0 and 255.
  2. The value 0 corresponds to off or 0% duty cycle and 255 is basically full on or 100% duty cycle any value in between these two endpoints provides a corresponding duty cycle that will approximate an analog output. 60% duty cycle means the signal is on 60% of the time but off 40% of the time.
  3. In our case, we will use the pwm as part of the analogwrite function to emulate the needed led brightness.


Post a Comment

0 Comments