Hi everyone,
I am a little rusty, but I think I figured out how to use one of the avr-libc functions for crc-16 calculations on a serial input. I split these two files out of what I'm working because others may find it helpful.
setup and loop
#define maxLength 16
boolean debugmsg = true; //retrun a debug answer
// Arduino has Tx and Rx buffers with ISRs that push/pull from its respective buffer.
// So all I need to do is check if a serial input is available, and extract it.
String command;
uint16_t crc;
boolean commandComplete = false;
boolean crcComplete = false;
void setup() {
command.reserve(maxLength);
Serial.begin(9600);
command = "";
crc =0;
}
void loop () {
if(Serial.available() > 0) {
getIncomingChars();
}
if (commandComplete == true) {
if(debugmsg) {
Serial.println ("# CRC "+ String(crc,HEX));
}
// processCommand();
command = "";
commandComplete = false;
crc = 0;
crcComplete = false;
}
}
get serial input
/*
http://www.nongnu.org/avr-libc/user-manual/group__util__crc.html
http://forum.arduino.cc/index.php?topic=100977.0;wap2
send "123456789;" should give crc value 0xBB3D
also check calculator on web http://dk.bg-elektronik.dk/support/crc/
select CRC-16, and polynomial hex value is 0x8005, also do not inclued the ';'
*/
extern "C" {
#include <util/crc16.h>
};
extern "C" {
static __inline__ uint16_t _crc16_update(uint16_t __crc, uint8_t __data);
}
void getIncomingChars() {
char inChar = Serial.read();
// "\n" == 10 line feed, "\r" == 13 carriage return, ";" == 59
command.concat(inChar);
if(inChar == ';'){
crcComplete = true;
}
if(!crcComplete) {
crc = _crc16_update( crc, (uint8_t)inChar);
}
if(inChar == '\n'){
commandComplete = true;
}
}
I use Serial Monitor to send "123456789;" (with newline) and get 0xBB3D, which is correct.
I'm also tinkering with crcmod in python (3.4.1) on the other end and that looks like:
import crcmod.predefined
crc16 = crcmod.predefined.mkCrcFun('crc-16')
print(hex(crc16(str('123456789').encode('utf-8'))))