Skip to main content
2 of 3
edited tags
m_goldberg
  • 108.1k
  • 16
  • 104
  • 259

Raspberry Pi GPIO operations with Mathematica

I started exploring GPIO operations on the RPi with Mathematica by following this brief tutorial which describes how to use DeviceWrite to cycle an LED on and off. A natural extension is to use DeviceRead to find the current value of the pin, and this seems to work as well.

I then thought I would attempt to translate some of the introductory python scripts that Adafruit uses to demonstrate basic features of the RPi GPIO programming. In particular, I am trying to operate a basic photocell for light monitoring. The meat of the python code is this:

def RCtime (RCpin):
        reading = 0
        GPIO.setup(RCpin, GPIO.OUT)
        GPIO.output(RCpin, GPIO.LOW)
        time.sleep(0.1)
 
        GPIO.setup(RCpin, GPIO.IN)
        # This takes about 1 millisecond per loop cycle
        while (GPIO.input(RCpin) == GPIO.LOW):
                reading += 1
        return reading

which I first attempted to replicate with:

lightMeasure[] := Module[{r = 0, pin = 23},
  DeviceWrite["GPIO", pin -> 0];
  While[(pin /. DeviceRead["GPIO", pin]) == 0, r++];
  r
  ]

This function always returns 0. Executing something like:

DeviceWrite["GPIO", 23->0];DeviceRead["GPIO",23]

Gives a value of 1, which I interpret to mean that the DeviceWrite operation is not discharging the capacitor. To test this, I removed the circuit from +3.3V and executed the code above, and the result is still 23 -> 1. I can then physically remove the capacitor, discharge it and return it to the circuit. Finally, I get 23->0.

Looking at the python code, I think that the GPIO.setup/GPIO.output/time.sleep commands force the pin low for 100 ms, allowing the capacitor to discharge. It does not look like the analogous Mathematica command, DeviceWrite is able to do the same thing.

Is there some way I might be able to force a Device object to maintain a set value for a given amount of time?

bobthechemist
  • 19.8k
  • 4
  • 56
  • 140