Alexandre Salconi-Denis / Mbed 2 deprecated ProjetOctopode

Dependencies:   debug mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers CRC16.cpp Source File

CRC16.cpp

00001 #include "CRC16.h"
00002 
00003 /*
00004  * FUNCTION: calcCRC calculates a 2-byte CRC on serial data using
00005  * CRC-CCITT 16-bit standard maintained by the ITU
00006  * ARGUMENTS: queue_ptr is pointer to queue holding are a to be CRCed
00007  * queue_size is offset into buffer where to stop CRC calculation
00008  * RETURNS: 2-byte CRC
00009  */
00010 
00011 #define POLY 0x8005//0x8408
00012 /*
00013 //                                      16   12   5
00014 // this is the CCITT CRC 16 polynomial X  + X  + X  + 1.
00015 // This works out to be 0x1021, but the way the algorithm works
00016 // lets us use 0x8408 (the reverse of the bit pattern).  The high
00017 // bit is always assumed to be set, thus we only use 16 bits to
00018 // represent the 17 bit value.
00019 */
00020 
00021 
00022 uint16_t CRC16_BUYPASS(const char *data, size_t len) { 
00023   uint16_t crc = 0x0000; 
00024   size_t j; 
00025   int i; 
00026   for (j=len; j>0; j--) { 
00027     crc ^= (uint16_t)(*data++) << 8; 
00028     for (i=0; i<8; i++) { 
00029       if (crc & 0x8000) crc = (crc<<1) ^ 0x8005; 
00030       else crc <<= 1; 
00031     } 
00032   } 
00033   return (crc); 
00034 } 
00035 
00036 /*int main() { 
00037   uint8_t test[9]  = {0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39}; 
00038   uint8_t tgil[29] = {0x00,0x0B,0x01,0x0E,0x01,0xC6,0x00,0x00,0x00,0x00, 
00039                       0x00,0x00,0x33,0x31,0x30,0x31,0x34,0x31,0x30,0x30, 
00040                       0x41,0x00,0x00,0x04,0x24,0x14,0x16,0x06,0x49}; 
00041   uint16_t crc; 
00042   crc = CRC16_BUYPASS(test, 9); 
00043   //printf("Rocksoft check value: 0x%04X, test ", crc); 
00044   //if (crc==0xFEE8) printf("passed.\n"); else printf("failed!\n"); 
00045   crc = CRC16_BUYPASS(tgil, 29); 
00046   //printf("CRC gil's data: 0x%04X\n", crc); 
00047   return 0; 
00048 } */
00049 
00050 unsigned short calculateCRC16(const char *data_p, unsigned short length)
00051 {
00052     unsigned char i;
00053     unsigned int data;
00054     unsigned int crc = 0xffff;
00055 
00056     if (length == 0)
00057     return (~crc);
00058 
00059     do
00060     {
00061         for (i=0, data=(unsigned int)0xff & *data_p++;
00062         i < 8;
00063         i++, data >>= 1)
00064         {
00065             if ((crc & 0x0001) ^ (data & 0x0001))
00066             crc = (crc >> 1) ^ POLY;
00067             else  crc >>= 1;
00068         }
00069     } while (--length);
00070 
00071     crc = ~crc;
00072     data = crc;
00073     crc = (crc << 8) | (data >> 8 & 0xff);
00074 
00075     return (crc);
00076 }