我正在使用串口从微控制器获取数据。我的问题是,如果我告诉MCU每20毫秒发送一次数据,一些数据就会被破坏。例如,如果MCU发送sin(时间),你会期望所有数据的范围从-1到1,但我最终得到-1到100的范围(尽管我得到的大部分是在-1之间)到1)。不幸的是,我不会总是知道将要发送到计算机的内容,它可能会有很大差异,我需要能够相信python告诉我它正在接收的内容。 Python和串口是否有时间限制,如果是这样的话是什么?或者有没有办法更可靠地获取数据?我原本以为这只是一个问题,通信被分成几个块(MCU发送:xxxx | xxxx | xxxx和python读取xxx和x | xxxx |和xxxx),我已经处理过了。这是我用来从串口获取东西的代码:
import serial
import serial.tools.list_ports as det
import os
import datetime
from time import gmtime, strftime
import csv
######################### Functions #########################
## Find letter or character in string
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
## Find string in string
def find_str(s, char):
index = 0
if char in s:
c = char[0]
for ch in s:
if ch == c:
if s[index:index+len(char)] == char:
return index
index += 1
return -1
## Data saving
def DataSave(x, data):
#for i in range(x):
# DATALISTS[i].append( int( a[ find(buffer,"|")[i] : find(buffer,"|")[i+1] ] ) )
save = open(x, 'a')
save.write(data + "\n")
save.close()
######################### End #########################
######################### Filter #########################
First = True
Plot = True
NumberOfDataPoints = 1
currupt = []
TimeStamp = []
repeat = True
def GetDATA( file, path, port, baud ):
File = True
First = True
Plot = True
NumberOfDataPoints = 1
currupt = []
TimeStamp = []
repeat = True
try:
ser = serial.Serial(port, baud, timeout = 1)
except FileNotFoundError:
pass
while repeat:
x = ser.inWaiting()
# only read when something is in buffer
if x:
# convert serial.read to a string and remove b' and ' from the beginning and end, respectively
buffer = str (ser.read(x))
buffer = buffer[2:][:-1]
# Gets the time and appends to TimeStamp list
TimeStamp.append (datetime.datetime.now())
# Comfirm all data is received, if data is added to the buffer currupt
lineEnd = ['\\r','\\n']
# If there is no \r and/or \n in buffer, add buffer to currupt list
if not any(word in buffer for word in lineEnd) :
currupt.append(buffer)
# If \r and/or \n in buffer print buffer
# If there is data in currupt list, buffer becomes data in currupt + buffer
if any(word in buffer for word in lineEnd):
if len(currupt) is not 0:
buffer = ''.join(currupt) + buffer
del currupt[:]
# Remove \r and \n from buffer
while any(word in buffer for word in lineEnd):
for i in range(len(lineEnd)):
if lineEnd[i] in buffer:
buffer = buffer [: find_str(buffer, lineEnd[i] ) ]
if First:
buffer = ''
del TimeStamp[:]
First = False
Plot = True
# makes sure that there is something to write
if len(buffer) is not 0:
# Set of one datapoint
if '|' not in buffer:
if File is not False:
datafile=os.path.join(os.path.expanduser('~'), path, file)
DataSave(datafile, str(TimeStamp[0]) + '|' + buffer +'|')
#print(TimeStamp[0], buffer)
del TimeStamp[:]
## unused
def SetDataPoints(file, path, port):
GetDATA( file, path, port, False )
return NumberOfDataPoints