Hi there, folks.
I'm kind of a newbie and I'm having problems making Arduinos talk with each other while using CRC to guarantee the validity of the received messages...
Basically, the MASTER sends to the SLAVE a message that begins with an !, followed by an Address Letter (eg: A) and the CRC for that letter (in hexadecimal).
eg: !A18
Here's some code:
if (startByte == '!') { // if the Arduino has received a serial message that started with the character '!'
unsigned long startTime = millis(); // set the startTime = to now
int timeout = 1000; // set the timout to 1 second
while (millis() - startTime < timeout && Serial.available() < 3) {
; // wait for the buffer to be filled with 3 characters while doing nothing
}
// Read the received Address and its CRC
receivedAddressLetter[0] = Serial.read();
for (int i=0; i < 2; i++) {
receivedAddressCRC[i] = Serial.read();
}
Now, I have the letter's CRC in an array, with each hexadecimal digit separated:
receivedAddressLetter == {'A'}
receivedAddressCRC == {'1', '8'}
How can I convert the receivedAddressCRC array into an hexadecimal int so that I can compare it with the CRC generated by the SLAVE Arduino???
Should I even convert it into an hexadecimal int??? Please look at the code below and give me some tips.
Thanks!
Here's some example code for the MASTER:
/*
* 8-bit CRC Generator
* by Dallas Temperature
*
* How it works:
* Creates a CRC-8 based on the values of the data[] array
* which, with further code, can then be appended to strings
* or compared with received CRCs.
*/
byte data[1] = {'A'};
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print('!');
Serial.print('A'); // the Slave's address
Serial.print( crc8(data, 1), HEX);
delay(1000);
}
// The CRC-8 generator function
uint8_t crc8(uint8_t *addr, uint8_t len) {
uint8_t crc = 0;
while (len--) {
uint8_t inbyte = *addr++;
for (uint8_t i = 8; i; i--) {
uint8_t mix = (crc ^ inbyte) & 0x01;
crc >>= 1;
if (mix) crc ^= 0x8C;
inbyte >>= 1;
}
}
return crc;
}