2021-10-01 04:00 AM
Hello
I'm having trouble calculating crc. I am using STM32F401 with cube ide.
The correct crc occurs on crccalc.com. But I couldn't run CRC-8 with MCU. I have looked at the examples, but when I try it gives different results.
Can you provide a working code example?
2021-10-01 04:17 AM
Sorry, but in what context?
I don't recall the F4 provides a programmable CRC peripheral, is this under SPI? Please elaborate on the application.
2021-10-01 05:01 AM
I'm getting the data with I2C. For example, incoming data;
0x17 0X1D 0x00 0x0A
Data is: 171D00
CRC is : 0A
I must use CRC-8, http://smbus.org/faq/crc8Applet.htm
x8+x2+x+1
i don't know how to calculate this crc-8 with mcu :(
When I calculate via http://crccalc.com, input: 171D00, result is 0A (this is ok)
I couldn't get this result when I calculated it with mcu.
I tried the library here. But the result does not match
https://stm32f4-discovery.net/2015/07/hal-library-10-crc-for-stm32fxxx/
Thanks for help
2021-10-01 05:49 AM
>>I couldn't get this result when I calculated it with mcu.
Right because the MCU has a fixed 32-bit CRC / Polynomial implementation in hardware which is entirely unusable for your application
>>i don't know how to calculate this crc-8 with mcu
A regular software implementation would work
2021-10-01 06:00 AM
// CRC8 0x07 Example sourcer32@gmail.com
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
uint8_t crc_07(uint8_t crc, uint8_t data)
{
int i;
crc = crc ^ data;
for(i=0; i<8; i++)
if (crc & 0x80) // Left shifting, MSB
crc = (crc << 1) ^ 0x07;
else
crc <<= 1;
return(crc);
}
uint8_t crc_07_block(uint8_t crc, int size, uint8_t *buffer)
{
while(size--)
crc = crc_07(crc, *buffer++);
return(crc);
}
uint8_t crc_07_block_quick(uint8_t crc, int size, uint8_t *buffer)
{
const static uint8_t crctbl[] = { // 0x07 Nibble Table, sourcer32@gmail.com
0x00,0x07,0x0E,0x09,0x1C,0x1B,0x12,0x15,
0x38,0x3F,0x36,0x31,0x24,0x23,0x2A,0x2D };
while(size--)
{
crc ^= *buffer++;
crc = (crc << 4) ^ crctbl[(crc >> 4) & 0xF]; // Two rounds of 4-bits
crc = (crc << 4) ^ crctbl[(crc >> 4) & 0xF];
}
return(crc);
}
int main(int argc, char **argv)
{
char test1[] = "123456789";
uint8_t test2[]= { 0x17, 0x1D, 0x00 };
printf("%02X\n", crc_07_block(0x00, strlen(test1), (uint8_t *)test1));
printf("%02X\n", crc_07_block(0x00, sizeof(test2), test2));
putchar('\n');
printf("%02X\n", crc_07_block_quick(0x00, strlen(test1), (uint8_t *)test1));
printf("%02X\n", crc_07_block_quick(0x00, sizeof(test2), test2));
putchar('\n');
return(1);
}