B4R Question polynomial CRC8

peacemaker

Expert
Licensed User
Longtime User
Hi, All

Some i2C sensor chips use such CRC check.
How to calculate such CRC ?

Source code::
    - initial value=0xFF, polynomial=(x8 + x5 + x4 + 1) ie 0x31 CRC [7:0] = 1+X4+X5+X8
*/
/**************************************************************************/
bool AHTxx::_checkCRC8()
{

  {
    uint8_t crc = 0xFF;                                      //initial value

    for (uint8_t byteIndex = 0; byteIndex < 6; byteIndex ++) //6-bytes in data, {status, RH, RH, RH+T, T, T, CRC}
    {
      crc ^= _rawData[byteIndex];

      for(uint8_t bitIndex = 8; bitIndex > 0; --bitIndex)    //8-bits in byte
      {
        if   (crc & 0x80) {crc = (crc << 1) ^ 0x31;}         //0x31=CRC seed/polynomial
        else              {crc = (crc << 1);}
      }
    }

    return (crc == _rawData[6]);
}
 

peacemaker

Expert
Licensed User
Longtime User
Solved
B4X:
Private Sub CRC(buf() As Byte, ref_crc8 As Byte) As Boolean
    Dim CRC1 As UInt = 0xFF
    For i = 0 To buf.Length - 1
        CRC1 = Bit.Xor(CRC1, buf(i))
        For j = 1 To 8
            If Bit.And(CRC1, 0x80) = 0x80 Then
                CRC1 = Bit.ShiftLeft(CRC1, 1)
                CRC1 = Bit.Xor(CRC1, 0x31)
            Else
                CRC1 = Bit.ShiftLeft(CRC1, 1)
            End If
        Next
    Next
    Dim crc8(2) As Byte = Main.bc.UIntsToBytes(Array As UInt(CRC1))
    If ref_crc8 = crc8(0) Then
        Return True
    Else
        Return False
    End If
End Sub
 
Upvote 0
Top