想要吧接收标志位‘S'和结束标志位’E'去掉,开始结束换成40秒的时间 uart_r = serial.Serial("COM8", 115200) # Wait the beging flag print("Please send char S to start receiving:") uart_r.timeout = None read_byte = uart_r.read(1) print("received: ", read_byte) while (b'S' != read_byte): read_byte = uart_r.read(1) print("received: ", read_byte) print("Receiving data: ") received_bytes_list = [] uart_r.timeout = 60 read_byte = uart_r.read(1) while (None != read_byte) and (b'E' != read_byte): print(".", end="") received_bytes_list.append(read_byte.decode()) read_byte = uart_r.read(1) if (None == read_byte): print("Warning: timeout!") if (b'E' == read_byte): print("Received endflag!") # Save to Excel file # print('received_bytes_list: ', received_bytes_list) received_bytes = ''.join(received_bytes_list) # print('received_bytes: ', received_bytes) received_data = received_bytes.split() # print('received_data:', received_data) received_data_8 = [received_data[i: i + 8] for i in range(0, len(received_data), 8)] # print('received_data_8:', received_data_8) df = pd.DataFrame(columns=['0', '1', '2', '3', '4', '5', '6', '7']) for i, str in enumerate(received_data_8): print("Write to excel line :", i, str) if (len(str) < 8): print("Populate data.") str += [0] * (8 - len(str)) df.loc[i] = str # .insert(0, 'none') df.to_excel('%s.xlsx' % TIME) uart_r.close()
时间: 2024-03-05 08:54:18 浏览: 86
好的,你可以这样修改代码:
```python
uart_r = serial.Serial("COM8", 115200)
print("Receiving data: ")
received_bytes_list = []
start_time = time.time()
while (time.time() - start_time <= 40):
read_byte = uart_r.read(1)
if read_byte != b'':
print(".", end="")
received_bytes_list.append(read_byte.decode())
if len(received_bytes_list) == 0:
print("Warning: timeout!")
else:
print("Received data successfully!")
# Save to Excel file
received_bytes = ''.join(received_bytes_list)
received_data = received_bytes.split()
received_data_8 = [received_data[i: i + 8] for i in range(0, len(received_data), 8)]
df = pd.DataFrame(columns=['0', '1', '2', '3', '4', '5', '6', '7'])
for i, str in enumerate(received_data_8):
print("Write to excel line:", i, str)
if (len(str) < 8):
print("Populate data.")
str += [0] * (8 - len(str))
df.loc[i] = str
df.to_excel('%s.xlsx' % TIME)
uart_r.close()
```
这段代码去掉了接收标志位'S'和结束标志位'E',而是通过计时器来控制接收时间,时间为40秒。如果在规定时间内没有接收到任何数据,将会输出“Warning: timeout!”的提示信息;如果接收到数据,将会输出“Received data successfully!”的提示信息,并将数据保存到Excel文件中。
阅读全文