diff --git a/Makefile b/Makefile index 9281e3a..2fc3cdd 100644 --- a/Makefile +++ b/Makefile @@ -93,7 +93,8 @@ C_INCLUDES = \ -IDrivers/STM32F1xx_HAL_Driver/Inc \ -IDrivers/STM32F1xx_HAL_Driver/Inc/Legacy \ -IDrivers/CMSIS/Device/ST/STM32F1xx/Include \ --IDrivers/CMSIS/Include +-IDrivers/CMSIS/Include \ +-Ilib/crc/src # compile gcc flags diff --git a/lib/crc/src/crc32.h b/lib/crc/src/crc32.h new file mode 100644 index 0000000..8d669a0 --- /dev/null +++ b/lib/crc/src/crc32.h @@ -0,0 +1,40 @@ +/* Simple public domain implementation of the standard CRC32 checksum. + * Outputs the checksum for each file given as a command line argument. + * Invalid file names and files that cause errors are silently skipped. + * The program reads from stdin if it is called with no arguments. */ + +#include +#include +#include + +uint32_t crc32_for_byte(uint32_t r) { + for(int j = 0; j < 8; ++j) + r = (r & 1? 0: (uint32_t)0xEDB88320L) ^ r >> 1; + return r ^ (uint32_t)0xFF000000L; +} + +void crc32(const void *data, size_t n_bytes, uint32_t* crc) { + static uint32_t table[0x100]; + if(!*table) + for(size_t i = 0; i < 0x100; ++i) + table[i] = crc32_for_byte(i); + for(size_t i = 0; i < n_bytes; ++i) + *crc = table[(uint8_t)*crc ^ ((uint8_t*)data)[i]] ^ *crc >> 8; +} +/* +int main(int ac, char** av) { + FILE *fp; + char buf[1L << 15]; + for(int i = ac > 1; i < ac; ++i) + if((fp = i? fopen(av[i], "rb"): stdin)) { + uint32_t crc = 0; + while(!feof(fp) && !ferror(fp)) + crc32(buf, fread(buf, 1, sizeof(buf), fp), &crc); + if(!ferror(fp)) + printf("%08x%s%s\n", crc, ac > 2? "\t": "", ac > 2? av[i]: ""); + if(i) + fclose(fp); + } + return 0; +} +*/ diff --git a/src/main.c b/src/main.c index b737a77..90a6ac1 100644 --- a/src/main.c +++ b/src/main.c @@ -24,6 +24,8 @@ #include "setup.h" #include "config.h" //#include "hd44780.h" +#include "crc32.h" +#include void SystemClock_Config(void); @@ -43,7 +45,7 @@ int cmd3; typedef struct{ int16_t steer; int16_t speed; - //uint32_t crc; + uint32_t crc; } Serialcommand; volatile Serialcommand command; @@ -89,6 +91,19 @@ void poweroff() { } } +bool checkCRC(Serialcommand* command) { + uint32_t crc = 0; + crc32((const void *)command, 4, &crc); // 4 2x uint16_t = 4 bytes + + setScopeChannel(0, (int)crc); // 1: ADC1 + setScopeChannel(1, (int)command->crc); // 2: ADC2 + + + if(command->crc == crc) { + return true; + } + return false; +} int main(void) { HAL_Init(); @@ -150,7 +165,7 @@ int main(void) { #ifdef CONTROL_SERIAL_USART2 UART_Control_Init(); - HAL_UART_Receive_DMA(&huart2, (uint8_t *)&command, 4); + HAL_UART_Receive_DMA(&huart2, (uint8_t *)&command, 8); #endif #ifdef DEBUG_I2C_LCD @@ -212,8 +227,16 @@ int main(void) { #endif #ifdef CONTROL_SERIAL_USART2 + if(checkCRC(&command)) + { cmd1 = CLAMP((int16_t)command.steer, -1000, 1000); cmd2 = CLAMP((int16_t)command.speed, -1000, 1000); + } else + { + cmd1 = 0; + cmd2 = 0; + } + timeout = 0; #endif