From 976ba2d44af3d9dafd9edad1a50b4a12571cf625 Mon Sep 17 00:00:00 2001 From: Elliot Williams Date: Mon, 16 Dec 2019 16:11:07 +0100 Subject: [PATCH] minimalistic framing for UART command copied the uart framing idea from https://github.com/EmanuelFeru/hoverboard-firmware-hack-FOC to use: send $AAAA to start frame then steer, speed as usual and XOR($AAAA, steer, speed) as checksum commands that don't match are ignored, and UART DMA is reset hopefully this will set it up to catch the next one re-send frequently. --- Inc/config.h | 1 + Src/main.c | 26 ++++++++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/Inc/config.h b/Inc/config.h index 319ae81..dfe17d2 100644 --- a/Inc/config.h +++ b/Inc/config.h @@ -9,6 +9,7 @@ #define DELAY_IN_MAIN_LOOP 5 // in ms. default 5. it is independent of all the timing critical stuff. do not touch if you do not know what you are doing. #define TIMEOUT 5 // number of wrong / missing input commands before emergency off +#define START_FRAME 0xAAAA // serial command start-of-frame magic word // ############################### GENERAL ############################### diff --git a/Src/main.c b/Src/main.c index 4cc2624..8c53302 100644 --- a/Src/main.c +++ b/Src/main.c @@ -41,9 +41,10 @@ int cmd2; int cmd3; typedef struct{ - int16_t steer; - int16_t speed; - //uint32_t crc; + uint16_t start_of_frame; + int16_t steer; + int16_t speed; + uint16_t checksum; } Serialcommand; volatile Serialcommand command; @@ -157,7 +158,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, sizeof(command)); #endif #ifdef DEBUG_I2C_LCD @@ -218,12 +219,17 @@ int main(void) { timeout = 0; #endif - #ifdef CONTROL_SERIAL_USART2 - cmd1 = CLAMP((int16_t)command.steer, -1000, 1000); - cmd2 = CLAMP((int16_t)command.speed, -1000, 1000); - - timeout = 0; - #endif +#ifdef CONTROL_SERIAL_USART2 + if (command.start_of_frame == START_FRAME && command.checksum == + (command.start_of_frame ^ command.steer ^ command.speed)) { + cmd1 = CLAMP((int16_t)command.steer, -1000, 1000); + cmd2 = CLAMP((int16_t)command.speed, -1000, 1000); + } else { // restart DMA to hopefully get back in sync + HAL_UART_DMAStop(&huart2); + HAL_UART_Receive_DMA(&huart2, (uint8_t *)&command, sizeof(command)); + } + timeout = 0; +#endif #ifdef CONTROL_MOTOR_TEST if (motor_test_direction == 1) cmd2 += 1;