Note. The calculation of an 8-bit CRC is discussed in greater detail on my PIC Page. There is also an Application Note at Dallas Semiconductor.
' Program CRC.BAS
'
' Illustrates how to calculate the 8-bit Cyclic Redundancy Check (CRC) of
' data received from Dallas 1-W devices.
'
' The new BasicX24 provides for the direct interface with the Dallas 1-W
' family, including the DS1820 thermometer and DS2401 Silicon Serial
' Number.
'
' Most data is sent as a block consisting of eight or nine bytes of data
' with the final byte being the CRC check number.
'
' In this routine, GetID is a stub which loads array ID with eight bytes.
' This might be a serial number (8 bytes) or the result of a temperature
' measurment (9 bytes).
'
' The routine then calculates and displays the CRC.
'
' copyright, Peter H. Anderson, Baltimore, MD, Oct, '99
Sub Main()
Dim ID(1 to 8) as Byte, CRC as Byte
Call OpenSerialPort(2, 9600)
Call GetID(ID) ' fecth the serial number
CRC = Calc_CRC(ID, 8) ' calculate the CRC, 8 bytes
Call PutB(CRC) ' display it
Done:
Goto Done
End Sub
Sub GetID(ByRef ID() as Byte)
ID(1) = &H02
ID(2) = &H1c
ID(3) = &Hb8
ID(4) = &H01
ID(5) = &H00
ID(6) = &H00
ID(7) = &H00
ID(8) = &Ha2
End Sub
Function Calc_CRC(ByRef buff() as byte, ByVal num_vals as Integer) as byte
Dim Shift_Reg as Byte, SR_lsb as Byte, Data_Bit as Byte, v as Byte
Dim FB_bit as Byte, i as Integer, j as Integer
Shift_Reg = 0 ' initialize the shift regsiter
For i = 1 to num_vals ' for each byte in the array
v = buff(i)
For j = 1 to 8 ' for each bit
Data_Bit = v AND &H01 ' isolate least sign bit
SR_lsb = Shift_Reg AND &H01
FB_bit = (Data_Bit XOR SR_lsb) AND &H01
' calculate the feed back bit
Shift_Reg = Shift_Reg \ 2 ' shift right
If (FB_bit = 1) then
Shift_Reg = Shift_Reg XOR &H8c
End if
'Call PutB(Shift_Reg) ' for debugging
'Call NewLine()
v = v \ 2 ' next bit now in least sig bit position
Next
' Call PutB(Shift_Reg)
' Call NewLine()
Next
Calc_CRC = Shift_Reg ' return the result
End Function