CRC-8 Counterpart to CRC16() and CRC32()

Here you can share completed projects or parts of projects that may be useful to others. You may post files relevant to ZBasic - source code, schematics, etc.
Post Reply
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

CRC-8 Counterpart to CRC16() and CRC32()

Post by dkinzer »

The code below is the 8-bit counterpart to the ZBasic functions CRC16() and CRC32(). It is a general purpose routine that can be used to compute a CRC-8 value for many different CRC-8 algorithms in the same way that the built-in functions can be used. In particular, the parameters for generating a CRC compatible with the Dallas/Maxim 1-wire and with SMBus are given.

Code: Select all

'
'' CRC8
'
' This function is the CRC-8 counterpart to the ZBasic CRC16() and CRC32()
' functions.  See the descriptions of those routines for more information about
' the bits of the crcFlags parameter.  The Rocksoft model parameters for a
' few popular CRC-8 algorithms are given below.
'
'      Name       1-Wire    SMBus
'      -------    ------    -----
'      WIDTH           8        8
'      POLY         &H31     &H07
'      INIT            0        0
'      REFIN        True    False
'      REFOUT       True    False
'      XOROUT          0        0
'      CHECK        &HA1     &HF4
'
Function CRC8(ByRef dataBuf() as Byte, ByVal dataLen as UnsignedInteger, _
        ByVal crcPoly as Byte, ByVal crc as Byte, ByVal crcFlags as Byte) as Byte
    Dim i as UnsignedInteger
    For i = 1 to dataLen
        Dim b as Byte
        b = dataBuf(i)
        If CBool(crcFlags And &H01) Then
            ' reflected input data
            b = FlipBits(b)
        End if

        Dim mask as Byte
        mask = &H80
        Do
            If CBool(crc And &H80) Xor CBool(b and mask) Then
                crc = Shl(crc, 1) Xor crcPoly
            Else
                crc = Shl(crc, 1)
            End If
            mask = Shr(mask, 1)
        Loop While &#40;mask <> 0&#41;
    Next i

    ' reflected output data
    If CBool&#40;crcFlags And &H02&#41; Then
        CRC8 = FlipBits&#40;crc&#41;
    Else
        CRC8 = crc
    End If
End Function
- Don Kinzer
lucianod6
Posts: 4
Joined: 25 May 2014, 1:35 AM

Post by lucianod6 »

this is my code for crc8 (tested whit zelio plc, ELSIST plc in ascii mode)

Code: Select all

Public function CRC8&#40;ByRef dataBuf&#40;&#41; as Byte,dataLen as UnsignedInteger&#41; as Byte
    Dim I As UnsignedInteger
    Dim Temp As UnsignedInteger
    Dim CRCx As UnsignedInteger
    dataLen =dataLen
    Temp = 0
    For I = 1 To dataLen 
        Temp = cuint&#40;dataBuf&#40;I&#41;&#41; + Temp
    Next I
    
    Temp = Temp Xor 65535
    Temp = Temp And 255
    Temp = Temp + 1 
    CRC8 = cbyte&#40;Temp&#41;
End function
Post Reply