二、程序分析:
主要程序分析,其实功能很简单,来看看主函数:- 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();
- /* Configure the system clock */
- SystemClock_Config();
- /* Initialize all configured peripherals */
- MX_GPIO_Init();
- MX_USART2_UART_Init();
- /* USER CODE BEGIN 2 */
- /* USER CODE END 2 */
- /* Infinite loop */
- /* USER CODE BEGIN WHILE */
- while (1)
- {
- HAL_UART_Transmit_IT(&huart2, (uint8_t *)TxBuffer, TXBUFFERSIZE); //发送提示信息
- while (UartReady != SET)
- {
- ;
- }
-
- UartReady = RESET;
-
- HAL_UART_Receive_IT(&huart2, (uint8_t *)RxBuffer, RXBUFFERSIZE); //串口接收命令
-
- while (UartReady != SET)
- {
- ;
- }
-
- UartReady = RESET;
-
- switch (CommandHandle((uint8_t *)RxBuffer)) //根据串口接收的命令执行相应的命令,然后根据结果返回提示
- {
- case 0: //返回不可识别的命令
- HAL_UART_Transmit_IT(&huart2, (uint8_t *)"不能识别的命令!\n\n\n", COUNTOF("不能识别的命令!\n\n\n"));
- break;
- case 1: //返回执行正常命令
- HAL_UART_Transmit_IT(&huart2, (uint8_t *)"执行正常!\n\n\n", COUNTOF("执行正常!\n\n\n"));
- break;
- case 2: //返回Led状态为亮信息
- HAL_UART_Transmit_IT(&huart2, (uint8_t *)"LED状态为:亮!\n\n\n", COUNTOF("LED状态为:亮!\n\n\n"));
- break;
- case 3: //返回Led状态为灭信息
- HAL_UART_Transmit_IT(&huart2, (uint8_t *)"LED状态为:灭!\n\n\n", COUNTOF("LED状态为:灭!\n\n\n"));
- break;
- default:
- ;
- }
- while (UartReady != SET)
- {
- ;
- }
-
- UartReady = RESET;
-
- /* USER CODE END WHILE */
- /* USER CODE BEGIN 3 */
- }
- /* USER CODE END 3 */
- }
其中根据命令执行控制灯程序为:- <p>static uint16_t Commandcmp(uint8_t* pCommand1, uint8_t* pCommand2, uint16_t CommandLength) //命令比较函数,其实字符串比较
- {
- while (CommandLength)
- {
- if ((*pCommand1) != *pCommand2)
- {
- return CommandLength;
- }
- pCommand1++;
- pCommand2++;</p><p> CommandLength--;
- }
- return 0;
- }
- static uint16_t CommandHandle(uint8_t* Command) //命令处理
- {
- if (Commandcmp(Command, (uint8_t *)Command_Lib[0], RXBUFFERSIZE) == 0) //亮灯
- {
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
- return 1;
- }
- else if (Commandcmp(Command, (uint8_t *)Command_Lib[1], RXBUFFERSIZE) == 0) //灭灯
- {
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
- return 1;
- }
- else if (Commandcmp(Command, (uint8_t *)Command_Lib[2], RXBUFFERSIZE) == 0) //反转灯
- {
- HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
- return 1;
- }
- else if (Commandcmp(Command, (uint8_t *)Command_Lib[3], RXBUFFERSIZE) == 0) //查询状态
- {
- if ((GPIOA->ODR & GPIO_PIN_5) != (uint32_t)GPIO_PIN_RESET)
- {
- return 2; //亮
- }
- else
- {
- return 3;//灭
- }
- }
- else
- {
- return 0;//无法识别命令
- }
- }</p>
|