User Tools

Site Tools

한국어

cubloc:basic_modbus_rtu_master:index

An Example Modbus RTU Master Written in BASIC

#Include "MSB6XX"
 
Ramclear
 
Dim RxByte As Byte
Dim _Txb(80) As Byte
Dim MBdata(32) As Integer
Dim _Crcres As Integer   
On Recv3 Gosub GETMODBUS ' Data Receive Interrupt routine
 
Set Ladder On
Do
   MBreadReg 3, 1, 28682, 1
   Wait 1000
Loop
 
GETMODBUS:
   Debug "Response: "
   Do While Blen(3,0) > 0   ' While buffer is not empty then
      RxByte = Get(3, 1)    ' Get byte from RX Buffer
      Debug Hex RxByte, " " ' Print byte to debug console
   Loop
   Debug Cr 'New Line         
   Return
End
 
Sub MBReadCoil(_MBch As Byte, _MBslave As Byte,_MBadr As Integer,_MBlen As Integer)
   _Txb(0) = _MBslave
   _Txb(1) = 1
   _Txb(2) = _MBadr.Byte1
   _Txb(3) = _MBadr.Byte0
   _Txb(4) = _MBlen.Byte1
   _Txb(5) = _MBlen.Byte0
   Getcrc _Crcres,_Txb,6
   _Txb(6) = _Crcres.Byte1
   _Txb(7) = _Crcres.Byte0
   Puta _MBch,_Txb,8
End Sub
 
Sub MBreadReg(_MBch As Byte, _MBslave As Byte,_MBadr As Integer,_MBlen As Integer)
   _Txb(0) = _MBslave
   _Txb(1) = 3
   _Txb(2) = _MBadr.Byte1
   _Txb(3) = _MBadr.Byte0
   _Txb(4) = _MBlen.Byte1
   _Txb(5) = _MBlen.Byte0
   Getcrc _Crcres,_Txb,6
   _Txb(6) = _Crcres.Byte1
   _Txb(7) = _Crcres.Byte0
   Puta _MBch,_Txb,8
End Sub
 
Sub MBWriteSingleReg(_MBch As Byte, _MBslave As Byte,_MBadr As Integer,_MBdata As Integer)
   _Txb(0) = _MBslave
   _Txb(1) = 6
   _Txb(2) = _MBadr.Byte1
   _Txb(3) = _MBadr.Byte0
   _Txb(4) = _MBdata.Byte1
   _Txb(5) = _MBdata.Byte0
   Getcrc _Crcres,_Txb, 6
   _Txb(6) = _Crcres.Byte1
   _Txb(7) = _Crcres.Byte0
   Puta _MBch,_Txb,8
End Sub
 
Sub MBWriteSingleCoil(_MBch As Byte, _MBslave As Byte,_MBadr As Integer,_MBdata As Integer)
   _Txb(0) = _MBslave
   _Txb(1) = 5
   _Txb(2) = _MBadr.Byte1
   _Txb(3) = _MBadr.Byte0
   If _MBdata <> 0 Then _MBdata = &hff00
   _Txb(4) = _MBdata.Byte1
   _Txb(5) = _MBdata.Byte0
   Getcrc _Crcres,_Txb,6
   _Txb(6) = _Crcres.Byte1
   _Txb(7) = _Crcres.Byte0
   Puta _MBch,_Txb,8
End Sub
 
 
Sub MBWriteMulReg(_MBch As Byte, _MBslave As Byte,_MBadr As Integer,_MBlen As Integer)
   Dim _mbi As Integer,_mbj As Integer
 
   If _MBlen > 32 Then _MBlen = 32
   _Txb(0) = _MBslave
   _Txb(1) = 16
   _Txb(2) = _MBadr.Byte1
   _Txb(3) = _MBadr.Byte0
   _Txb(4) = _MBlen.Byte1
   _Txb(5) = _MBlen.Byte0
   _Txb(6) = _MBlen << 1
   _mbj = 7
   For _mbi = 0 To _MBlen
   _Txb(_mbj) = MBdata(_mbi).Byte1
   Incr _mbj
   _Txb(_mbj) = MBdata(_mbi).Byte0
   Incr _mbj
   Next
   Getcrc _Crcres,_Txb,_mbj
   _Txb(_mbj) = _Crcres.Byte1
   Incr _mbj
   _Txb(_mbj) = _Crcres.Byte0
   Incr _mbj
   Puta _MBch,_Txb,_mbj
End Sub
cubloc/basic_modbus_rtu_master/index.txt · Last modified: 2023/03/28 16:37 by COMFILE Technology