ATtiny85 Template Code
Code snippets for the ATtiny85
 All Files Functions Variables Typedefs Enumerations Enumerator Macros
crc16.c
Go to the documentation of this file.
1 /*--------------------------------------------------------------------------*
2 * CRC16 calculations (CCITT standard)
3 *---------------------------------------------------------------------------*
4 * 15-Apr-2014 ShaneG
5 *
6 * Helper function to generate a 16 bit CRC from binary data. This implement
7 * is optimised for a small lookup table - saving flash. Code is based on the
8 * example found here -
9 * http://www.digitalnemesis.com/info/codesamples/embeddedcrc16/
10 *--------------------------------------------------------------------------*/
11 #include <avr/pgmspace.h>
12 #include "utility.h"
13 
20 static const uint16_t CRC_LOOKUP[] PROGMEM = {
21  0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
22  0x0881, 0x2991, 0x4AA1, 0x6BB1, 0x8CC1, 0xADD1, 0xCEE1, 0xEFF1
23  };
24 
31 uint16_t crcInit() {
32  return 0xFFFF; // As per CCITT standard
33  }
34 
44 uint16_t crcByte(uint16_t crc, uint8_t data) {
45  uint8_t work, val;
46  // Do the high nybble first
47  work = crc >> 12;
48  val = data >> 4;
49  work ^= val;
50  crc = crc << 4;
51  crc ^= pgm_read_word_near(CRC_LOOKUP + work);
52  // Now do the low nybble
53  work = crc >> 12;
54  val = data & 0x0F;
55  work ^= val;
56  crc = crc << 4;
57  crc ^= pgm_read_word_near(CRC_LOOKUP + work);
58  // All done
59  return crc;
60  }
61 
74 uint16_t crcData(uint16_t crc, const uint8_t *pData, uint8_t length) {
75  for(uint8_t index=0; index<length; index++)
76  crc = crcByte(crc, pData[index]);
77  return crc;
78  }
79 
92 uint16_t crcDataP(uint16_t crc, const uint8_t *pData, uint8_t length) {
93  for(uint8_t index=0; index<length; index++)
94  crc = crcByte(crc, pgm_read_byte_near(pData + index));
95  return crc;
96  }
97 
uint16_t crcInit()
Definition: crc16.c:31
uint16_t crcData(uint16_t crc, const uint8_t *pData, uint8_t length)
Definition: crc16.c:74
uint16_t crcByte(uint16_t crc, uint8_t data)
Definition: crc16.c:44
uint16_t crcDataP(uint16_t crc, const uint8_t *pData, uint8_t length)
Definition: crc16.c:92