 # Implementing CRC (8 bit, Maxim 1-wire)

I’m trying to implement the algorithm as per https://www.maximintegrated.com/en/app-notes/index.mvp/id/27.

I’m using 0x02 as testinput, to be able to compare the result with Example 2 page 5 in the linked application note, it goes well until the 6th cycle.

``````--- Begin ---
00000000
00000000
10001100
01000110
00100011
10011101
11001110
01100111
``````

which should be

``````--- Begin ---
00000000
00000000
10001100
01000110
00100011
10011101
11000010    (not 11001110)
01100001    (not 01100111)
``````

Can anybody see what’s going wrong? Thanks.

void setup() {
Serial.begin(9600);
}

byte temp;
byte old_X;
int i = 0;

////////// Testdata ///////
byte input = 0b00000010;
byte X = 0b00000000;
////////////////////////////

// X = X0 X1 X2 X3 X4 X5 X6 X7
void loop() {

if(i == 0){Serial.println("— Begin —");}

if(i < 8){
Serial.println(X, BIN);

old_X = X;

// X = X >> 1
// X0 = X8 XOR input
temp = (input ^ old_X) << 7;
X = X >> 1;
X = X | temp;

// X4 = old X3 XOR new X0
temp = ( (X >> 3) ^ old_X ) & 0b00010000;
temp = temp >> 1;
X = X | temp;

// X5 = old X4 xor new X0
temp = ( (X >> 4) ^ old_X ) & 0b00001000;
temp = temp >> 1;
X = X | temp;

++i;
input = input >> 1;
}

}

The MAXIM Onewire 8-bit CRC is implemented in the OneWire library. It would save you a lot of pain :)

Pete

Hi Pete Nice to hear from you.

I know, but I would like to implement it anyway.

Can you see what's going wrong?

Markus

After I’d figured out that you were trying to implement the shift register in Figure 2 of your link, I changed your code to this:

``````byte temp;
byte old_X;
int i = 0;

//////////  Testdata  ///////
byte input = 0b00000010;
byte X = 0b00000000;
////////////////////////////

// Print one byte as 8 binary bits including leading zeros
void print_binary(byte b)
{
int i,bit = 0x80;
for(i=0;i<8;i++) {
if(b&bit)Serial.print("1");
else Serial.print("0");
bit >>= 1;
}
Serial.println();
}

void setup()
{
Serial.begin(9600);
while(!Serial);
delay(1000);

for(int i=0;i<8;i++) {
print_binary(X);
old_X = X;

// generate the feedback bit from the XOR gate at X8
temp = (input ^ old_X) << 7;
X = X >> 1;
X = X | temp;

// XOR the feedback into X4
X = X ^ (temp >> 4);
// XOR the feedback into X5
X = X ^ (temp >> 5);

input = input >> 1;
}
}

void loop()
{

}
``````

Pete