2013-05-16 1 views
1

나는 Arduino를 사용하고 방패와 센서로부터 값을 얻고 있습니다. 또한 9600 포트를 청취하기 때문에 serial.println에 일부를 보냅니다. 9600 포트를 수신하고이 값을 txt에 저장합니다. 그런 다음이 값을 데이터베이스에 업로드하고 웹 서비스를 사용합니다.포트 9600 datas 주어진 시간에 저장

그러나 주어진 시간에 9600 포트를 저장할 수 없습니다. 왜냐하면 내가 파이썬 응용 프로그램을 닫지 않았기 때문에 결코 닫히지 않고 txt 파일을 저장하지 않기 때문입니다.

내 코드는 다음과 같습니다. 1 분마다 txt를 저장하고 싶습니다.

어떻게하면됩니까?

import serial 
ser = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1) 
while 1: 
    line = ser.readline() # read a '\n' terminated line 
    line2=line.decode("utf-8") 
    ths = open("/Users/macproretina//Desktop/data.txt", "a") 
    ths.write(line2) 
ser.close() 
+0

ser.close() 아래에 ths.close()를 추가하십시오. – reptilicus

+0

어떻게 시간을 정의 할 수 있습니까? – Gyepesto

+1

파일에 시작 시간을 기준으로 이름을 지정 하시겠습니까? 그것은 실행될 때마다 고유 한 파일 이름을 만듭니다. – reptilicus

답변

1

간단한 타이머를 사용하여 루프를 중지 할 수 있습니다. 컨텍스트 관리자가 정말 유용합니다 조금 리소스 관리를 청소.

import threading 
from contextlib import closing 
import serial 

continue_looping = True 
def stopper(): 
    global continue_looping 
    continue_looping = False 

timer = threading.Timer(60, stopper) 
timer.start() 

with open("/Users/macproretina/Desktop/data.txt", 'w') as out_file: 
    with closing(serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1)) as ser: 
     while continue_looping: 
      line = ser.readline() # read a '\n' terminated line 
      out_file.write(line.decode('utf-8') 
      out_file.flush() 

그것은 인해 시리얼 제한 시간에 약간 떨어져있을 수 있습니다. 필요할 경우를 대비하여 f.flush()으로 전화하면 파일에 출력이 기록됩니다.

+0

다음과 같이 오류가 발생합니다. 역 추적 (마지막으로 가장 최근 통화) : 파일 "serial-reader.py", 라인 (17), out_file.write (선)의 형식 오류가 : 바이트 – Gyepesto

+0

당신이 python3를 사용하고 있지 STR,해야합니까? –

+0

예. 그것을 변경해야합니까? – Gyepesto

관련 문제