【发布时间】:2021-11-22 02:52:24
【问题描述】:
我正在通过串行通信收集数据,下面是我的代码。我的计划是每次收到数据时,数据都应该以不同的名称记录在不同的文件中(文件名无关紧要,我希望它是不同的文件,所以我使用了时间和数据模块)。 但我面临的问题是,一旦在 UART 端口上接收到数据,文件就开始收集数据(我监控文件大小),一两秒后,文件大小回到零字节。我尝试了不同的方法来解决它,但我认为我在这里犯了一些我找不到的愚蠢错误。
import serial
import time
import datetime
import os
ser = serial.Serial(port='/dev/serial0', baudrate=115200, parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS, rtscts=1,)
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%dT%H.%M.%S") + ".txt")
while (True):
if (ser.inWaiting() > 0):
text_file = open(outputFilePath, 'w')
# read the bytes and convert from binary array to ASCII
data_str = ser.read(ser.inWaiting()).decode('ascii')
# print the incoming string without putting a new-line
# ('\n') automatically after every print()
#print(data_str, end='')
text_file.write(data_str)
text_file.flush()
text_file.close()
time.sleep(0.01)
基本上,我有大约 900 kB 的数据,这些数据由微控制器生成并通过 UART 传输到 Raspberry Pi。数据将每天多次发送到 RP(例如 50 次),每次发送这 900kB 数据时,我想将其保存在不同的文件中(所以 50 个文件,每个文件具有不同的名称和 900 kB数据的)。 另一件事是我没有偏好使用数据/时间保存文件名。如果我可以用 1.txt、2.txt 等保存……那也很好。我无法访问 RP,因此我需要在自动脚本中使用它。
【问题讨论】:
标签: raspberry-pi serial-port pyserial