hzeller / rpi-rgb-led-matrix

Controlling up to three chains of 64x64, 32x32, 16x32 or similar RGB LED displays using Raspberry Pi GPIO
GNU General Public License v2.0
3.69k stars 1.17k forks source link

Free up pins on exit? #749

Closed clickworkorange closed 5 years ago

clickworkorange commented 5 years ago

At first I had trouble getting access to the unused GPIO pins with the Adafruit RGBMatrix "bonnet":

sudo python gpiotest.py
Traceback (most recent call last):
  File "gpio.py", line 34, in <module>
    GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
RuntimeError: No access to /dev/mem.  Try running as root!

This was solved by initialising GPIO before the RGBMatrix, but the code now only works once after a clean reboot; subsequent runs give:

sudo python gpiotest.py 
Traceback (most recent call last):
  File "gpiotest.py", line 21, in <module>
    GPIO.add_event_detect(button, GPIO.FALLING, bouncetime=200)
RuntimeError: Failed to add edge detection

It seems the RGBMatrix library leaves something behind on exit which prevents RPi.GPIO from adding the edge detection, since the same code with the RGBMatrix bits commented out can be re-run as many times as you like without this issue.

#!/usr/bin/env python

import sys
import RPi.GPIO as GPIO
from rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics

def start():
  print("Press CTRL-C to exit.")
  matrix.Clear()
  graphics.DrawText(matrix, font, 15, 14, green, "HELLO")

def stop(pin):
  print "Button pressed"
  matrix.Clear()
  graphics.DrawText(matrix, font, 8, 14, red, "GOODBYE")

# GPIO button
button = 19
GPIO.setmode(GPIO.BCM)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(button, GPIO.FALLING, bouncetime=200)
GPIO.add_event_callback(button, stop)

# RGBMatrix
options = RGBMatrixOptions()
options.rows = 32
options.cols = 64
options.chain_length = 1
options.parallel = 1
options.hardware_mapping = "adafruit-hat"
matrix = RGBMatrix(options = options)
font = graphics.Font()
font.LoadFont("fonts/7x14B.bdf")
red = graphics.Color(255, 0, 0)
green = graphics.Color(0, 255, 0)

try:
  start()
  while True:
    pass

except KeyboardInterrupt:
  GPIO.cleanup()
  sys.exit(0)
clickworkorange commented 5 years ago

Ok, I found the problem: a bug was introduced in the RPi.GPIO library v0.6.4, and subsequently fixed in 0.6.5, see https://github.com/RPi-Distro/python-gpiozero/issues/687 Removing the version shipped by Raspbian and installing via pip pulled in 0.6.5 and the issue went away. Odd that it only seemed to happen when the RGBMatrix library was used, but all's well that ends well - and your library is innocent!

hzeller commented 5 years ago

phew :)