代码之家  ›  专栏  ›  技术社区  ›  Ammar Ashraf

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

  •  -3
  • Ammar Ashraf  · 技术社区  · 7 年前

    我想从连接在我的一个com端口上的UHF RFID阅读器读取数据,数据应该是十六进制,并且必须是一个完整的十六进制,应该粘贴在我用VB制作的windows窗体应用程序的文本框中。净额。

    请帮助我,我是VB新手。NET编程。我需要一个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
    

    结束类

    1 回复  |  直到 7 年前
        1
  •  0
  •   David Wilson    7 年前

    我明白你的问题。。

    线路

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

    顺便提一下,您的数据是8位二进制的,串行端口读取器将每个8位作为字符类型读取。

    你需要的是使用VB内置函数 Hex

    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
    

    If..End If