Search code examples
c#raspberry-piiot

C# .NET 5 Break beam sensor Raspberry PI


I've started a project to counter objects on a production line using a break beam sensor with the Raspberry Pi and Visual Studio Code. I have a python script that works however I need to do it in C#. Currently my code looks like this:

using System;
using System.Device.Gpio;
using System.Threading;

Console.WriteLine("Break Beam. Press Ctrl+C to end.");
int pin = 17;
using var controller = new GpioController();
controller.OpenPin(pin, PinMode.Output);
bool BeamBroke = true;
while (true)
{
   controller.Write(pin, ((BeamBroke) ? PinValue.High : PinValue.Low));
   Thread.Sleep(1000);
   BeamBroke = !BeamBroke;
}

The problem is that when I run this console app nothing is written about the beam being broken. There aren't any errors.


Solution

  • You will need to open an input pin with.

    controller.OpenPin(pin, PinMode.Input);
    

    You will also need to register a callback to be triggered upon pin value change.

    void BeamBreakCallback(object sender, PinValueChangedEventArgs pinValueChangedEventArgs)
    {
        BeamBroke = pinValueChangedEventArgs.ChangeType == PinEventTypes.Falling;
    }
    

    And then register the callback to be called whenever the input value changes on your input pin.

    controller.RegisterCallbackForPinValueChangedEvent(
        pin,
        PinEventTypes.Falling | PinEventTypes.Rising, // trigger on both rising and falling edges
        BeamBreakCallback
    );
    

    If you want to write anything to the console you'll need to add something to the callback

    void BeamBreakCallback(object sender, PinValueChangedEventArgs pinValueChangedEventArgs)
    {
        BeamBroke = pinValueChangedEventArgs.ChangeType == PinEventTypes.Falling;
    
        if (pinValueChangedEventArgs.ChangeType == PinEventTypes.Falling)
            Console.WriteLine("beam broken");
        else
            Console.WriteLine("beam unbroken");
    }
    

    Caveat I've made some assumptions about whether a falling or rising edge represents a broken beam.