Modbus communication using HMI and controller

P

Thread Starter

petrusha

Hello there.I am writing the code in vb 2008 to communicate with hmi using Modbus. I am getting error as error in write function and also i do have doubt in crc too. so if possible can anyone help me out of it

mail [email protected]
 
hi there,

i am getting error in write fuction and also in crc. I am writing code to communicate with HMI via PC using modbus. plz help me with modbus write function 16 and replace the code if possible.

<b>Moderator's note: this was a second message posted by petrusha</b> <pre>
Imports System.Array
Imports System.IO.Ports
Imports System


Public Class GUI_amey1
Dim crc As Byte
Dim c As Byte
'Dim strHMI As String
'public bool SendFc16(byte address, ushort start,
''ushort registers, short[] values</pre>
 
I just finished with coding a Modbus communications (serial and ethernet) package using vb.net.

If you need a CRC sounds like you are using a serial port? Any issues with getting the port to open? Also, check for baud, parity, data and stop bits are correct for what you need.

I place the message I want to send into a buffer. First byte is the slave address followed by the PDU portion. I call this bufPDU(). The code below simply moves this into TransmitBuffer() when the message mode is "RTU" (for ASCII and Ethernet some other things need to be done)<pre>
Case "RTU" 'formulate message to send via Serial/RTU
Dim j As Integer
For j = 0 To (lbuf - 1) Step 1
TransmitBuffer(j) = bufPDU(j)
Next
Dim CRCValue As Integer
CRCValue = CRC(TransmitBuffer, lbuf)
TransmitBuffer(lbuf) = CByte((CRCValue And &HFF)) 'lo byte
TransmitBuffer(lbuf + 1) = CByte((CRCValue >> 8) And &HFF) 'hi byte
TransmitCount = lbuf + 2

The CRC is two bytes with the low byte placed first in the message. Finally, to calculate the CRC here's a routine someone else had posted that works for me.

'-------------------------------------------------
'CRC Generator
'-------------------------------------------------
Public Function CRC(buf() As Byte, lbuf As Integer) As Integer
' returns the MODBUS CRC of the lbuf first bytes of "buf" buffer (buf is a global array of bytes)
Dim CRC1 As Integer
Dim j As Integer
Dim k As Integer

CRC1 = &HFFFF ' init CRC
For Me.i = 0 To lbuf - 1 Step 1 ' for each byte
CRC1 = CRC1 Xor buf(Me.i)
For j = 0 To 7 Step 1 ' for each bit
k = CRC1 And 1 ' memo bit 0 state
'CRC1 = (((CRC1 And &HFFFE) / 2) And &H7FFF) ' Shift right with 0 at left
CRC1 = (((CRC1 And &HFFFE) >> 1) And &H7FFF) ' Shift right with 0 at left
If k > 0 Then CRC1 = CRC1 Xor &HA001
Next j
Next Me.i
CRC = CRC1
End Function</pre>
To send the message over the serial port (where my serial port I opened was named SerialPort1).

SerialPort1.Write(TransmitBuffer, 0, TransmitCount)

Hope this helps... Jim
 
Top