我想读取连接在我的一个com端口上的UHF RFID阅读器的数据,数据应该是HEX,并且必须是一个完整的HEX,应该粘贴在我制作的Windows窗体应用程序的文本框中在VB.NET中。
请帮助我,我是VB.NET Programming的新手。我需要一个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
结束班
答案 0 :(得分:0)
我看到了你的问题..
行
./configure --prefix=/usr/local/apache-2.4.20 --with-included-apr
正在尝试将字符转换为int32,但该函数假设传入的值已经是十六进制,并且您的答案完全错误。
顺便提一下,您的数据是8位二进制文件,并且您的串行端口读取器将每个8位读取为char类型。
你需要的是使用VB内置函数hexVal = Convert.ToInt32(c, 16) '16 specifies the base
,它取一个整数/字节(在这种情况下是每个字符的ascii代码)并返回一个十六进制值作为字符串,所以
Hex
将“F”分配给字符串
一切都很好。但是,如果您需要2位十六进制字符串,则需要检查返回的字符串是否只有一个字符,如果是,请在开头添加“0”。
所以,你的行
Dim x As Integer = 15
Dim s As String = hex(x)
应替换为..
Dim hexVal As Integer
hexVal = Convert.ToInt32(rcv, 16) '16 specifies the base
txtReceived.Text = hexVal
并添加此函数以转换字符,并在必要时添加“0”..
Dim hexVal As string =""
For Each c As Char In rcv
hexVal = heval & AsciiCharToHexSring(c)
Next
txtReceived.Text = hexVal
如果每次都不需要2位十六进制数,只需删除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
块