I use C # to communicate via modbus rs485 rs232 with two phase counters, which, among others, register the supply voltage.
I need to send data on the bus so that I can receive readings.
I connected a regular wire and shorted the transmission and reception.
The data is received and this event is fired:
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; byte[] buff = new byte[sp.BytesToRead];
Then this buffer is sent to another function, which is the following:
private void AddBuffer(byte b) { buffer.Add(b); byte[] msg = buffer.ToArray(); //Make sure that the message integrity is correct if (this.CheckDataIntegrity(msg)) { if (DataReceived != null) { ModbusEventArgs args = new ModbusEventArgs(); GetValue(msg, args); DataReceived(this, args); } buffer.RemoveRange(0, buffer.Count); } }
I think the problem is data integrity checking:
public bool CheckDataIntegrity(byte[] data) { if (data.Length < 6) return false; //Perform a basic CRC check: byte[] CRC = new byte[2]; GetCRC(data, ref CRC); if (CRC[0] == data[data.Length - 2] && CRC[1] == data[data.Length - 1]) return true; else return false; }
There is a CRC check, and it is strange that it never becomes true. Calculation of CRC:
private void GetCRC(byte[] message, ref byte[] CRC) { ushort CRCFull = 0xFFFF; byte CRCHigh = 0xFF, CRCLow = 0xFF; char CRCLSB; for (int i = 0; i < (message.Length) - 2; i++) { CRCFull = (ushort)(CRCFull ^ message[i]); for (int j = 0; j < 8; j++) { CRCLSB = (char)(CRCFull & 0x0001); CRCFull = (ushort)((CRCFull >> 1) & 0x7FFF); if (CRCLSB == 1) CRCFull = (ushort)(CRCFull ^ 0xA001); } } CRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF); CRC[0] = CRCLow = (byte)(CRCFull & 0xFF); }
source share