dotnet / iot

This repo includes .NET Core implementations for various IoT boards, chips, displays and PCBs.
MIT License
2.16k stars 582 forks source link

Discussion around the introduction of a Pin class #1671

Closed raffaeler closed 1 year ago

raffaeler commented 3 years ago

Discussion started here on this code.

// set up for LED and pin
using GpioController led = new();
led.OpenPin(pin, PinMode.Output);

@krwq initially suggested that:

Feels like Pin class could be useful

I commented about the requirements that this would trigger to be able to share the pin with other controllers/pin:

@joperezr said that:

The original design of the API was very much considering that we wouldn't have a Pin class, so now that we have gone through that route, a lot would have to change if we were to introduce it now

One additional comment from me. What are the implications in using multiple GpioController instances? This could give the answer to the issues behind the abstraction needed to implement Pin.

/cc @Ellerbach @pgrawehr

pgrawehr commented 3 years ago

On the technical perspective: It is possible to create multiple GpioController instances, and as long as these don't use the same pins, there won't be any problems.* But if you use the same pin from different instances, the behavior is more or less undefined. It is highly recommended to use the Board class as root of your device instances, as it handles these cases nicely and throws exceptions if you try to reuse pins.

From an API perspective, adding a method Pin OpenPin(int pinNumber) to GpioController would be easy, but as already stated would also require updating many bindings to use this new object type instead of just numbers. While it may look nicer, I doubt it helps that much, since you actually rarely access pins directly. Most of the time, you'd use a binding that does this for you.

Maybe, to simplify some introductory scenarios, we should introduce a Led binding and a Button binding?

. * Note that this applies only to "native" Gpio Pins, i.e. on the Raspi, but not on external devices, such as an Arduino or an FT4222.

Ellerbach commented 3 years ago

In .NET nanoFramework, we do have a GpioPin. See https://github.com/nanoframework/System.Device.Gpio/blob/develop/System.Device.Gpio/GpioPin.cs

GpioController is the only one which can open or close pins, ownership is to it.

GpioPin is present for 2 reasons:

Now, all the Iot.Device bindings, like for .NET IoT only takes a GpioContoller or a null one in any binding constructor. Reason is for the ownership.

Ellerbach commented 1 year ago

Closing as done and merged!