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

Visual Basic串口COM项目输出异常求助(VS2019)

VB串口通信异常修复指南

代码错误修正

1. 波特率类型转换错误

原代码直接将下拉框的字符串赋值给BaudRate(整数属性),会触发类型不匹配异常,必须显式转换并增加有效性校验:

' 替换initButton_Click中的波特率赋值逻辑
Dim baudRate As Integer
If Not Integer.TryParse(baudComboBox.Text, baudRate) Then
    MessageBox.Show("请选择有效的波特率数值")
    Return
End If
SerialPort1.BaudRate = baudRate

2. 缺失关键串口参数配置

11年前的教程默认参数可能和你的iTegno读卡器不兼容,需手动设置标准通信参数(多数USB转串口设备为8数据位、1停止位、无校验):

' 在SerialPort1.Open()前添加以下配置
SerialPort1.DataBits = 8
SerialPort1.StopBits = StopBits.One
SerialPort1.Parity = Parity.None
SerialPort1.Encoding = Encoding.ASCII ' 若读卡器用UTF-8则改为Encoding.UTF8

3. 增加异常捕获避免崩溃

串口操作极易出现端口占用、参数错误等问题,在初始化和关闭环节添加异常处理:

Private Sub initButton_Click(sender As Object, e As EventArgs) Handles initButton.Click
    If String.IsNullOrEmpty(portComboBox.Text) Then
        MessageBox.Show("请先选择串口")
        Return
    End If

    Dim baudRate As Integer
    If Not Integer.TryParse(baudComboBox.Text, baudRate) Then
        MessageBox.Show("波特率格式无效")
        Return
    End If

    Try
        SerialPort1.PortName = portComboBox.Text
        SerialPort1.BaudRate = baudRate
        SerialPort1.DataBits = 8
        SerialPort1.StopBits = StopBits.One
        SerialPort1.Parity = Parity.None
        SerialPort1.Encoding = Encoding.ASCII
        SerialPort1.Open()

        initButton.Enabled = False
        writeButton.Enabled = True
        closeButton.Enabled = True
    Catch ex As Exception
        MessageBox.Show($"串口初始化失败:{ex.Message}")
    End Try
End Sub

Private Sub closeButton_Click(sender As Object, e As EventArgs) Handles closeButton.Click
    Try
        If SerialPort1.IsOpen Then
            SerialPort1.Close()
        End If
        initButton.Enabled = True
        writeButton.Enabled = False
        closeButton.Enabled = False
    Catch ex As Exception
        MessageBox.Show($"关闭串口出错:{ex.Message}")
    End Try
End Sub

4. 优化数据接收逻辑

ReadExisting()的结果受串口编码影响,建议添加异常捕获防止接收线程崩溃:

Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    Try
        Dim receivedStr As String = SerialPort1.ReadExisting()
        ReceivedText(receivedStr)
    Catch ex As Exception
        ReceivedText($"接收错误:{ex.Message}")
    End Try
End Sub

硬件排查步骤

  • 先用串口调试工具(如SSCOM)连接读卡器,发送测试指令验证硬件是否能正常收发数据,排除驱动或硬件故障。
  • 打开设备管理器,确认USB转串口设备的驱动已正确安装,且串口编号与你选择的一致。
  • 查阅iTegno读卡器的官方手册,确保代码中的通信参数(波特率、数据位等)和设备要求完全匹配。

内容的提问来源于stack exchange,提问作者Rock Sora

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:46:19