Search code examples
pythonraspberry-piadafruitpn532

Writing/Reading from/to SPI on GPIO Interrupt failed with OSError: [Errno 9] Bad file descriptor


I am running an NFC Reader with an interrupt pin on my Raspberry Pi and I wrote a script to make it running. So far it works quite well but in some cases the SPI xfer crashes with an OSError: [Errno 9] Bad file descriptor

The whole SPI part happens when I receive the interrupt of the GPIO Pin - could that be an issue? I know that the code should not do too much on an interrupt and this may leads into this crash.

It is a littlebit too much code to share here but I am using the PN532 Chip with the Adafruit Library https://github.com/adafruit/Adafruit_Python_PN532 - I know it is deprecated but the difference to the C implementation is very small. I am running pn532.read_passive_target(timeout=0.2) to read the UID from that NFC Chip and make it scan for NFC Cards.

It works quite well until I do it too often. For testing I hold the card against the Reader over and over again without any delay. After around 5-10 times it crashes.

Any Ideas how to fix that? Sorry for that bad description of the error.


Solution

  • I refactored the code to not do any SPI work in the interrupt process. The Interrupt is now only handling states and nothing else, the main thread then checks the state and handles it. With that I was not able to reproduce the error again.

    Note: Do not use SPI on the interrupt process callback and use a state machine or python schedule.