Skip to content

Instantly share code, notes, and snippets.

@tspspi
Created October 24, 2018 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tspspi/e5a34bc3200397dea1e63e67a0d1690c to your computer and use it in GitHub Desktop.
Save tspspi/e5a34bc3200397dea1e63e67a0d1690c to your computer and use it in GitHub Desktop.
1-Wire CRC: A CLI tool to calculate or verify CRC for device ROM IDs
/*
Simply command line tool to calculate CRC
of device ROM IDs for dallas 1-wire devices
(or compatible)
*/
#include <stdio.h>
#include <stdint.h>
static uint8_t crcUpdate8(uint8_t crc, uint8_t data) {
uint8_t j;
crc = crc ^ data;
for (j = 0; j < 8; j=j+1) {
if ((crc & 0x01) != 0) {
crc = (crc >> 1) ^ 0x8C;
} else {
crc = crc >> 1;
}
}
return crc;
}
int main(int argc, char* argv[]) {
uint8_t data[8];
unsigned int nextValue;
uint8_t crc = 0;
uint8_t i;
/*
Command line argument: 7 bytes hexadecimal
*/
if((argc != 8) && (argc != 9)) {
printf("Calculate or validate Dallas 1-wire ROM ID CRC\n");
printf("Usage:\n");
printf("\tValidation: %s B0 B1 B2 B3 B4 B5 B6 B7\n", argv[0]);
printf("\tCalculation: %s B0 B1 B2 B3 B4 B5 B6\n", argv[0]);
return -1;
}
for(i = 1; i < argc; i=i+1) {
// Read hex value
if(sscanf(argv[i], "%x ", &nextValue) < 1) {
printf("Invalid argument\n");
return -1;
}
if(nextValue > 255) {
printf("Invalid argument %x\n", nextValue);
return;
}
data[i-1] = (uint8_t)nextValue;
crc = crcUpdate8(crc, data[i-1]);
}
if(argc == 8) {
data[7] = crc;
for(i = 0; i < 8; i=i+1) {
if(i != 7) {
printf("0x%x, ", data[i]);
} else {
printf("0x%x\n", data[i]);
}
}
} else if(argc == 9) {
if(crc == 0) {
printf("Ok\n");
return 0;
} else {
printf("Failed\n");
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment