以下代码实现从串口2获取数据,如果有新的数据就写入test.txt文件。
# !/usr/bin/python
# encoding:utf-8
import serial
if __name__ == '__main__':
serial = serial.Serial('COM2','9600')
if serial.isOpen():
print('串口打开成功!\n')
f = open('./test.txt','w')
#pass
else :
print('串口打开失败!\n')
try:
getBytes=b''
while True:
count = serial.inWaiting()
if count > 0:
data = serial.read(count)
if data != getBytes:
#print(data);
f.write(data.decode('utf-8'))
f.write('\n')
getBytes=data
except KeyboardInterrupt:
if serial != None:
f.close()
serial.close()
需要使用以下命令安装serial
pip install pyserial