十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
不会 是 参考 人家的 程序吧
创新互联是一家集网站建设,解放企业网站建设,解放品牌网站建设,网站定制,解放网站建设报价,网络营销,网络优化,解放网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
变量 S 再哪里 定义?
把 这个 Private s As String 加 Public Class Form1 之后 试试
Ok了,我 调试过
不知道你是不是用51单片机往串口发数据,是的话那是因为51的SBUF最多存放8个字节,所以你发12个字节会分成两次发完。还有在接收的时候最好定义好通信协议,比如加一个侦头,一个侦尾,通过这两个字节的内容来接收数据。
老兄,提问还是给点悬赏分嘛,不要吝啬哪点分,知识是无价的,你给得越多,回答你的人才会越多。
你可以预先约定一个截止附,读取的字节统统放到缓存区里,直到读到截止附再处理、显示。
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
合法性校验有很多方法,要视情况而定,比如说可以用正则表达式,如果是数字,除了正则表达式,也可以用诸如TryParse这种方法。
使用委托方式处理:
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