重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
使用委托方式处理:
创新互联建站专业为企业提供新罗网站建设、新罗做网站、新罗网站设计、新罗网站制作等企业网站建设、网页设计与制作、新罗企业网站模板建站服务,十余年新罗做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
Public Class Form1
Dim mSTR As String
Dim strData As String
Dim strDat As String
Dim mRecvByte() As Byte
Dim Hexsj As String
Dim form2 As Form
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim mSize As Integer = Me.SerialPort1.BytesToRead
ReDim mRecvByte(mSize - 1)
SerialPort1.Read(mRecvByte, 0, mSize)
BeginInvoke(New EventHandler(AddressOf ONMLoadA), SerialPort1.BytesToRead()) '使用委托方式显示接收到的字符串
End Sub
Sub ONMLoadA(ByVal sender As System.Object, ByVal e As System.EventArgs) '委托
strDat = ""
TextBox1.Text = ""
Dim i As Integer
For i = 0 To UBound(mRecvByte) 'mSize - 1
strData = strData IIf(mRecvByte(i) 15, Hex(mRecvByte(i)), "0" Hex(mRecvByte(i))) " "
Next
Dim sj As Byte
For i = 1 To Len(strData) Step 3 '处理为ASCII字符
sj = Val("H" Mid(strData, i, 2))
If sj 32 Or sj 128 Then '当接收字节中有Chr(0)时,其后字符被切割
strDat = strDat "."
Else
strDat = strDat Chr(sj)
End If
Next
TextBox1.Text = strDat '显示字符
TextBox2.Text = strData '显示为16进制
TextBox3.Text = Len(strData) / 3
End Sub
vb.net的话
For
Each
sp
As
String
In
My.Computer.Ports.SerialPortNames
cbxport.Items.Add(sp)
Next
vb6.0的话要调用API查看串口相关信息存在的注册表。
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
通过读注册表的方法获得串口数量,当然也可以获得串口号了。
Option
Explicit
Private
Declare
Function
RegOpenKey
Lib
"advapi32.dll
"
Alias
"RegOpenKeyA
"
(ByVal
hKey
As
Long,
ByVal
lpSubKey
As
String,
phkResult
As
Long)
As
Long
Private
Declare
Function
RegQueryInfoKey
Lib
"advapi32.dll
"
Alias
"RegQueryInfoKeyA
"
(ByVal
hKey
As
Long,
ByVal
lpClass
As
String,
lpcbClass
As
Long,
ByVal
lpReserved
As
Long,
lpcSubKeys
As
Long,
lpcbMaxSubKeyLen
As
Long,
lpcbMaxClassLen
As
Long,
lpcValues
As
Long,
lpcbMaxValueNameLen
As
Long,
lpcbMaxValueLen
As
Long,
lpcbSecurityDescriptor
As
Long,
lpftLastWriteTime
As
Long)
As
Long
Private
Const
HKEY_LOCAL_MACHINE
=
H80000002
'
获得当前系统的
COM
口的数量
Function
GetCOMCount()
As
Integer
Dim
ret
As
Long,
cntCOM
As
Long
RegOpenKey
HKEY_LOCAL_MACHINE,
"HARDWARE\DEVICEMAP\SERIALCOMM
",
ret
RegQueryInfoKey
ret,
"
",
0,
0,
0,
0,
0,
cntCOM,
0,
0,
0,
GetCOMCount
=
cntCOM
End
Function
Private
Sub
Command1_Click()
MsgBox
"您的机器有
"
GetCOMCount
"
个串口。
",
vbOKOnly,
"串口数量
"
End
Sub
不是很明白你的题意
strHex = strHex + [String].Format("{0:X2} "
这里的意思是把每个字节数据转换成了十六进制,每个字节占两个字符
如果你串口收到的4个字节数据:43,27,56,200
那么你的结果是:2B1B38C8
即receivebytes.Text="2B1B38C8"
不足两位的补0
如果你串口收到的4个字节数据:3,27,56,200
那么你的结果是:031B38C8
即receivebytes.Text="031B38C8"