c# - Modbus Communication -


i using c# communicate via modbus rs485 rs232 2 phase meters among other log power voltage.

i have send data on bus can receive readings.
have connected normal wire , shorted send , receive.

the data recieved , event fired:

private void port_datareceived(object sender, serialdatareceivedeventargs e) {     serialport sp = (serialport)sender;     byte[] buff = new byte[sp.bytestoread];      //read serial buffer     sp.read(buff, 0, buff.length);     string data= sp.readexisting();      foreach (byte b in buff)     {         addbuffer(b); //add byte buffer     } } 

then buffer sent function one:

private void addbuffer(byte b) {     buffer.add(b);      byte[] msg =  buffer.toarray();      //make sure message integrity 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 problem lies @ data integrity check:

public bool checkdataintegrity(byte[] data) {     if (data.length < 6)         return false;     //perform 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 crc check , strange never becomes true. crc calculation:

private void getcrc(byte[] message, ref byte[] crc) {      ushort crcfull = 0xffff;     byte crchigh = 0xff, crclow = 0xff;     char crclsb;      (int = 0; < (message.length) - 2; i++)     {         crcfull = (ushort)(crcfull ^ message[i]);          (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); } 

the problem use of readexisting(). not used in manner buffer being filled useless data serial port. problem identified @glace in comments!


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -