I have some C code running on my Arduino that does a CRC calculation. I can't get it to work on Python with my RPi. I suspect it's because the Arduino is using a 16 bit unsigned integer and RPi is not. BTW - I'm brand new to Python.
Here's my Arduino code
void setup() {
Serial.begin(9600);
byte testData[]= {0x82, 0x00, 0x3A, 0x0A, 0x89, 0x00, 0x7D, 0xE3};
// crc for test data is 32227
// first 6 bytes in testData is the data, last 2 are CRC
uint16_t crc = crc16_test(testData, 6);
Serial.println(crc);
}
uint16_t crc16_test(uint8_t buf[], uint8_t len )
{
uint16_t crc = 0;
for (int j=0; j < len; j++)
{
crc ^= buf[j] << 8;
for(int i = 0; i < 8; ++i )
{
if( crc & 0x8000 )
crc = (crc << 1) ^ 0x1021;
else
crc = crc << 1;
}
}
return crc;
}
Here's my RPi code
rlist = [0x82, 0x00, 0x3A, 0x0A, 0x89, 0x00, 0x7D, 0xE3]
crc = crc16_ccitt(rlist, 6)
print(crc)
#----------------------
def crc16_ccitt(rawData, length):
crc = 0
l = 0
for byteData in rawData:
if l == length:
break
crc ^= (byteData << 8)
l += 1
k = 0
while k < 8:
k += 1
if(crc & 0x8000):
crc = (crc << 1) ^ 0x1021
else:
crc = crc << 1
return (crc)
The python code returns a big 19 digit number.
File "/usr/local/lib/python2.7/dist-packages/crcmod/crcmod.py", line 450, in crcfun return xorOut ^ fun(data, xorOut ^ crc, table) File "/usr/local/lib/python2.7/dist-packages/crcmod/_crcfunpy.py", line 73, in _crc32r crc = table[ord(x) ^ int(crc & 0xFFL)] ^ (crc >> 8) TypeError: ord() expected string of length 1, but int found
– Scott Goldthwaite Nov 15 '18 at 01:55uint16_t, the operations are performed modulo 2^16. You need to do the same in python. That can be done using bitwise and with 0xFFFF. – SleuthEye Nov 15 '18 at 04:02