3

All of the examples that I've seen for reading GPIO in Mathematica use polling loops of the form:

While[ True,
  If[DeviceRead["GPIO", pin] ... (*meets some criterion*)
    (*do something*)
  ]
]

Instead of this, has anybody tried writing doing event-driven GPIO on Raspberry Pi?

For example, in the popular GPIOzero library in python, it is common to write things like:

from gpiozero import Button, LED
from signal import pause

button = Button(22)

def buttonAction1():
    print("Button is pressed")

def buttonAction2():
    print("Button is released")

button.when_pressed = buttonAction1
button.when_released = buttonAction2

pause()

where the functions get called when an event occurs (in this case, a button being pressed or released)

Are there any examples of event-driven GPIO in Mathematica?

I suppose this would be analogous to the notebook-related function EventHandler but for GPIO.

I suspect it has something to do with SessionSubmit and ContinuousTask but DeviceRead is a blocking function.

On the other hand, I suppose it might be possible to take advantage of Dynamic functionality (and more specifically DynamicModule) to implement something like this.

Joshua Schrier
  • 3,356
  • 8
  • 19
  • How the event (like voltage changes) on GPIO is defined on hardware level of Rapsberry? Do it has any pre-defined interrupts? I guess, there are not. The when_pressed method is realized as regular asking of the GPIO interface. – Rom38 Feb 18 '20 at 05:23

1 Answers1

3

My best attempt to "fake" a program style that looks like this using Dynamic:

isPressed[pin_Integer] := (# == 1) &@ First@DeviceRead["GPIO", pin] 

buttonAction[True] := With[{},
  DeviceWrite["GPIO", 17 -> 1];
  "Button is pressed"]

buttonAction[False] := With[{},
  DeviceWrite["GPIO", 17 -> 0];
  "Button is released"]

Dynamic[
 buttonAction@isPressed[22]]

In reality, I suspect it is doing polling behind the scenes....

Joshua Schrier
  • 3,356
  • 8
  • 19