Search code examples
luai2ccrc8

PEC calculation in Lua


I am struggling to calculate the packet error code (PEC) of received data over I2C in order to know check if the data is valid. PEC Definition

I used the code stated in a previous question but it does not work for me.

The data looks like this: 0x00, 0x07, 0x01, 0x12, 0x3b, 0xd5

PEC is 0xd5 which is based on the polynomial = x^8+ x^2+ x^1+ x^0 - 0x107

This works also fine with this calculator.

So my question is, where is the difference between the code from the website and the one from the linked question:

local function crc8(t)
   local c = 0
   for _, b in ipairs(t) do
      for i = 0, 7 do
         c = c >> 1 ~ ((c ~ b >> i) & 1) * 0xE0
      end
   end
   return c
end

Solution

  • This definition of CRC uses reversed bits in all data bytes.

    local function reverse(x)
       -- reverse bits of a byte
       local y = 0
       for j = 1, 8 do
          y = y * 2 + (x&1)
          x = x >> 1
       end
       return y
    end
    
    local function crc8(t)
       local c = 0
       for _, b in ipairs(t) do
          b = reverse(b)
          for i = 0, 7 do
             c = c >> 1 ~ ((c ~ b >> i) & 1) * 0xE0
          end
       end
       c = reverse(c)
       return c
    end
    
    print(tohex(crc8{0x00, 0x07, 0x01, 0x12, 0x3b}))  -->   0xd5