Public CmdLenth As Integer
Public HiByte As String
Public LoByte As String
Private Sub Form_Load()
‘1. 通讯口初始化:
MSComm1.Settings = "4800,n,8,1"
MSComm1.CommPort = 3
MSComm1.SThreshold = 0
MSComm1.PortOpen = True
End Sub
‘2. CRC 校验码的计算方法,如以下函数,可以得到字节数组变量cmdstring 指向的字符串的CRC
‘校验码?
Function crc16(ByRef cmdstring() As Byte, ByVal j As Integer)
Dim data As Integer
Dim i As Integer
Addressreg_crc = &HFFFF
For i = 0 To j
Addressreg_crc = Addressreg_crc Xor cmdstring(i)
For j = 0 To 7
data = Addressreg_crc And &H1
If data Then
Addressreg_crc = Int(Addressreg_crc / 2)
Addressreg_crc = Addressreg_crc And &H7FFF
Addressreg_crc = Addressreg_crc Xor &HA001
Else
Addressreg_crc = Addressreg_crc / 2
Addressreg_crc = Addressreg_crc And &H7FFF
End If
Next j
Next i
If Addressreg_crc < 0 Then
Addressreg_crc = Addressreg_crc - &HFFFF0000
End If
HiByte = Addressreg_crc And &HFF
LoByte = (Addressreg_crc And &HFF00) / &H100
End Function
Private Sub Command1_Click()
‘4. 写多个字的命令(本例是写2 号站%MW20 起始的3 个字):
Dim WriteStr() As Byte
k = 6 ‘写6 个字节
ReDim WriteStr(8 + k)
WriteStr(0) = 2 ‘从站号是2
WriteStr(1) = &H10 ‘写多个字的命令代码
WriteStr(2) = 0 ‘起始地址高字节
WriteStr(3) = 20 ‘起始地址低字节
WriteStr(4) = &H0 ‘数据长度高字节<字的个数>
WriteStr(5) = k / 2 ‘数据长度低字节<字的个数>
WriteStr(6) = k ‘数据长度<字节的个数>
WriteStr(7) = &H12 ‘写的第1 个字的高字节
WriteStr(8) = &H34 ‘写的第1 个字的低字节
WriteStr(9) = &H56 ‘写的第2 个字的高字节
WriteStr(10) = &H78 ‘写的第2 个字的低字节
WriteStr(11) = &H9A ‘写的第3 个字的高字节
WriteStr(12) = &HBC ‘写的第3 个字的低字节
Call crc16(WriteStr(), 6 + k)
WriteStr(9 + (k / 2 - 1) * 2) = HiByte
WriteStr(10 + (k / 2 - 1) * 2) = LoByte
Text2.Text = HiByte
Text3.Text = LoByte
MSComm1.InBufferCount = 0
MSComm1.Output = WriteStr
‘写命令发送后,当接收到8 个字节时中断
CmdLenth = 8
MSComm1.RThreshold = CmdLenth
End Sub
‘5. 通讯事件中断产生时的数据处理:
Private Sub MSComm1_OnComm()
Dim inx() As Byte
Select Case MSComm1.CommEvent
Case comEvReceive ‘判断为接收事件
MSComm1.InputLen = CmdLenth ‘接收数据的长度
inx = MSComm1.Input ‘接收数据
MSComm1.InBufferCount = 0
For k = 3 To CmdLenth - 3
tmpstr = tmpstr & "/" & Hex(inx(k))
Next
Text1.Text = tmpstr ‘以十六进制显示所接收长度的数据
Beep
Endselect
End Sub
点击按钮Command1时,PLC上的通讯灯com会一亮,一亮的,可就是数据发不过去,不知为何?!
小弟在此跪谢了!!!