VB 控件Mscomm 控件与PLC 进行RS485(Modbus)通讯源码 本人用的是Modbus RTU 通讯模式,通过计算机串口转RS485 与外围设备通行通讯,读写外围设备指定地址里的数据,从而达到自动化控制远端设备。 Dim HiByte As Byte Dim LoByte As Byte Dim CRC16Lo As Byte Dim CRC16Hi As Byte Dim ReturnData(1) As Byte Dim K As Integer Dim CmdLenth As Integer Private Sub Command1_Click() K = Text9.Text '写6 个字节 Text13.Text = "" '=========== 数组赋值输入代码 ======================================================================================= '<< 算法一 >> Dim WriteStr() As Byte Dim u As Integer ReDim WriteStr(K + 2) For u = 0 To K WriteStr(u) = Val("&H" & Text1(u).Text) Next '<< 算法二 >> Dim CRC_2() As Byte Dim v As Integer ReDim CRC_2(K) For v = 0 To K CRC_2(v) = Val("&H" & Text1(v).Text) Next '================================================================================================== Call CRC161(CRC_2()) Call CRC16(WriteStr(), K) MSComm1.InBufferCount = 0 '========== 显示发送代码 ======================================================================================== Dim m As Integer For m = 0 To 23 If m <= K Then Text8(m).Text = Hex(WriteStr(m)) Else Text8(m).Text = "" End If Next '================================================================================================== WriteStr(K + 1) = LoByte WriteStr(K + 2) = HiByte ' 发送代码 Text4.Text = "" Dim g As Integer For g = 0 To K + 2 Text4.Text = Text4.Text + " " + Hex(WriteStr(g)) Next '写命令发送后,当接收到8 个字节时中断 CmdLenth = 8 MSComm1.RThreshold = CmdLenth MSComm1.Output = WriteStr End Sub Private Sub Command2_Click() End End Sub Private Sub Command3_Click() Label34.Caption = "=" Text13.Text = "" K = Text9.Text '写6 个字节 '=========== 数组赋值输入代码 ==========================================================...