如何确定Python回调的变量作用域?树莓派脉冲计数共享变量问题
问题原因
你在main()函数中对ictr执行赋值操作ictr=1时,没有提前声明global ictr,Python会默认将ictr识别为main()函数的局部变量,和回调函数中修改的全局ictr是两个完全独立的变量,因此主函数永远读不到回调修改的数值。同时你原有逻辑中sctr全程没有更新,始终为0,即便解决变量作用域问题也会出现逻辑卡死、打印计数永远为0的问题。
修正方案
- 在
main()函数内第一次操作ictr前添加global ictr声明,确保主函数和回调操作的是同一个全局变量 - 优化主函数的计数读取逻辑,删除不合理的死等判断,避免脉冲丢失、程序卡住
修正后的完整代码
import signal import sys import RPi.GPIO as GPIO import time iTP = 40 ictr=0 def signal_handler(sig, frame): GPIO.cleanup() print("\nOut of here!") sys.exit(0) def button_pressed_callback(channel): global ictr ictr+=1 def main(): global ictr # 新增:声明使用全局ictr print("Here we go!") GPIO.setmode(GPIO.BOARD) GPIO.setup(iTP, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(iTP, GPIO.FALLING, callback=button_pressed_callback, bouncetime=20) signal.signal(signal.SIGINT, signal_handler) while 1: time.sleep(1) print("====") if ictr == 0: continue print("busy") # 读取当前计数并清零全局计数器 current_cnt = ictr ictr = 0 print("Cnt={}".format(current_cnt)) main()
内容的提问来源于stack exchange,提问作者user2542266
相关产品推荐
相关产品推荐

