python判定串口已连接_python 自动识别并连接串口的实现

这个属于我项目中一个函数,跟大家分享一下我的思路及最终实现

在编写串口通信工具中,需要实现一个函数,自动找到对应com 口,并且连接该com口,保证后续通信正常

作为初始化过程的一部分。

思路

在win 设备管理器中,经常会出现多个com 口,但并不是每个com 口都是目标设备所链接的。

尝试打开每个com 口,输入enter 按键, 正确的com 口,会有ack log 返回,表明通信 正常

否则,没有任何log 返回,则判断为非目标设备所连接的com 口。

实现

4d6099272283f0bc2324abed101a57fe.png

尝试去打开所有com 口,然后发送enter, 如果在一段时间内有返回值,检查com 口收到的字节数,如果非零,则表明找到了对应的com 口。

完整测试代码如下:

import serial

import serial.tools.list_ports

import threading

import binascii

import time

from datetime import datetime

# default value

baunRate = 115200

is_read = False

is_write = False

write_buff = []

sys_buff = []

mSerial = None

callback = None

is_opened = 0

is_registed = 0

class SerialPort:

def __init__(self,port,buand):

self.port = serial.Serial(port,buand)

self.port.close()

if not self.port.isOpen():

self.port.open()

#the index of data_bytes for read operation,私有属性

#only used in read lines

self.__read_ptr = 0

self.__read_head = 0

#store all read bytes

# used in read date, read lines

self.__data_bytes = bytearray()

def port_open(self):

if not self.po

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值