You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WxPython定时事件中读取Arduino计数变量:求串口模块及示例

Arduino与WxPython串口通信实现方案

我之前做过类似的WxPython+Arduino项目,刚好能给你一套可行的方案,分两端来说明:

Arduino端:自带Serial库即可

不需要额外安装任何模块,Arduino原生的Serial库完全能满足需求。核心思路是把统计到的零件数量以带结束符的字符串形式发送(比如换行符),这样Python端能准确识别每次的数值。

Arduino示例代码

// 模拟零件计数变量
int partCount = 0;

void setup() {
  // 初始化串口,波特率要和Python端一致,这里用9600
  Serial.begin(9600);
  // 实际项目中替换成你的传感器触发逻辑
}

void loop() {
  // 模拟零件计数逻辑(实际替换为机器的计数触发代码)
  partCount++;
  // 发送计数,用println会自动添加换行符,方便Python端读取
  Serial.println(partCount);
  // 模拟生产间隔,实际根据机器节奏调整
  delay(1000);
}

Python(WxPython)端:使用pyserial库

WxPython负责GUI渲染和定时事件调度,串口通信需要依赖pyserial库——这是Python生态中最常用的串口处理工具。

第一步:安装依赖

打开终端执行:

pip install pyserial wxpython

WxPython示例代码

import wx
import serial
from serial.tools.list_ports import comports

class PartCountFrame(wx.Frame):
    def __init__(self, parent, title):
        super().__init__(parent, title=title, size=(300, 150))
        
        # 初始化串口(支持自动检测Arduino端口,也可手动指定)
        self.ser = None
        self.init_serial()
        
        # 创建显示计数的GUI控件
        self.count_label = wx.StaticText(self, label="当前零件数量:0", pos=(50, 50), size=(200, 30))
        font = wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
        self.count_label.SetFont(font)
        
        # 设置定时事件:每1秒读取一次串口数据
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.update_count, self.timer)
        self.timer.Start(1000)  # 间隔1000毫秒(1秒)
        
        self.Show()

    def init_serial(self):
        # 自动查找Arduino串口,手动指定可替换为serial.Serial("COM3", 9600, timeout=1)
        ports = comports()
        for port in ports:
            if "Arduino" in port.description:
                try:
                    self.ser = serial.Serial(port.device, 9600, timeout=1)
                    print(f"成功连接串口:{port.device}")
                    break
                except Exception as e:
                    print(f"串口连接失败:{str(e)}")
        if not self.ser:
            print("未找到Arduino设备,请检查连接")

    def update_count(self, event):
        if self.ser and self.ser.is_open:
            try:
                # 读取串口一行数据(对应Arduino的println输出)
                data = self.ser.readline().decode('utf-8').strip()
                if data.isdigit():
                    count = int(data)
                    # 更新GUI文本
                    self.count_label.SetLabel(f"当前零件数量:{count}")
            except Exception as e:
                print(f"读取串口数据失败:{str(e)}")

if __name__ == "__main__":
    app = wx.App()
    PartCountFrame(None, "零件生产计数器")
    app.MainLoop()

关键注意事项

  • 两端的波特率必须完全一致(示例中都是9600),否则会出现乱码或读取失败。
  • Python端要做好异常处理,比如Arduino突然断开连接的情况,避免程序崩溃。
  • 如果自动检测串口失败,可以直接手动指定端口号(Windows通常是COMx,Linux是/dev/ttyACM0)。

内容的提问来源于stack exchange,提问作者Dylan Devotta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:37:47