2017-12-28 46 views
0

복잡한 프로젝트를 단순화하기 위해 하나의 스위치와 1 개의 푸시 버튼이 있습니다. 내가 원하는 것은 스위치의 두 위치 모두에 대해 버튼을 눌렀을 때 코드가 기능을 분리하도록하는 것입니다.add_event_detect를 사용하여 두 함수 사이에서 변수를 통신하는 방법은 무엇입니까?

두 파일이 있습니다. 주 파일은 일부 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() 

하여 라인 ('NUM')를 image_select_write 것을있는 열쇠는 다른 파일에 정의되어 있지만 기본적으로 그냥 텍스트 파일에 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

파이프를 사용하고 stdin 및 stdout을 사용하여 서로 다른 파일에서 데이터를 읽을 수 있지만 한 파일이 완전히 실행되어야합니다. – babygame0ver

+0

나는 이것이 무슨 뜻인지 정확히 모르겠습니다. 이것은 본질적으로 파일을 쓰는 것과 같지 않습니까? 파이썬 유형 솔루션에서 "포인터"를 더 생각하고있었습니다. –

+0

파이썬에는 포인터와 같은 개념이 없습니다. 그러나 원하는 경우 데이터를 교환하는 예를 파이프를 기반으로하는 두 개의 스크립트로 표시 할 수 있습니다. 어쩌면 그것은 당신을 위해 작동 할 것입니다. – babygame0ver

답변

0

실제로 전역을 사용할 수 있어야합니다. 그러나 어디서나 전역을 선언해야합니다. 모듈의 맨 위에서 선언 할 수는 없습니다. 즉, 글로벌에 액세스하려면 grid_input으로 변경해야합니다.

그러나 코드의 목표는 분명하지 않아서 나는 더 나은 접근 방법을 생각해 낼 수 있다고 생각합니다.