vb串口通信温度检测模块。求解答
Dim data, data1 As Variant '串口初始化
Private Sub Command2_Click()
Text2.Text = ""
End Sub
Private Sub Form_Load()
MSComm1.CommPort = 1 ' 设置通信端口号为COM1
MSComm1.Settings = "9600,n,8,1" ' 设置串口1参数
MSComm1.InputMode = comInputModeBinary ' 接收二进制数据
MSComm1.InputLen = 1
MSComm1.RThreshold = 24
InBufferSize = 40
If MSComm1.PortOpen = True Then MSComm1.PortOpen = False
If MSComm1.PortOpen = False Then MSComm1.PortOpen = True ' 打开通信端口1
End Sub
Private Sub Command1_Click()
MSComm1.OutBufferCount = 0
MSComm1.Output = "#018" + (vbCr)
End Sub
Private Sub MSComm1_OnComm()
On Error Resume Next
Dim BytReceived() As Byte
Dim strBuff As String
Dim strData As String
Dim i As Integer
Dim x As Integer
Select Case MSComm1.CommEvent
Case 2
strBuff = MSComm1.Input
BytReceived() = strBuff
For i = 0 To UBound(BytReceived)
If Len(Hex(BytReceived(i))) = 1 Then
strData = strData & "0" & Hex(BytReceived(i))
Else
strData = strData & Hex(BytReceived(i))
End If
Next
Text2 = Text2 + strData
MSComm1.InBufferCount = 20 '清空输入寄存器
MSComm1.OutBufferCount = 0 '清空传输缓冲区
End Select
End Sub
该程序只能一次接受几个字节的数据。我想要一次接收好几十个怎么办。想用数组形式。不会用啊。
[解决办法]
你把:"#018" + (vbCr)
转换为数组就可以了
Dim OutByte(0 To 4) as Byte
OutByte(0)=ASC("#")
OutByte(1)=ASC("0")
OutByte(2)=ASC("1")
OutByte(3)=ASC("8")
OutByte(4)=13 'vbCr的ASCII码
MSComm1.Output=OutByte