0

I'm trying to calculate a crc modbus in an application for PIC, but the crc returned is always incorrect compared to simulators online .. follow the code

void CRC (unsigned char * msg, unsigned char * out)
{
    // char CRC16 [2] = {0xFF, 0xFF};
    unsigned int CRC16 = 0xffff;
    unsigned int poly = 0xA001;
    unsigned char data [14];
    unsigned char crc [2];

    for (int i = 0; i <14; i ++)
    {
        CRC16 = (unsigned int) msg ​​[i] ^ CRC16; // change date to msg
        for (int j = 0; j <8; j ++)
        {
            CRC16 >> = 1;

            if (CRC16 & 0x0001 == 1)
            {
                CRC16 = poly;
            }
        }
    }
    crc [0] = CRC16 >> 8;
    crc [1] = CRC16 & lt; / RTI & gt;
    strcpy (data, msg);
    strcat (data, crc);
    strcpy (out, date);


}

I enter with a buffer of 12 bytes for the calculation and in the end should get the buffer next to the crc .. but the calculation of crc itself is returning the wrong value .. what could be wrong in the code?

in case my message should return 8C0C but returns 68FE

  • Modbus/RTU or Modbus/ASCII? You are using strcpy/strcat, which implies you are using Modbus/ASCII (cuz NUL is a valid BYTE value in Modbus/RTU, but NOT Modbus/ASCII) – franji1 Mar 29 '18 at 17:47
  • Modbus/RTU .. i'll remove that part of code.. but with a break Point in CRC[1] the values still wrong. – user7331387 Mar 29 '18 at 18:51
  • If msg only contains 12 bytes, why does your for loop iterate 14 times? – franji1 Mar 30 '18 at 02:04
  • Please only post code that actually compiles. You can't put a space between the `>>` and the `=`. There is no `lt`. Is the `/` on that line supposed to be `//` (a comment)? Is the last `strcpy` second parameter supposed to be `data`? The `CRC16 & 0x0001` needs to be in parentheses. – Mark Adler Mar 30 '18 at 05:17
  • Please provide the input data. It does no good to say what the output is supposed to be without providing the input. – Mark Adler Mar 30 '18 at 05:17
  • You can't use `str*` functions, which expect zero-terminated strings, on binary data, which a CRC is. Furthermore, if `msg` is supposed to be zero terminated, then why do you always process 14 bytes of `msg`, regardless of the contents? – Mark Adler Mar 30 '18 at 05:19
  • The correct advance of a CRC in this code would be `CRC16 = CRC16 & 1 ? (CRC16 >> 1) ^ poly : CRC16 >> 1;`. What you have there makes no sense. – Mark Adler Mar 30 '18 at 05:21

0 Answers0