VB.NET串口读取十六进制数据并插入文本框

VB.NET Serial Port reading HEX data and insert in the textbox

我想从连接到我的一个 com 端口的 UHF RFID reader 读取数据,数据应该是 HEX,并且必须是一个完整的 HEX,应该粘贴到我的文本框中windows 我在 VB.NET.

申请的表格

请帮助我,我是 VB.NET 的新手 Programming.I 需要一个 vb.net 代码来完成此任务:

我的代码:

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
   For Each s In System.IO.Ports.SerialPort.GetPortNames() 
        ComboBox1.Items.Add(s)
    Next s

End Sub


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ComboBox1.SelectedIndex = -1 Then
        MessageBox.Show("Please select a port")
        Exit Sub
    Else
        SerialPort1.BaudRate = 9600
        SerialPort1.DataBits = 8
        SerialPort1.Parity = IO.Ports.Parity.None
        SerialPort1.StopBits = IO.Ports.StopBits.One
        SerialPort1.PortName = ComboBox1.SelectedItem.ToString
        SerialPort1.Open()
    End If
End Sub

Private Shared buffer As String = ""

Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

    Try
        Dim rcv As String = _SerialPort1.ReadExisting()
        buffer = String.Concat(buffer, rcv)


        Dim hexVal As Integer
        hexVal = Convert.ToInt32(rcv, 16) '16 specifies the base

        txtReceived.Text = hexVal

    Catch ex As Exception
    End Try

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    SerialPort1.Close()

End Sub

结束Class

我看到你的问题了..

hexVal = Convert.ToInt32(c, 16) '16 specifies the base

正在尝试将字符转换为 int32,但该函数假设传入值已经是十六进制,而您得到的答案完全错误。

顺便说一句,你的数据是 8 位二进制,你的串行端口 reader 将每 8 位读取为 char 类型。

你需要的是使用 VB 内置函数 Hex,它需要一个 integer/byte(在本例中是每个字符的 ascii 码)和 returns 作为字符串的十六进制值所以

Dim x As Integer = 15
Dim s As String = hex(x)

会将"F"赋值给字符串

一切都很好。但是,如果您想要一个 2 位十六进制字符串,则需要检查返回的字符串是否只有一个字符,如果是,则在开头添加一个“0”。

那么,你的台词

Dim hexVal As Integer
hexVal = Convert.ToInt32(rcv, 16) '16 specifies the base
txtReceived.Text = hexVal

应替换为..

Dim hexVal As string =""
For Each c As Char In rcv
    hexVal = heval & AsciiCharToHexSring(c)
Next
txtReceived.Text = hexVal

并添加此功能以转换字符并在必要时添加“0”..

Private Function AsciiCharToHexSring(s As Char) As String
    Dim hexdigit As String = Hex(Asc(s))
    If hexdigit.Length = 1 Then
        hexdigit = "0" & hexdigit
    End If
    Return hexdigit
End Function

如果不需要每次都输入2位十六进制数,删除If..End If块即可