python 串口助手 简书_python 制作串口工具(二)

如需转载,请标明出处!

Beautiful is better than ugly.

前言

继续上一篇使用 python 制作串口工具(一),完成要实现的串口工具代码逻辑!

实现

最终效果:

642f631cec92

image

获取接入的 com 口

首先,我们先实现获取电脑当前所接入的串口,实现效果为:每次点击 Combo Box,就把当前电脑接入的串口号信息读取出来。所以我们需要对 Combo Box 这个控件进行重写,这里新建个 my_combobox.py,代码如下:

my_combobox.py

import serial

import serial.tools.list_ports

from PyQt5.QtWidgets import QComboBox

class My_ComBoBox(QComboBox):

def __init__(self, parent = None):

super(My_ComBoBox,self).__init__(parent)

# 重写showPopup函数

def showPopup(self):

# 先清空原有的选项

self.clear()

index = 1

# 获取接入的所有串口信息,插入combobox的选项中

port_list = self.get_port_list(self)

if port_list is not None:

for i in port_list:

self.insertItem(index, i)

index += 1

QComboBox.showPopup(self)# 弹出选项框

@staticmethod

# 获取接入的COM

def get_port_list(self):

try:

port_list = list(serial.tools.list_ports.comports())

for port in port_list:

yield str(port)

except Exception as err:

print("获取接入的串口设备出错!错误信息为:" + str(err))

上面实现了每次点击 Combo Box 后获取所有接入串口的信息。文件创建好并且写入代码后,我们需要引用它,回到 UI 文件 Ui_uart_tool_ui.py,引入刚才所写的内容,

642f631cec92

image

搞定后,我们重新运行下代码,看看效果吧,这里我调试的时候刚好旁边没有串口,所以直接拿了两个 Jlink 演示一下。(我现在是有空的时候写一点,所以偶尔所处的地方,装备有可能不齐全,请谅解!),效果如下:

642f631cec92

image

可以看到,每次点击,都会刷新获取一次当前接入的串口,无论是新接入还是刚断开的串口,在每次点击后都会刷新。

实现串口底层接口

上面完成后,我们先来实现串口底层的接口,后面在应用逻辑交互上,需要对串口底层操作,串口底层单独新建个文件来写, 这里我命名为 uart.py,部分代码如下:

uart.py

class Uart_Recv_Data_Thread(threading.Thread):

def __init__(self, cur_self, main_self):

super(Uart_Recv_Data_Thread, self).__init__()

self.cur_self = cur_self

self.thread = threading.Event()

self.main_self = main_self

def stop(self):

self.thread.set()

def stopped(self):

return self.thread.is_set()

def run(self):

while True:

time = ''

if self.stopped():

break

try:

if False =

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值