How to use arduino analogWrite function for PWM

with illustration on breadboard, proteus simulation and video

In this tutorial we explain how to use the arduino analogWrite function for PWM. Arduino UNO has six 3,5,6,9,10,11 PWM(Pulse Width Modulation) pins. To send out pulse width modulated signal we use the analogWrite function which is builtin function in Arduino. Pulse Width Modulation are digital pulses with varying duty cycle, pulses having different length. These can be emulated as analog signal by sending out PWM pulses of increasing duty cycle.

Before going to see how to use the arduino analogWrite function for PWM, you should know about the analogWrite function. The analogWrite() has the followng syntax;

analogWrite(pin number, value)

where the pin number is the PWM pin and value is from 0 to 255

Using for loop then we can then send PWM pulses having values from 0 to 256. This will then emulate analog signal.

This is useful for example when we want to control DC motor speed or when we want to glow the Light bulb or LED slowly higher.

To illustrate an example of using analogWrite() function in Arduino, we will write a program/sketch that glow on a LED slowly higher and then back to low.


The schematic required for this is shown below. A LED is connected to the 10th pin(PWM pin) and grounded via 220Ohm resistor.

how to use the arduino analogWrite function for PWM



The program is as follows.

In the above code, first we defined label LED for the PWM pin 10. Then in the setup function we declared the LED or pin 10 as our output because we will be sending out PWM pulses at this pin. After that in the loop function, we first increase the LED brightness by increasing the PWM values using the analogWrite function. We add delay of 10ms between each pulses. Once the loop has reached the maximum value, we decrease the LED brightness using another for loop and decreasing value of PWM.

Video showing how to use arduino analogWrite function for PWM

A short video illustrating this in breadboard is shown below.

video showing PWM in arduino

Now you should be able to use this concept on other similar works where PWM is required. In the next arduino tutorial we will show how you can use it for control speed of a DC motor which is very important and frequency used application of pulse width modulation.

Leave a Reply

Your email address will not be published. Required fields are marked *