为了简化复杂的项目,我有一个开关和一个按钮。我想要的是当按下按钮的两个位置时代码执行单独的功能。
所以我有两个文件。主文件设置了一些gpio和事件检测。另一个文件具有为按钮定义的回调函数。这是主文件:
import Adafruit_GPIO as GPIO
gpio = GPIO.get_platform_gpio()
global staff_mode
staff_mode = 0
Bg1 = 24
global audio_latch
audio_latch = 13
global image_latch
image_latch = 26
def staff_mode_audio():
staff_mode_write(0)
global staff_mode
if not gpio.input(audio_latch) and gpio.input(image_latch):
staff_mode=0;
print('You are in audio setup')
print(staff_mode)
def staff_mode_image():
staff_mode_write(1)
global staff_mode
if not gpio.input(image_latch) and gpio.input(audio_latch):
staff_mode=1;
print('You are in image setup')
gpio.add_event_detect(Bg1, GPIO.FALLING, callback = lambda x:grid_input(1,page_select,current_mode,staff_mode), bouncetime=debounce_time)
gpio.add_event_detect(image_latch, GPIO.FALLING, callback = lambda x: staff_mode_image(), bouncetime=300)
gpio.add_event_detect(audio_latch, GPIO.FALLING, callback = lambda x: staff_mode_audio(), bouncetime=300)
try:
while True:
signal.pause()
except KeyboardInterrupt:
gpio.cleanup()
关键是行image_select_write(' num')在另一个文件中定义,但基本上只是将0或1写入文本文件。下一个文件是:
def staff_mode_write(num):
file=open('image_select.txt', 'w')
file.write(str(num))
file.close()
def staff_mode_read():
file=open('image_select.txt', 'rt')
image_select=int(file.read())
file.close()
return image_select
def grid_input(grid_select,page_select,current_mode,staff_mode):
staff_mode = staff_mode_read()
if (staff_mode == 0):
#Do stuff
staff_mode_write(1)
else:
#Do other stuff
staff_mode_write(0)
因此回调函数grid_input读取文本文件以确定按钮应执行的功能。我试图使用全局变量来传递staff_mode的值。
这个解决方案有效,但很笨重。如何在不使用文本文件的情况下传达staff_mode的状态?谢谢!
答案 0 :(得分:0)
你确实应该能够使用全局。但是,您必须在任何地方声明全局。您无法在模块的顶部声明它。换句话说,您必须将grid_input
更改为此才能访问全局。
def grid_input(grid_select,page_select,current_mode):
global staff_mode
if (staff_mode == 0):
#Do stuff
else:
#Do other stuff
然而,你的代码的目标对我来说并不是那么清楚,所以我认为你可能会想出一个更好的方法。