1

I'm using the function callback from the python library pigpio to read the time where a raising edge happens and the time when a falling edge happens as well. With the code I have I can successfully print those values and when I do the math I can verify they're correct. However, I would like to subtract those values to get the pulse width. I tried declaring global variables so I could access them outside the functions but I haven't had any luck. When I run it, it seems that the variables are not acting as global but as local. I would appreciate some help! I'm new programming on Python!

#enter sudo pigpiod in terminal
import pigpio
import time


pi = pigpio.pi()
pi.set_mode(17,pigpio.INPUT)
pi.set_pull_up_down(17,pigpio.PUD_DOWN)


global falling
global raising
falling = 0
raising = 0


def cbf(gpio, level, tick):
    rising = tick
    print(rising)
    return 


def cbf1(gpio,level,tick1):
    falling = tick1
    print(falling)
    return 



cb1 = pi.callback(17, pigpio.RISING_EDGE, cbf)
cb2 = pi.callback(17, pigpio.FALLING_EDGE, cbf1)

while True:
    pass
3

You have global raising but in other places you refer to rising. You need to edit your script and use the same name throughout.

Pythons handling of globals in not intuitive.

When you assign to a global within a function you must declare the variable global in the function.

So use

def cbf(gpio, level, tick):
    global rising
    rising = tick
    print(rising)
    return 


def cbf1(gpio,level,tick1):
    global falling
    falling = tick1
    print(falling)
    return 

If you don't use global within the function the assignment will be to a local variable.

Annoyingly if you only read from a variable in a function you don't need the global statement, it will be assumed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.