Search code examples
c#androidxamarinxamarin.androidandroid-things

Android Things with Xamarin Issue with IGpioCallback


I'm just starting with Android Things with Xamarin, and I've already successfully turned on a LED, but I'm having trouble to detect a push button input. I think the problem is the "RegisterGpioCallback" in the code below, but I'm not sure and really don't know how to fix it. Can somebody help me?? This is the code I'm using:

public class BlinkActivity : Activity
{
    private IGpio gpio;
    private IGpio button;
    private IGpioCallback mButtonCallback;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        this.mButtonCallback = mButtonCallback; 
        PeripheralManager peripheralManager = PeripheralManager.Instance;
        gpio = peripheralManager.OpenGpio("BCM17");
        gpio.SetDirection(Gpio.DirectionOutInitiallyLow);
        gpio.Value = false;
        button = peripheralManager.OpenGpio("BCM4");
        button.SetDirection(Gpio.DirectionIn);
        button.SetEdgeTriggerType(Gpio.EdgeNone);
        button.RegisterGpioCallback(new Handler(), mButtonCallback);
        base.OnCreate(savedInstanceState);
        Task.Run(() =>
        {
            if (mButtonCallback.OnGpioEdge(button) == true)
            {
                gpio.Value = !gpio.Value;
            }
        });
    }
}

Solution

  • You need to actually implement the IGpioCallback interface so the com.google.android.things.pio library can make a "call back" into your application when the value of the GPIO changes.

    Assign the RegisterGpioCallback to the actual object instance that has implemented the interface, in the following example, that will be on the Activity.

    public class BlinkActivity : Activity, IGpioCallback
    {
        ~~~~
        button.RegisterGpioCallback(new Handler(), this);
        ~~~~
    
        // remove the Task.Run block
    
        public OnGpioEdge(Gpio gpio)
        {
            Log.Debug("SO", gpio.Value.ToString());
        }
    
        ~~~~
    }