不是很明白你的题意
让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:空间域名、雅安服务器托管、营销软件、网站建设、郧西网站维护、网站推广。
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"
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
上面的代码看不出问题,如果初始化串口控件时已经注册了AxMSComm1_OnComm,有数据接收应该能触发,至于为什么没有触发,要看看你的接收方是否已经收到你的发出指令,是否已经有响应数据回发。
建议分开调试,用一个通用的串口助手,如格西烽火串口助手之类的,分别调试你的上位机和下位机。格西烽火串口助手能轻松的定制如你上面的发送数据。
首先:
textbox里没有显示,是因为SerialPort1和TextBox2不是同一线程创建的,需要跨线程操作。需要用到委托,这样才能显示出来。
其次:
我觉得用串口的接收数据事件更好一些。
下面代码供参考:
'----------------------
'串口接收数据事件,其实比用定时器更好,
'触发事件的条件可以自己在form_load中设置ReceivedBytesThreshold属性数值,默认为ReceivedBytesThreshold=1
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim strRecvData As String = ""
strRecvData = SerialPort1.ReadExisting
Call disPlayComData(strRecvData)
End Sub
Delegate Sub callback(ByVal strT As String) '定义委托
Sub showString(ByVal comdata As String) '显示结果
Me.TextBox1.Text = "结果:" comdata
End Sub
Sub disPlayComData(ByVal strTmp As String) '判定是否为跨线程
If Me.TextBox1.InvokeRequired Then
Dim d As New callback(AddressOf showString)
Me.Invoke(d, New Object() {strTmp})
Else
Me.TextBox1.Text = strTmp
End If
End Sub