/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "string.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ CRC_HandleTypeDef hcrc; UART_HandleTypeDef huart1; UART_HandleTypeDef huart2; /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_USART1_UART_Init(void); static void MX_USART2_UART_Init(void); static void MX_CRC_Init(void); /* USER CODE BEGIN PFP */ /* 宏定义区(可快�?�修改参数) */ #define SLAVE_ADDR 0x30 // 从机地址 #define LED_COIL_ADDR 0x0000 // LED线圈地址 #define TEMP_REG_ADDR 0x1000 // 温度寄存器地�?? /* 全局变量 */ uint8_t modbusRxBuf[256]; // Modbus接收缓冲�?? uint8_t modbusTxBuf[256]; // Modbus发�?�缓冲区 volatile uint8_t rxFlag = 0; // 接收完成标志 void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART2){ HAL_UART_Receive_IT(huart, modbusRxBuf, 1); // 重置接收 } } // 中断回调函数 void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { static uint8_t cnt = 0; if(huart->Instance == USART2){ USART1->TDR = modbusRxBuf[cnt]; if(cnt == 0 && modbusRxBuf[0] != SLAVE_ADDR){ HAL_UART_Receive_IT(huart, modbusRxBuf, 1); // 重置接收 return; } if(++cnt >= 8){ // 严格8字节接收 cnt = 0; rxFlag = 1; } HAL_UART_Receive_IT(huart, &modbusRxBuf[cnt], 1); } } /* CRC计算函数 */ uint16_t CRC16(uint8_t *buf, int len) { uint16_t crc = 0xFFFF; for(int pos=0; pos>= 1; crc ^= 0xA001; }else{ crc >>= 1; } } } return crc; } /* CRC计算函数 */ void AppendCRC(uint8_t* buf, uint8_t len) { uint16_t crc = CRC16(buf, len); buf[len] = crc & 0xFF; // 低字节在前(网页3�? buf[len+1] = crc >> 8; // 高字节在�? } /* 指令处理函数 */ void Process_Modbus(void) { /* 第一层地�?过滤 */ if(modbusRxBuf[0] != SLAVE_ADDR) return; // 非本机地�?直接忽略 /* 第二层CRC验证 */ uint16_t crc = CRC16(modbusRxBuf, 6); if(*(uint16_t*)&modbusRxBuf[6] != crc) return; switch(modbusRxBuf[1]){ case 0x01: // Read Coils if(*(uint16_t*)&modbusRxBuf[2] == LED_COIL_ADDR) { modbusTxBuf[0] = SLAVE_ADDR; modbusTxBuf[1] = 0x01; modbusTxBuf[2] = 0x01; // Byte count if(HAL_GPIO_ReadPin(GPIOA, LED1_Pin) == 1) {modbusTxBuf[3] = 0x01;} else {modbusTxBuf[3] = 0x00;} modbusTxBuf[3] = HAL_GPIO_ReadPin(GPIOA, LED1_Pin) ? 0x01 : 0x00; AppendCRC(modbusTxBuf, 4); HAL_UART_Transmit(&huart2, modbusTxBuf, 6, 100); // 精确发�??6字节 } break; case 0x05: // Write Coil if(*(uint16_t*)&modbusRxBuf[2] == LED_COIL_ADDR) { // 控制LED if(modbusRxBuf[4] == 0xFF) { HAL_GPIO_WritePin(GPIOA, LED1_Pin|LED2_Pin, GPIO_PIN_SET); } else { HAL_GPIO_WritePin(GPIOA, LED1_Pin|LED2_Pin, GPIO_PIN_RESET); } memcpy(modbusTxBuf, modbusRxBuf, 6); // 回显�?6字节 AppendCRC(modbusTxBuf, 6); HAL_UART_Transmit(&huart2, modbusTxBuf, 8, 100); // 写操�?8字节响应 } break; case 0x03: // Read Registers if(*(uint16_t*)&modbusRxBuf[2] == TEMP_REG_ADDR) { modbusTxBuf[0] = SLAVE_ADDR; modbusTxBuf[1] = 0x03; modbusTxBuf[2] = 0x02; // 两个字节数据 uint16_t temp = 25; // 实际�?替换为传感器读取 modbusTxBuf[3] = temp >> 8; modbusTxBuf[4] = temp & 0xFF; AppendCRC(modbusTxBuf, 5); HAL_UART_Transmit(&huart2, modbusTxBuf, 7, 100); // 7字节响应 } break; } memset(modbusTxBuf, 0, sizeof(modbusTxBuf)); // 清空发�?�缓冲区 } /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ 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_USART1_UART_Init(); MX_USART2_UART_Init(); MX_CRC_Init(); /* USER CODE BEGIN 2 */ // 发�?�测试Modbus指令 // uint8_t testCmd[] = {0x01, 0x03, 0x12, 0x34, 0x56, 0x01}; // AppendCRC(testCmd, 6); // 添加CRC校验 // HAL_UART_Transmit(&huart2, testCmd, sizeof(testCmd), 1000); HAL_GPIO_WritePin(GPIOA, LED2_Pin|LED1_Pin, GPIO_PIN_SET); HAL_UART_Transmit(&huart1, modbusTxBuf, 6, 100); HAL_UART_Transmit(&huart2, modbusTxBuf, 6, 100); HAL_Delay(1000); HAL_GPIO_WritePin(GPIOA, LED2_Pin|LED1_Pin, GPIO_PIN_RESET); HAL_Delay(100); //HAL_UART_Receive_IT(&huart1, modbusRxBuf, 8); // 启动接收中断 HAL_UART_Receive_IT(&huart2, modbusRxBuf, 1); // 启动接收中断 /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ if(rxFlag){ rxFlag = 0; Process_Modbus(); HAL_GPIO_WritePin(GPIOA, LED2_Pin, GPIO_PIN_SET); HAL_Delay(100); HAL_GPIO_WritePin(GPIOA, LED2_Pin, GPIO_PIN_RESET); HAL_Delay(100); } } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Configure the main internal regulator output voltage */ HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1); /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1; RCC_OscInitStruct.PLL.PLLN = 8; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /** * @brief CRC Initialization Function * @param None * @retval None */ static void MX_CRC_Init(void) { /* USER CODE BEGIN CRC_Init 0 */ /* USER CODE END CRC_Init 0 */ /* USER CODE BEGIN CRC_Init 1 */ /* USER CODE END CRC_Init 1 */ hcrc.Instance = CRC; hcrc.Init.DefaultPolynomialUse = DEFAULT_POLYNOMIAL_ENABLE; hcrc.Init.DefaultInitValueUse = DEFAULT_INIT_VALUE_ENABLE; hcrc.Init.InputDataInversionMode = CRC_INPUTDATA_INVERSION_NONE; hcrc.Init.OutputDataInversionMode = CRC_OUTPUTDATA_INVERSION_DISABLE; hcrc.InputDataFormat = CRC_INPUTDATA_FORMAT_BYTES; if (HAL_CRC_Init(&hcrc) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN CRC_Init 2 */ /* USER CODE END CRC_Init 2 */ } /** * @brief USART1 Initialization Function * @param None * @retval None */ static void MX_USART1_UART_Init(void) { /* USER CODE BEGIN USART1_Init 0 */ /* USER CODE END USART1_Init 0 */ /* USER CODE BEGIN USART1_Init 1 */ /* USER CODE END USART1_Init 1 */ huart1.Instance = USART1; huart1.Init.BaudRate = 9600; huart1.Init.WordLength = UART_WORDLENGTH_8B; huart1.Init.StopBits = UART_STOPBITS_1; huart1.Init.Parity = UART_PARITY_NONE; huart1.Init.Mode = UART_MODE_TX_RX; huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart1.Init.OverSampling = UART_OVERSAMPLING_16; huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE; huart1.Init.ClockPrescaler = UART_PRESCALER_DIV1; huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } if (HAL_UARTEx_SetTxFifoThreshold(&huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK) { Error_Handler(); } if (HAL_UARTEx_SetRxFifoThreshold(&huart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK) { Error_Handler(); } if (HAL_UARTEx_DisableFifoMode(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } /** * @brief USART2 Initialization Function * @param None * @retval None */ static void MX_USART2_UART_Init(void) { /* USER CODE BEGIN USART2_Init 0 */ /* USER CODE END USART2_Init 0 */ /* USER CODE BEGIN USART2_Init 1 */ /* USER CODE END USART2_Init 1 */ huart2.Instance = USART2; huart2.Init.BaudRate = 9600; huart2.Init.WordLength = UART_WORDLENGTH_8B; huart2.Init.StopBits = UART_STOPBITS_1; huart2.Init.Parity = UART_PARITY_NONE; huart2.Init.Mode = UART_MODE_TX_RX; huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart2.Init.OverSampling = UART_OVERSAMPLING_16; huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE; huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1; huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT; if (HAL_UART_Init(&huart2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART2_Init 2 */ /* USER CODE END USART2_Init 2 */ } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* USER CODE BEGIN MX_GPIO_Init_1 */ /* USER CODE END MX_GPIO_Init_1 */ /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOA, LED2_Pin|LED1_Pin, GPIO_PIN_RESET); /*Configure GPIO pins : LED2_Pin LED1_Pin */ GPIO_InitStruct.Pin = LED2_Pin|LED1_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN MX_GPIO_Init_2 */ /* USER CODE END MX_GPIO_Init_2 */ } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */