As part of working through adding OrangePi support to Home Assistant, Alastair and I decided to change to a different GPIO library for OrangePi to avoid the requirement for Home Assistant to have access to /dev/mem.
I just realised that I hadn’t posted updated examples of how to do GPIO output with the new library. So here’s a quick post about that.
Assuming that we have an LED on GPIO PA7, which is pin 29, then the code to blink the LED would look like this with the new library:
import OPi.GPIO as GPIO
import time
# Note that we use SUNXI mappings here because its way less confusing than
# board mappsings. For example, these are all the same pin:
# sunxi: PA7 (the label on the board)
# board: 29
# gpio: 7
GPIO.setmode(GPIO.SUNXI)
GPIO.setwarnings(False)
GPIO.setup('PA7', GPIO.OUT)
while True:
GPIO.output('PA7', GPIO.HIGH)
time.sleep(1)
GPIO.output('PA7', GPIO.LOW)
time.sleep(1)
The most important thing there is the note about SUNXI pin mappings. I find the whole mapping scheme hugely confusing, unless you use SUNXI and then its all fine. So learn from my fail people!
What about input? Well, that’s not too bad either. Let’s assume that you have a button in a circuit like this:
The to read the button the polling way, you’d just do this:
import OPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.SUNXI)
GPIO.setwarnings(False)
GPIO.setup('PA7', GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
while True:
print('Reading...')
if GPIO.input('PA7') == GPIO.LOW:
print('Pressed')
else:
print('Released')
time.sleep(1)
Let’s pretend it didn’t take me ages to get that to work right because I had the circuit wrong, ok?
Now, we have self respect, so you wouldn’t actually poll like that. Instead you’d use edge detection, and end up with code like this:
import OPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.SUNXI)
GPIO.setwarnings(False)
GPIO.setup('PA7', GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def event_callback(channel):
print('Event detected: %s' % GPIO.input('PA7'))
GPIO.add_event_detect('PA7', GPIO.BOTH, callback=event_callback, bouncetime=50)
while True:
time.sleep(1)
So there ya go.
2 thoughts on “Updated examples for OrangePi GPIOs”