Tech Talk with Gus 021 - Pulse Width Modulation - PWM

In this episode we’ll show you how PWM works and what it can be used for.

5 Likes

using System;
using System.Threading;
using GHIElectronics.TinyCLR.Pins;
using GHIElectronics.TinyCLR.Devices.Pwm;
using GHIElectronics.TinyCLR.Devices.Gpio;

namespace PWM
{
    public class Program
    {
        public static void Main()
        {
            GpioController Gpio = GpioController.GetDefault();
            GpioPin Button = Gpio.OpenPin(FEZPandaIII.GpioPin.Ldr0);
            Button.SetDriveMode(GpioPinDriveMode.InputPullUp);

            PwmController pwm = PwmController.GetDefault(); // Get the default PWM controller
            PwmPin MyPin = pwm.OpenPin(FEZPandaIII.PwmPin.Led1);
 
            double duty = 0.5;
            int frequency = 1000;
            double delta = 0.1;
 
            while (true)
            {
                while (Button.Read() == GpioPinValue.Low)
                {
                    MyPin.Stop();
                    pwm.SetDesiredFrequency(frequency);
                    MyPin.Start();
                    MyPin.SetActiveDutyCyclePercentage(0.5);
                    frequency += 200;
                    Thread.Sleep(100);
                }

                MyPin.Stop();
                pwm.SetDesiredFrequency(1000);
                MyPin.Start();
                MyPin.SetActiveDutyCyclePercentage(duty);
                duty += delta;

                if (duty >= 0.8 || duty <= 0.2)
                    delta *= -1;

                 Thread.Sleep(100);
            }
        }

    }

}