PrivateSubCommand1_Click()'发送指令Dimpu()AsByteDimstrdataAsStringDimcrc_js()AsByteReDimpu(5)pu(0)="&H00"pu(1)="&H03"pu(2)="&H00"'2、3为温度计地址pu(3)="&H00"'2、3为温度计... Private Sub Command1_Click() '发送指令
Dim pu() As Byte
Dim strdata As String
Dim crc_js() As Byte
ReDim pu(5)
pu(0) = "&H00"
pu(1) = "&H03"
pu(2) = "&H00" '2、3为温度计地址
pu(3) = "&H00" '2、3为温度计地址
pu(4) = "&H00" '4、5为读取寄存器长度
pu(5) = "&H01" '4、5为读取寄存器长度
crc_js = CRC16(pu())
MSComm1.Output = pu
MSComm1.Output = crc_js
MSComm1.OutBufferCount = 0 '清除发送缓冲区
End Sub
Private Sub Form_Load()
MSComm1.CommPort = 7 '串口为7
MSComm1.Settings = "9600,n,8,1"
MSComm1.RThreshold = 1 '发送频率为1每发送一个字符都会使 MSComm 控件触发OnComm 事件
MSComm1.SThreshold = 1
MSComm1.InBufferCount = 0 '清除接收缓冲区
MSComm1.OutBufferCount = 0 '清除发送缓冲区
MSComm1.InputMode = comInputModeBinary '二进制接收
If Not MSComm1.PortOpen Then
MSComm1.PortOpen = True '打开串口
End If
End Sub
Private Sub Form_Unload(Cancel As Integer)
MSComm1.PortOpen = False
End Sub
Private Sub MSComm1_OnComm() 'COM事件
Print "返回值:" & MSComm1.CommEvent
Select Case MSComm1.CommEvent
Case comEventBreak
MsgBox "comEventBreak"
Case comEventCDTO
MsgBox "comEventCDTO"
Case comEventCTSTO
MsgBox "comEventCTSTO"
Case comEventDSRTO
MsgBox "comEventDSRTO"
Case comEventFrame
MsgBox "comEventFrame"
Case comEventOverrun
MsgBox "comEventOverrun"
Case comEventRxOver
MsgBox "comEventRxOver"
Case comEventRxParity
MsgBox "comEventRxParity"
Case comEventTxFull
MsgBox "comEventTxFull"
Case comEventDCB
MsgBox "comEventDCB"
Case comEvCD
MsgBox "comEvCD"
Case comEvCTS
MsgBox "comEvCTS"
Case comEvDSR
MsgBox "comEvDSR"
Case comEvRing
MsgBox "comEvRing"
Case comEvEOF
MsgBox "comEvEOF"
Case comEvReceive
MsgBox "接收到数据返回"
End Select
End Sub
结果是 MSComm1.CommEvent = 1 'ComEvSend 1 发送缓冲区中的字符数少于 SThreshold。
我想获取温度计温度,该如何写啊,求高手指点,附通讯协议。
输出时不要清缓冲区Private Sub Command1_Click() '发送指令
Dim pu() As Byte
Dim strdata As String
ReDim pu(5)
pu(0) = "&H00"
pu(1) = "&H03"
pu(2) = "&H00" '2、3为温度计地址
pu(3) = "&H00" '2、3为温度计地址
pu(4) = "&H00" '4、5为读取寄存器长度
pu(5) = "&H01" '4、5为读取寄存器长度
MSComm1.Output = pu
MSComm1.Output = CRC16(pu)
'MSComm1.OutBufferCount = 0 '清除发送缓冲区
End Sub事件处理程序不要用 Msgbox,也没必要每种事件都处理。Private Sub MSComm1_OnComm() 'COM事件
Dim RcvBuff() As Byte
Debug.Print "返回值:" & MSComm1.CommEvent
Select Case MSComm1.CommEvent
Case comEvReceive
DoEvents
RcvBuff = MSComm1.Input
'
'处理 RcvBuff 中的返回报文
'
Case Else
'Donothing...
End Select
End Sub如何处理收到的报文我就不写了,你自己研究。