PWM Generation With Arduino and LED

by svraut29 in Circuits > Arduino

2558 Views, 1 Favorites, 0 Comments

PWM Generation With Arduino and LED

PWM generation with Arduino and LED.png

In Pulse Width Modulation (PWM), the width of pulse changes with time. In this tutorial, we will show you how to generate a pulse wave of any frequency/duty cycle and time period using Arduino and a LED. The LED is needed to view the result of pulse wave modulation.

Supplies

Make Circuit Connections

arduino-pwm-led.png

We need to connect LED to our Arduino board. Follow the above circuit diagram.

Install Required Library in Arduino IDE

smart-duty-cycling-arduino-library.png

Install the Smart_Duty_Cycling library in Arduino IDE

Go to Sketch > Include Library > Manage Libraries

Search "Smart Duty Cycling" and install.

Decide Your Approach

There are two ways in which you can generate PWM using the Smart Duty Cycling library. You can either provide frequency & duty cycle or time period to generate PWM.


When you use frequency and duty cycle, The frequency will decide the full-time period of the cycle, while the duty cycle will decide ON time and OFF time.

cycle.setFrequencyDutyCycle(1,0.5); // Frequency (in Hz)(float) and Duty Cycle (0.0-1.0)(float) respectively

Here, 0.5 means 50% duty cycle and so on... A frequency of 1 Hz means a time period of 1 second for the entire ON/OFF cycle. So in the above example, LED will glow for 0.5 seconds and be OFF for 0.5 seconds.


Apart from this, you can also directly provide ON time and OFF time in the form of wake and sleep periods respectively.

cycle.setWakeSleepPeriods(1000,4000); // Wake and Sleep period respectively in milliseconds

In this example, LED will glow for 1 second and be OFF for 4 seconds.


You need to decide which of the two approaches you want to use in your project. Anyone will do as per your requirement. In the tutorial, we will be using the frequency & duty cycle approach.

Upload Code to Arduino

Upload the below code to Arduino:

#include <smart_duty_cycling.h>


smart_duty_cycling cycle;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
cycle.setFrequencyDutyCycle(1,0.5); // Frequency (in Hz)(float) and Duty Cycle (0.0-1.0)(float) respectively
}

void loop() {
// put your main code here, to run repeatedly:
if(cycle.switchMode())
{
if(cycle.wake)
{
//Perform operation in Wake / Active / ON time
digitalWrite(13,HIGH);
}
else
{
//Perform operation in Sleep / Inactive / OFF time
digitalWrite(13,LOW);
}
}
}

Power on Your Arduino and See the Result!

Now, Power ON your Arduino and check the result. The LED should glow for 0.5 seconds and be OFF for 0.5 seconds.

You should also try different frequencies and duty cycles to explore further. Also, try the other approach given in step 3 with wake and sleep periods. You can also try to set frequency and duty cycle dynamically by taking input from the COM port and then changing the frequency and duty cycle.