# How to calculate crc16 from Json buffer

I want to store an json string in EEPROM with crc16 calculated.
I can calculate crc16 from a character array, but how to cast a Json buffer character poointer?

//   This is my buffer definition:

StaticJsonBuffer<400> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

//   and my crc16:

uint16_t crc16(char* buf, int len) {
unsigned char x;
unsigned short crc = 0xFFFF;
unsigned int length = len;
while (length--) {
x = crc >> 8 ^ buf(length);
x ^= x >> 4;
crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x << 5)) ^ ((unsigned short)x);
}
return crc;
}


Any help is appreciated

I hope your Arduino has enough RAM for such stuff:

char buffer[400];
uint16_t size = root.printTo(buffer, 400);
uint16_t crc = crc16(buffer, size);


Your crc function has a couple of problems.
First, buf(length) should be buf[length].
Second, and even more important, although the function uses the CRC16 polynomial (same as used in XMODEM), you are calculating it from the end of the buffer backwards. You must calculate it in the order that it is transmitted which is from the first char to the last (unless the other end also calculates the CRC “backwards” - see below (*)). Your code should be this:

uint16_t test_crc16(char* buf, int len) {
unsigned char x;
unsigned short crc = 0xFFFF;

for(int i = 0; i < len;i++) {
x = (crc >> 8) ^ buf[i];
x ^= x >> 4;
crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x << 5)) ^ ((unsigned short)x);
}
return crc;
}


Pete
(*) I see that you are storing it in EEPROM in which case if you encode and decode the CRC with the same function, it won’t really matter.