Search code examples
c#windows-10-iot-corepwm

Windows 10 Iot Core app crashes if I try to open a PWM pin


I want to open a PWM pin to my buzzer. But If I try to call the pwmController.OpenPin(6) method, the app crashes with an System.Runtime.InteropServices.SEHException.

I had already double checked the sample sources like the ms-iot-samples. But I cannot see what my problems are.

An idea was that some permissions are missing, but if I try to add for exmaple <iot:Capability Name="lowLevelDevices" />, I cannot longer build the application.

Source

private PwmPin buzzerPin;
private PwmController pwmController;

public RainbowHAT()
{
    // ... do something else
    InitAsync();
}

private async void InitAsync()
{
    Logger.Log(this, "Init");

    // Setup PWM controller.
    if (LightningProvider.IsLightningEnabled)
    {
        LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
    }

    var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
    if (pwmControllers == null || pwmControllers.Count < 2)
    {
        throw new OperationCanceledException("Operation canceled due missing GPIO controller");
    }

    pwmController = pwmControllers[1];
    pwmController.SetDesiredFrequency(50);

    // Setup buzzer
    buzzerPin = pwmController.OpenPin(13); <-- CRASH
    buzzerPin.SetActiveDutyCyclePercentage(0.05);
    buzzerPin.Start();
}

I also tried the following tip to reduce the min required Windows version, but this does not help, too.


Solution

  • PWM Controller needs Lightning support. So you need to set the controller driver as Direct Memory Mapped Driver. Here is a sample about PWM on Raspberry Pi.

    enter image description here

    You also need to modify the code as following:

        private async void InitAsync()
        {
            Logger.Log(this, "Init");
    
            // Setup PWM controller.
            if (LightningProvider.IsLightningEnabled)
            {
                var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
                if (pwmControllers == null || pwmControllers.Count < 2)
                {
                    throw new OperationCanceledException("Operation canceled due missing GPIO controller");
                }
    
                pwmController = pwmControllers[1];
                pwmController.SetDesiredFrequency(50);
    
                // Setup buzzer
                buzzerPin = pwmController.OpenPin(13);
                buzzerPin.SetActiveDutyCyclePercentage(0.05);
                buzzerPin.Start();
            }
        }