2017-12-26 6 views
0

arduino 거리 센서에서 데이터를받는 python 스크립트 만들기. 나는 나노초마다 값을 받고있다. 이 값이 50 이상일 때마다 사용자에게 경고하고 싶습니다. (궁극적으로 알림 프로그램을 통해이 작업을 수행 할 예정이지만 현재는 경고를 인쇄하고 있습니다). 난 단지, 문이 더 이상 실행하지 않는 경우, 값이 THEN (50)에서 드롭 만> (50) 그 후, 30 초 번) 함수를 warn_user을 (실행하려는Python에서 일정 기간 동안 if 문을 한 번만 실행 하시겠습니까?

while 1:             # Keep receiving data 
    data = ser.readline()         # Getting data from arduino 
    value = [int(s) for s in data.split() if s.isdigit()] # Converting the Arduino ouput to only get the integer value 
    if value:            # Avoid empty values 
     distance = value[0]        # List to int 
      if distance > 50:        # If bigger than 50 cm, warn user. 
       warn_user()     

: 나는 다음을 다시. True/False 문을 사용하여 작업을 시도했지만 타이머가 잠자기 상태이지만 작동하지 않았습니다. 어떤 팁? 감사.

답변

2

프로그램 흐름을 제어하기 위해 좀 더 논리적 조건을 추가하기 만하면됩니다. 이런 식으로 뭔가가 작동합니다 :

from time import time 
warning_enabled = True 
time_of_warning = 0 

while 1: 
    data = ser.readline() 
    value = [int(s) for s in data.split() if s.isdigit()] 
    if value: 
     distance = value[0] 
      if distance > 50 and warning_enabled: 
       warn_user() 
       warning_enabled = False 
       time_of_warning = time() 
      if time() - time_of_warning > 30 and not warning_enabled and distance < 50: 
       warning_enabled = True 

는 이것이 않는 것은 경고 해고 된 마지막 시간을 추적하고 가능하면 두 번째 if 만 불을 만들기 위해 warning_enable 플래그를 사용한다는 것입니다.

건배

+0

이것은 완벽하게 작동합니다. 감사. – Jesse

2

당신이 필요 단지 당신이 당신의 목표를 달성하기 위해 무엇을 찾고 있는지 추적 다음 마지막 경고의 타임 스탬프와 거리가 추적중인 값 이하인지를.

import time 

distance_was_safe = True # tracks if distance went below specified range 
last_warned = 0   # tracks timestamp since last warning 

safe_distance = 50 # 50 cm 
warn_interval = 30 # 30 sec, warn no more than once every interval 


while True: 
    # Get data from Arduino. 
    data = ser.readline()         

    # Convert the Arduino output to only get the integer values. 
    value = [int(s) for s in data.split() if s.isdigit()] 

    # Avoid empty output. 
    if value:            
     # Get the first integer. 
     distance = value[0] 

      # If greater than safe zone, potentially warn the user. 
      if distance > safe_distance: 

       # Warn the user if distance was below range, 
       # and it has been enough time since the last warning. 
       if distance_was_safe and time.time() - last_warned > warn_interval: 
        distance_was_safe = False 
        last_warned = time.time() 
        warn_user() 

      else: 
       # Distance was less than warning distance, reset the flag. 
       distance_was_safe = True