LED PWM

In this project, the LED light is driven by PWM (Pulse Width Modulation). The LED will be brightened step by step.

There are two ways to use PWM, hardware and software. The hardware PWM can only be used on the GPIO that supports PWM. The software PWM can be used on almost every GPIO pins.

For Raspberry Pi 3B+, GPIO18 (pin 12) supports hardware PWM.

Hardware

Component List

  • Raspberry Pi 3 B+ x 1
  • GPIO Extension Board and GPIO Cable x 1 (If you do not have an Extension Board, connect Raspberry Pi and breadboard directly with jumper wires.)
  • Breadboard x 1
  • LED x 1
  • Resistor 220Ω x 1 (Check your LED specification for the correct resistor to use.)
  • Jumper Wire x 2

Schematic Diagram

Breadboard Diagram

Note that the longer leg of the LED needs to be connected to the positive. It is shown as bended leg in the diagram.

Program 1 Hardware PWM

Create a Console Project.

Add NuGet package Unosquare.Raspberry.IO.

Main Program: Program.cs

using Unosquare.RaspberryIO;
using Unosquare.RaspberryIO.Gpio;

...

GpioPin pin = Pi.Gpio.Pin01;    // pin 12, GPIO18
pin.PinMode = GpioPinDriveMode.PwmOutput;
pin.PwmRange = 100;

// turn brighter each step
for (int i = 0; i <= 5; i++)
{
    pin.PwmRegister = i * 20;
    System.Threading.Thread.Sleep(1000);
}

// turn darker each step
for (int i = 10; i >= 0; i--)
{
    pin.PwmRegister = i * 10;
    System.Threading.Thread.Sleep(500);
}

Program 2 Software PWM

Create a Console Project.

Add NuGet package Unosquare.Raspberry.IO.

Main Program: Program.cs

using Unosquare.RaspberryIO;
using Unosquare.RaspberryIO.Gpio;

...

GpioPin pin = Pi.Gpio.Pin01;    // pin 12, GPIO18

if (pin.IsInSoftPwmMode == false) 
{
    pin.StartSoftPwm(0, 100);
}

// turn brighter each step
for (int i = 0; i <= 5; i++)
{
    pin.SoftPwmValue = i * 20;
    System.Threading.Thread.Sleep(1000);
}

// turn darker each step
for (int i = 10; i >= 0; i--)
{
    pin.SoftPwmValue = i * 10;
    System.Threading.Thread.Sleep(500);
}

Unosquare.Raspberry.IO uses the pin number the same as Wiring Pi. At Terminal, enter command gpio readall to see pin number mapping. Use the number in column wPi to address the pins.

Leave a Reply