关于VB与单片机串口通信的怪问题。狂急!!~~
我用VB做了个程序,发给单片机。发送十六进制“F0”,单片机接收后返回“F0 0D 0A F0”,但我现在接收到“32 34 30 F0”,把大致程序发一下(接收部分):
dim buffer as variant
dim byte(0) as byte
buffer = mscomm1.input
byte(0) = AscB(buffer)
text1.text = text1.text + byte(0)
我是用二进制接收的。mscomm1.inputlen=0
接收一个字节就触发oncomm事件
------解决方案--------------------Private Sub cmdSend_Click()
Dim bytData(0) As Byte
bytData(0) = &HF0
Call SendData(bytData)
End Sub
Public Function SendData(ByRef bytData() As Byte) As Long
On Error Resume Next
MSComm1.InBufferCount = 0 '清空接收缓冲区
MSComm1.Output = bytData '发送数据
Do
DoEvents
Loop Until MSComm1.OutBufferCount = 0 '等待,直到数据发送完毕
MSComm1.OutBufferCount = 0 '清空发送缓冲区
End Function
Private Sub Form_Load()
MSComm1.CommPort = 1 'COM端口
MSComm1.Settings = "9600,n,8,1 "
MSComm1.InputMode = comInputModeBinary '采用二进制传输
MSComm1.InBufferCount = 0 '清空接受缓冲区
MSComm1.OutBufferCount = 0 '清空传输缓冲区
MSComm1.RThreshold = 1 '产生MSComm事件
MSComm1.PortOpen = True '打开端口
Text3 = " "
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
MSComm1.InputLen = 0
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
Text3 = Text3 + strData
If Left(strData, 2) = "F0 " And Len(strData) = 8 Then
Text1.Text = strData
Call DataClear
End If
End Select
End Sub
Public Sub DataClear()
MSComm1.OutBufferCount = 0 '清空发送缓冲区
MSComm1.InBufferCount = 0
Text3 = " "
End Sub