vsergeev / python-periphery

A pure Python 2/3 library for peripheral I/O (GPIO, LED, PWM, SPI, I2C, MMIO, Serial) in Linux.
MIT License
529 stars 139 forks source link

GPIO pins fail to connect on first try on RaspberryPi #10

Closed rwdavis513 closed 6 years ago

rwdavis513 commented 7 years ago

When initializing the pins on Raspbian, there appears to be a timing issue between the /sys/class/gpio/export and the write to /sys/class/gpio/direction

periphery/gpio.py

After running the code the first time the pin is added to the /sys/class/gpio/gpio{pin_number} list and therefore it works on the second try.

It looks like it could be addressed by adding a wait time if it fails. Here's a wrapper which addresses the issue:

for _ in range(number_of_attempts): try: gpio_pin = GPIO(pin, direction) break except GPIOError as e: if _+1 == number_of_attempts: raise e time.sleep(0.05) return gpio_pin

vsergeev commented 7 years ago

Interesting, and definitely possible if the underlying driver takes some time before the GPIO pin directory is exported. Looks like there should be a stat()/isdir() loop with a timeout on the pin directory before attempting to open its direction file.

vsergeev commented 6 years ago

Fixed in e6b905d.