如何停止键盘输入上的串行读取

时间:2018-12-08 17:13:59

标签: python arduino

所以我试图制作一个程序来读取Arduino的串行端口。一切正常,但问题是我想停不下来。我的arduino一直在发送数据(没关系),但是我的脚本仅在读取100行之后(根据我的设置)才停止。在这100次读数之后,它将列表保存到csv文件中。我该如何提前停止,例如在终端中输入“停止”或“退出”后仍然保存我的数据? ctrl + c只是停止我的脚本而不保存。

我的代码:

import serial
import csv
import re
import pandas as pd
import time

portPath = "/dev/cu.usbmodem1411"       
baud = 9600                     
timeout = 5     # Seconds
filename = time.strftime("%Y%m%d") + "_shieldv1_water_data.csv"
max_num_readings = 100

def create_serial_obj(portPath, baud_rate, tout):
return serial.Serial(portPath, baud_rate, timeout = tout)

def read_serial_data(serial):
serial.flushInput()     # buffer flush

serial_data = []
readings_left = True
timeout_reached = False

while readings_left and not timeout_reached:
    serial_line = serial.readline()
    if  serial_line == '':
        timeout_reached = True
    else:  
        serial_data.append(serial_line.decode('utf-8'))
        if len(serial_data) == max_num_readings:
            readings_left = False

return serial_data

def save_to_csv(data, filename):
with open(filename, 'w') as csvfile:
    csvwrite = csv.writer(csvfile, delimiter = '\n')
    csvwrite.writerow(data)


serial_obj = create_serial_obj(portPath, baud, timeout)

print("Reading serial data...")
serial_data = read_serial_data(serial_obj)

print("Saving to csv...")
save_to_csv(serial_data, filename)

print("Saved.")

1 个答案:

答案 0 :(得分:0)

您可以使用下面的check_input()函数。将其放入循环中,如果返回值不为None,则从中中断。 poll()检查标准输入缓冲区中是否有换行符,然后读取它们。

import select,sys,time

def check_input():

    po= select.poll()   
    po.register(sys.stdin.fileno(), select.POLLIN)  
    events= po.poll(0) 
    if events:
        for fno,ev in events:     
            if fno == sys.stdin.fileno():  
                return(input())
    return None

# testing:
if __name__ == "__main__":
   while True:
        s=check_input()
        if s:
            print("From keyboard:",s)
            break
        time.sleep(1)