准备着手写一个串口工具,当前编程环境,并没有办法接好下位机平台,需要模拟出一个串口,不断发送信息,方便调试串口工具。
1.win 下载虚拟串口
https://sourceforge.net/projects/com0com/files/latest/download
下载安装完成后,会在设备管理器中新增两个com。
这两个串口是互相接通的,一个com 可以当作上位机,一个com可以当作下位机
2.python 实现向一个串口内写数据,另一个串口内接受数据
#!/usr/bin/python
# -*-coding: utf-8 -*-
import serial
import serial.tools.list_ports
import threading
import time
from datetime import datetime
#列出所有当前的com口
port_list = list(serial.tools.list_ports.comports())
port_list_name = []
class SerialPort:
def __init__(self,port,buand):
self.port = serial.Serial(port,buand)
self.port.close()
if not self.port.isOpen():
self.port.open()
def port_open(self):
if not self.port.isOpen():
self.port.open()
def port_close(self):
self.port.close()
def send_data(self):
#date = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
while True:
date = datetime.now().strftime('%H:%M:%S.%f')[:-3]
print("send:",date)
self.port.write(date.encode())
time.sleep(1)
def read_data(self):
while True:
count = self.port.inWaiting()
if count > 0:
rec_str = self.port.read(count)
print("receive:",rec_str.decode())
def show_all_com():
if len(port_list) <= 0:
print("the serial port can't find!")
else:
for itms in port_list:
port_list_name.append(itms.device)
if __name__ == '__main__':
baunRate = 115200
print("1.list all com")
show_all_com()
print(port_list_name)
print("2.open write port ",port_list_name[0])
serialPort_w = port_list_name[0]
mSerial_w = SerialPort(serialPort_w,baunRate)
print("3.start write thread")
t1 = threading.Thread(target=mSerial_w.send_data)
t1.setDaemon(True)
t1.start()
print("4.open read port ",port_list_name[1])
serialPort_r = port_list_name[1]
mSerial_r = SerialPort(serialPort_r,baunRate)
print("5.start read thread")
t2 = threading.Thread(target=mSerial_r.read_data)
t2.setDaemon(True)
t2.start()
#do something else, make main thread alive there
while True:
time.sleep(10)
代码流程:
- 启动一个子线程,打开com3 ,将当前时间作为数据,写入到串口
- 启动另一个子线程,打开com4,读取串口中写入的数据
注意点:
1.串口中写入的数据为byte类型,str to byte 需要 encode(), 默认使用utf-8
2.从串口中读取的数据,也是byte类型,byte to str 需要decode(), 默认使用utf-8
3.虚拟串口是两个设备直接的通信 ,需要在com3 中写 ,在com4中读,笔者犯过一个低级错误,com3写,也在com3中读,不会出任何数据
4.子线程设置为守护线程,主线程退出,子线程随之退出,后续可以在主线程中处理读取到的数据