Skip to content

GPIO.add_event_detect : does not properly handle lambda expressions #368

@gratefulfrog

Description

@gratefulfrog

In order to understand your system configuration better, please run:

sudo /opt/scripts/tools/version.sh

That command no longer exists.

I ran this:

$ more /etc/dogtag 
BeagleBoard.org Debian Bullseye IoT Image 2023-08-05

I have discovered a rather serious and unpleasant bug in the Adafruit_BBIO.GPIO.add_event_detect method.

When passing a lambda expression as the callback, the internals are not properly evaluated when they are contained in a closure...

In the code below, the internal parameter "pin" is not properly evaluated at the time of loop execution. It is in fact, overwritten at each iteration, which is not correct python semantics.

At execution, we see what happens when P8_13 and P8_15 trigger interrupts
The first 2 lines show that the value of "pin" is correct within the python environment of the loop

 ./bbio_gpio_bug.py
lambda channel : print(channel, P8_13) 
lambda channel : print(channel, P8_15)   
Main Process running...
P8_15 P8_15  ### this is correct
P8_13 P8_15  ### this is incorrect and should be P8_13 P8_13

This is the code:

#!/usr/bin/python3

import Adafruit_BBIO.GPIO as GPIO
import signal
import sys

def startup():
    for pin in ['P8_13','P8_15']:
        GPIO.setup(pin, GPIO.IN,pull_up_down = GPIO.PUD_UP)
        GPIO.add_event_detect(pin,
                              GPIO.BOTH,
                              lambda channel : print(channel,pin),
                              1)
        print(f'lambda channel : print(channel, {pin})')
            
    signal.signal(signal.SIGINT, lambda sig,frame: signal_handler())
    
    print('Main Process running...')
    signal.pause()

def signal_handler():
    GPIO.cleanup()
    print ('\nclean exit...')
    sys.exit(0)
    
if __name__ == '__main__':
    startup()    

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions