main.c测试
uint8_t uart1RxBuf[64]={0};uint8_t Adc1ConvEnd=0;
uint8_t Adc2ConvEnd=0;int main(void)
{/* USER CODE BEGIN 1 *//* USER CODE END 1 *//* MCU Configuration--------------------------------------------------------*//* Reset of all peripherals, Initializes the Flash interface and the Systick. */HAL_Init();/* USER CODE BEGIN Init *//* USER CODE END Init *//* Configure the system clock */SystemClock_Config();/* USER CODE BEGIN SysInit *//* USER CODE END SysInit *//* Initialize all configured peripherals */MX_GPIO_Init();MX_DMA_Init();/* USER CODE BEGIN 2 *//* Debug: UART3 for debugging and printf */MX_USART3_UART_Init();/* Modbus: UART1 is used to transmit and receive modbus protocol */MX_USART1_UART_Init();HAL_UARTEx_ReceiveToIdle_IT(&huart1, (uint8_t *)&uart1RxBuf, 64);/* EEPROM */if(WriteDefaultEE()!=0){Error_Handler();}/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */while (1){/* Change flash operating parameters over modbus */Modbus_Event();/* USER CODE END WHILE *//* USER CODE BEGIN 3 */}/* USER CODE END 3 */
}/* USER CODE BEGIN 4 */
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{if (huart->Instance == USART1){if (huart->RxEventType == HAL_UART_RXEVENT_IDLE) {modbusData.reFlag=1;HAL_UARTEx_ReceiveToIdle_IT(&huart1, (uint8_t *)&uart1RxBuf, 64);//调用接收中断函数}}UNUSED(Size);
}
CRC16校验
#include <stdio.h>
#include "stdint.h"uint16_t ModRTU_CRC(const uint8_t buf[], uint8_t len)
{uint16_t crc = 0xFFFF;uint16_t pos = 0;uint8_t index = 0;for (pos = 0; pos < len; pos++){crc ^= (unsigned int)buf[pos]; // XOR byte into least sig. byte of CRCfor (index = 8; index != 0; index--) // Loop over each bit{if ((crc & 0x0001) != 0) // If the LSB is set{crc >>= 1; // Shift right and XOR 0xA001crc ^= 0xA001;}else // Else LSB is not set{crc >>= 1; // Just shift right}}}// Note, this number has low and high bytes swapped, so use it accordinglyreturn crc;
}int main()
{uint8_t buf[6]={0x0A ,0x03 ,0x00 ,0x00 ,0x00 ,0x07 };uint8_t crcval=0;crcval=ModRTU_CRC(buf,6);printf("%x \r\n",crcval);return 0;
}