活动介绍

uint16_t USART_ReceiveData(USART_TypeDef* USARTx) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); /* Receive Data */ return (uint16_t)(USARTx->DR & (uint16_t)0x01FF); }这段代码的作用

时间: 2025-09-01 18:11:53 AIGC 浏览: 6
<think>好的,我现在需要仔细分析用户的问题,关于STM32的USART_ReceiveData函数的工作原理和功能,特别是与DR寄存器的关系。首先,用户提供的代码和引用资料是关键,我得先理解这些内容。 首先看用户提供的代码段:USART_ReceiveData函数接收一个USARTx参数,返回一个uint16_t类型的数据。函数内部先进行参数检查,然后返回USARTx->DR与0x01FF的按位与结果。这里的DR寄存器是数据寄存器,用于接收或发送数据。根据引用[1],函数返回的是DR寄存器中的值,并且通过掩码0x01FF,可能因为DR寄存器的高位有其他用途或者保留位,所以需要屏蔽掉高位,只保留低9位的数据? 然后引用[2]中提到,读取DR寄存器可以清除RXNE(接收寄存器非空)标志位。这说明USART_ReceiveData函数不仅获取数据,还可能有清除状态标志的作用。需要确认这一点是否正确。根据STM32的参考手册,当读取DR寄存器时,RXNE标志会被自动清除,所以这个函数在读取数据的同时,确实会清除该标志,以便后续数据的接收。 接下来,我需要组织这些信息,解释函数的实现原理。DR寄存器是USART的数据寄存器,当有数据到达时,硬件会将数据存入DR,并设置RXNE标志。调用USART_ReceiveData函数时,会读取DR的值,同时清除RXNE标志。而使用0x01FF的掩码可能是因为DR寄存器在某些型号中是9位的(例如支持奇偶校验时,数据位可能是9位),所以需要保留低9位的数据,高位可能包含状态信息或其他位,需要屏蔽掉。 另外,用户提到的返回值是uint16_t类型,但实际数据可能只有8或9位,因此使用掩码确保只获取有效数据部分。同时,函数中的assert_param检查确保传入的USARTx是有效的,防止错误操作。 现在需要回答用户的问题,包括函数的功能、实现原理、DR寄存器的处理方式,以及如何与状态标志交互。需要引用用户提供的两个引用来支持解释,尤其是引用[2]中提到的读取DR会清除RXNE标志,这样函数的作用不仅仅是读取数据,还管理状态标志,确保后续数据能够正确接收。 可能还需要提到,当使用USART_ReceiveData时,通常需要先检查RXNE标志是否置位(通过USART_GetFlagStatus或USART_GetITStatus),确保数据已经准备好再读取,避免读到旧数据。这也是为什么在接收数据时,常见流程是先检测标志位,再读取数据的原因。 最后,生成相关问题需要考虑用户可能对STM32的USART通信机制、其他相关函数(如发送函数)、错误处理、中断使用等方面感兴趣。因此,相关问题可以涉及如何检测接收错误、如何结合中断使用这个函数、数据长度的影响等。</think>### STM32 USART_ReceiveData 函数解析 #### 功能概述 `USART_ReceiveData` 是STM32中用于从USART数据寄存器(DR)读取接收数据的函数。其核心功能包括: 1. **数据读取**:从DR寄存器中获取已接收的串口数据。 2. **标志位管理**:自动清除接收寄存器非空标志位(`RXNE`)[^2]。 #### 实现原理 1. **寄存器操作** DR寄存器是USART模块的核心寄存器,用于存储发送或接收的数据。接收时,当数据从物理接口传输完成后,硬件会自动将数据存入DR寄存器,并置位`RXNE`标志(表示数据可读)。 函数通过以下操作实现数据读取: ```c return (uint16_t)(USARTx->DR & (uint16_t)0x01FF); ``` - **掩码操作**:`0x01FF` 用于保留DR寄存器的低9位数据。USART支持多种数据长度(如8位或9位),若配置为9位模式,DR寄存器的第9位会包含有效数据,因此需通过掩码确保正确截取[^1]。 - **自动清除RXNE标志**:读取DR寄存器后,硬件会自动清除`RXNE`标志,无需手动操作[^2]。 2. **参数校验** `assert_param(IS_USART_ALL_PERIPH(USARTx))` 用于验证传入的USART外设指针是否有效,防止操作非法地址。 #### 典型应用场景 1. **查询模式** 需先检测`RXNE`标志是否置位,再调用此函数读取数据: ```c if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == SET) { uint16_t data = USART_ReceiveData(USART1); } ``` 2. **中断模式** 在USART接收中断服务程序(ISR)中直接调用该函数,无需手动检测标志位。 #### 注意事项 - **数据对齐**:若配置为8位数据模式,实际有效数据为DR寄存器的低8位,但返回值仍为`uint16_t`类型,需根据需求进行类型转换。 - **错误处理**:读取数据前应检查`USART_FLAG_ORE`(溢出错误)等标志,避免数据丢失或错误[^2]。 --- ### 相关问题
阅读全文

相关推荐

这是我的main.c文件/* 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" #include "dma.h" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "bsp.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 ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ uint8_t receiveData[50]; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ void HAL_UART_IDLECallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART1) { // ֹͣDMA��ֹ��ͻ HAL_UART_DMAStop(huart); // ����������ݳ��� uint16_t recv_len = sizeof(receiveData) - __HAL_DMA_GET_COUNTER(huart->hdmarx); // ���ͽ��յ������� HAL_UART_Transmit_DMA(&huart1, receiveData, recv_len); // ����DMA���� HAL_UART_Receive_DMA(huart, receiveData, sizeof(receiveData)); } } /* 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_DMA_Init(); MX_USART1_UART_Init(); MX_TIM1_Init(); MX_TIM2_Init(); MX_TIM3_Init(); /* USER CODE BEGIN 2 */ // ʹ��UART1�Ŀ����ж� __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE); // ����DMA���գ�ѭ��ģʽ�� HAL_UART_Receive_DMA(&huart1, receiveData, sizeof(receiveData)); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ 这是我的usart.c /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ #include "string.h" #include "stm32f1xx_hal.h" typedef struct __FILE FILE; #include "bsp.h" uint8_t rx_buffer[128]; #define RX_BUFFER_SIZE 32 // F103C8T6 RAM��С����С������ uint8_t uart_rx_buffer[RX_BUFFER_SIZE]; // ������ջ����� /* USER CODE END 0 */ UART_HandleTypeDef huart1; DMA_HandleTypeDef hdma_usart1_rx; DMA_HandleTypeDef hdma_usart1_tx; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ HAL_UART_Receive_IT(&huart1,uart_rx_buffer,sizeof(rx_buffer)); __HAL_DMA_DISABLE_IT(&hdma_usart1_rx,DMA_IT_HT); /* USER CODE END USART1_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART1 DMA Init */ /* USART1_RX Init */ hdma_usart1_rx.Instance = DMA1_Channel5; hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_rx.Init.Mode = DMA_NORMAL; hdma_usart1_rx.Init.Priority = DMA_PRIORITY_HIGH; if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart1_rx); /* USART1_TX Init */ hdma_usart1_tx.Instance = DMA1_Channel4; hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_tx.Init.Mode = DMA_NORMAL; hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx); /* USART1 interrupt Init */ HAL_NVIC_SetPriority(USART1_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USART1 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); HAL_DMA_DeInit(uartHandle->hdmatx); /* USART1 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ int fputc(int ch, FILE * str) { HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 10); return ch; } /* USER CODE END 1 */ 这是usart.h /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.h * @brief This file contains all the function prototypes for * the usart.c file ****************************************************************************** * @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 */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USART_H__ #define __USART_H__ #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "main.h" /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ extern UART_HandleTypeDef huart1; /* USER CODE BEGIN Private defines */ /* USER CODE END Private defines */ void MX_USART1_UART_Init(void); /* USER CODE BEGIN Prototypes */ /* USER CODE END Prototypes */ #ifdef __cplusplus } #endif #endif /* __USART_H__ */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * @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" #include "stm32f1xx_it.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "bsp.h" #include "usart.h" #include "dma.h" #include "uart_app.h" // ���ͷ�ļ� /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ extern TIM_HandleTypeDef htim1; extern DMA_HandleTypeDef hdma_usart1_rx; extern DMA_HandleTypeDef hdma_usart1_tx; extern UART_HandleTypeDef huart1; /* USER CODE BEGIN EV */ /* USER CODE END EV */ /******************************************************************************/ /* Cortex-M3 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles Non maskable interrupt. */ void NMI_Handler(void) { /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ while (1) { } /* USER CODE END NonMaskableInt_IRQn 1 */ } /** * @brief This function handles Hard fault interrupt. */ void HardFault_Handler(void) { /* USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_HardFault_IRQn 0 */ /* USER CODE END W1_HardFault_IRQn 0 */ } } /** * @brief This function handles Memory management fault. */ void MemManage_Handler(void) { /* USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ /* USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** * @brief This function handles Prefetch fault, memory access fault. */ void BusFault_Handler(void) { /* USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_BusFault_IRQn 0 */ /* USER CODE END W1_BusFault_IRQn 0 */ } } /** * @brief This function handles Undefined instruction or illegal state. */ void UsageFault_Handler(void) { /* USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ /* USER CODE END W1_UsageFault_IRQn 0 */ } } /** * @brief This function handles System service call via SWI instruction. */ void SVC_Handler(void) { /* USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */ /* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** * @brief This function handles Debug monitor. */ void DebugMon_Handler(void) { /* USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** * @brief This function handles Pendable request for system service. */ void PendSV_Handler(void) { /* USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */ /* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32F1xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f1xx.s). */ /******************************************************************************/ /** * @brief This function handles DMA1 channel4 global interrupt. */ void DMA1_Channel4_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */ /* USER CODE END DMA1_Channel4_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart1_tx); /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */ /* USER CODE END DMA1_Channel4_IRQn 1 */ } /** * @brief This function handles DMA1 channel5 global interrupt. */ void DMA1_Channel5_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */ /* USER CODE END DMA1_Channel5_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart1_rx); /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */ /* USER CODE END DMA1_Channel5_IRQn 1 */ } /** * @brief This function handles TIM1 capture compare interrupt. */ void TIM1_CC_IRQHandler(void) { /* USER CODE BEGIN TIM1_CC_IRQn 0 */ /* USER CODE END TIM1_CC_IRQn 0 */ HAL_TIM_IRQHandler(&htim1); /* USER CODE BEGIN TIM1_CC_IRQn 1 */ /* USER CODE END TIM1_CC_IRQn 1 */ } /** * @brief This function handles USART1 global interrupt. */ void USART1_IRQHandler(void) { /* USER CODE BEGIN USART1_IRQn 0 */ /* USER CODE END USART1_IRQn 0 */ HAL_UART_IRQHandler(&huart1); /* USER CODE BEGIN USART1_IRQn 1 */ HAL_UART_Receive_DMA(&huart1, rx_buffer, sizeof(rx_buffer)); __HAL_DMA_ENABLE_IT(&hdma_usart1_rx, DMA_IT_HT); /* 检测空闲中断标志 */ if(__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE)) { __HAL_UART_CLEAR_IDLEFLAG(&huart1); // 清除标志 HAL_UART_IDLECallback(&huart1); // 调用回调 } HAL_UART_IRQHandler(&huart1); /* USER CODE END USART1_IRQn 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ 这是stm32f1xx_it.c 下面是logic.c的代码 #include "logic.h" char rx_data[21]={0}; uint8_t rx_flag=0; /* 业务逻辑初始化 */ void Logic_Init(void) { /* 初始化业务逻辑 */ } /* 业务逻辑处理 */ void Logic_Process(void) { /* 处理业务逻辑 */ static uint32_t last_time = 0; uint32_t current_time = System_GetTick(); if (current_time - last_time > 1000) { last_time = current_time; printf("System running...\r\n"); } } //uart void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) { rx_flag=1; } void uart_proc(void) { if(rx_flag==1) { memset(rx_data,0,21); rx_flag=0; strncpy(rx_data,(const char *)rx_buffer,20); rx_data[20]=0; printf("%s",rx_buffer); printf("\n%d",strlen((const char *)rx_buffer)); memset(rx_buffer,0,128); } } 这是bsp.h #ifndef __BSP_H #define __BSP_H // 标准库 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdarg.h> #include "main.h" #include "stm32f1xx_hal.h" #include "usart.h" // 其他用户头文件 #include "system.h" #include "schedule.h" #include "periph.h" #include "logic.h" #define buffer_size 10 extern uint8_t led_buffer; extern uint32_t fre_data[4][buffer_size]; extern uint32_t fre_tim2,fre_tim3; extern uint32_t duty_tim2,duty_tim3; extern uint32_t adc_data[2][20]; extern double adc_1,adc_2; extern uint8_t rx_buffer[128]; #endif /* __BSP_H */

/* 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" #include "dma.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* 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 ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { if(huart == &huart2) { RS485_2_RX; // RS485 ?????? memset(usart2_data.rbuff, 0, usart2_data.len);//???????????? HAL_UART_Receive_DMA(&huart2,usart2_data.rbuff,MAX);//?????DMA???? usart2_data.sdflag = 0; //????????????? } else if(huart == &huart3) { usart3_data.sdflag = 0; // 发送完成,重置标志 } } /* 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_DMA_Init(); MX_USART1_UART_Init(); MX_USART2_UART_Init(); MX_USART3_UART_Init(); /* USER CODE BEGIN 2 */ RS485_2_TX; HAL_UART_Transmit(&huart1,"123456",3,1000); printf("串口三\n"); HAL_Delay(1); RS485_2_RX; Uart1_Config(); Uart2_Config(); Uart3_Config(); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { // HAL_Delay(1500); // HAL_GPIO_TogglePin(LED1_GPIO_Port,LED1_Pin); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ uint16_t MAX = 100; struct usart usart1_data = {0}; struct usart usart2_data = {0}; struct usart usart3_data = {0}; /* USER CODE END 0 */ UART_HandleTypeDef huart1; UART_HandleTypeDef huart2; UART_HandleTypeDef huart3; DMA_HandleTypeDef hdma_usart1_rx; DMA_HandleTypeDef hdma_usart1_tx; DMA_HandleTypeDef hdma_usart2_rx; DMA_HandleTypeDef hdma_usart2_tx; DMA_HandleTypeDef hdma_usart3_rx; DMA_HandleTypeDef hdma_usart3_tx; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } /* USART2 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART2_Init 2 */ /* USER CODE END USART2_Init 2 */ } /* USART3 init function */ void MX_USART3_UART_Init(void) { /* USER CODE BEGIN USART3_Init 0 */ /* USER CODE END USART3_Init 0 */ /* USER CODE BEGIN USART3_Init 1 */ /* USER CODE END USART3_Init 1 */ huart3.Instance = USART3; huart3.Init.BaudRate = 115200; huart3.Init.WordLength = UART_WORDLENGTH_8B; huart3.Init.StopBits = UART_STOPBITS_1; huart3.Init.Parity = UART_PARITY_NONE; huart3.Init.Mode = UART_MODE_TX_RX; huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart3.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&huart3) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART3_Init 2 */ /* USER CODE END USART3_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART1 DMA Init */ /* USART1_RX Init */ hdma_usart1_rx.Instance = DMA1_Channel5; hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_rx.Init.Mode = DMA_NORMAL; hdma_usart1_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart1_rx); /* USART1_TX Init */ hdma_usart1_tx.Instance = DMA1_Channel4; hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_tx.Init.Mode = DMA_NORMAL; hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx); /* USART1 interrupt Init */ HAL_NVIC_SetPriority(USART1_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } else if(uartHandle->Instance==USART2) { /* USER CODE BEGIN USART2_MspInit 0 */ /* USER CODE END USART2_MspInit 0 */ /* USART2 clock enable */ __HAL_RCC_USART2_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ GPIO_InitStruct.Pin = GPIO_PIN_2; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_3; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART2 DMA Init */ /* USART2_RX Init */ hdma_usart2_rx.Instance = DMA1_Channel6; hdma_usart2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart2_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart2_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart2_rx.Init.Mode = DMA_NORMAL; hdma_usart2_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart2_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart2_rx); /* USART2_TX Init */ hdma_usart2_tx.Instance = DMA1_Channel7; hdma_usart2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart2_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart2_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart2_tx.Init.Mode = DMA_NORMAL; hdma_usart2_tx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart2_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart2_tx); /* USART2 interrupt Init */ HAL_NVIC_SetPriority(USART2_IRQn, 0, 1); HAL_NVIC_EnableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspInit 1 */ /* USER CODE END USART2_MspInit 1 */ } else if(uartHandle->Instance==USART3) { /* USER CODE BEGIN USART3_MspInit 0 */ /* USER CODE END USART3_MspInit 0 */ /* USART3 clock enable */ __HAL_RCC_USART3_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /**USART3 GPIO Configuration PB10 ------> USART3_TX PB11 ------> USART3_RX */ GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_11; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* USART3 DMA Init */ /* USART3_RX Init */ hdma_usart3_rx.Instance = DMA1_Channel3; hdma_usart3_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart3_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart3_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart3_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart3_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart3_rx.Init.Mode = DMA_NORMAL; hdma_usart3_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart3_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart3_rx); /* USART3_TX Init */ hdma_usart3_tx.Instance = DMA1_Channel2; hdma_usart3_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart3_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart3_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart3_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart3_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart3_tx.Init.Mode = DMA_NORMAL; hdma_usart3_tx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart3_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart3_tx); /* USART3 interrupt Init */ HAL_NVIC_SetPriority(USART3_IRQn, 0, 2); HAL_NVIC_EnableIRQ(USART3_IRQn); /* USER CODE BEGIN USART3_MspInit 1 */ /* USER CODE END USART3_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USART1 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); HAL_DMA_DeInit(uartHandle->hdmatx); /* USART1 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } else if(uartHandle->Instance==USART2) { /* USER CODE BEGIN USART2_MspDeInit 0 */ /* USER CODE END USART2_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART2_CLK_DISABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3); /* USART2 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); HAL_DMA_DeInit(uartHandle->hdmatx); /* USART2 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspDeInit 1 */ /* USER CODE END USART2_MspDeInit 1 */ } else if(uartHandle->Instance==USART3) { /* USER CODE BEGIN USART3_MspDeInit 0 */ /* USER CODE END USART3_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART3_CLK_DISABLE(); /**USART3 GPIO Configuration PB10 ------> USART3_TX PB11 ------> USART3_RX */ HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10|GPIO_PIN_11); /* USART3 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); HAL_DMA_DeInit(uartHandle->hdmatx); /* USART3 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART3_IRQn); /* USER CODE BEGIN USART3_MspDeInit 1 */ /* USER CODE END USART3_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ //重定向printf int fputc(int c,FILE *f) { HAL_UART_Transmit(&huart1,(uint8_t *)&c,1,1000); return c; } void Uart1_Config(void) { HAL_UART_Receive_DMA(&huart1, usart1_data.rbuff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);//使能串口1空闲中断 } void Uart2_Config(void) { HAL_UART_Receive_DMA(&huart2, usart2_data.rbuff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart2,UART_IT_IDLE);//使能串口2空闲中断 } void Uart3_Config(void) { HAL_UART_Receive_DMA(&huart3, usart3_data.rbuff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart3,UART_IT_IDLE);//使能串口3空闲中断 } //函数名称:void RS485_Usart3_DMA_Send(uint8_t *buf,uint8_t len) //功能描述:串口2采用RS485总线实现DMA发送 //参数说明:*buf 数据帧的指针,len数据帧的长度 void RS485_Usart2_DMA_Send(uint8_t *buf,uint8_t len) { uint8_t i; if(usart2_data.sdflag==0) //如果串口发送处于完成状态 { RS485_2_TX; //发送控制置位到发送状态——使能高电平正在发送 usart2_data.sdflag=1; //发送完成标识置位———有发送 for( i=0;i<10;i++); //短暂延时,使EN进入高电平稳定状态 if(HAL_UART_Transmit_DMA(&huart2, buf,len)!= HAL_OK) //判断是否发送正常,如果出现异常则进入异常中断函数 { Error_Handler(); } } } /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * @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" #include "stm32f1xx_it.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "usart.h" #include <string.h> /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ extern DMA_HandleTypeDef hdma_usart1_rx; extern DMA_HandleTypeDef hdma_usart1_tx; extern DMA_HandleTypeDef hdma_usart2_rx; extern DMA_HandleTypeDef hdma_usart2_tx; extern DMA_HandleTypeDef hdma_usart3_rx; extern DMA_HandleTypeDef hdma_usart3_tx; extern UART_HandleTypeDef huart1; extern UART_HandleTypeDef huart2; extern UART_HandleTypeDef huart3; /* USER CODE BEGIN EV */ /* USER CODE END EV */ /******************************************************************************/ /* Cortex-M3 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles Non maskable interrupt. */ void NMI_Handler(void) { /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ while (1) { } /* USER CODE END NonMaskableInt_IRQn 1 */ } /** * @brief This function handles Hard fault interrupt. */ void HardFault_Handler(void) { /* USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_HardFault_IRQn 0 */ /* USER CODE END W1_HardFault_IRQn 0 */ } } /** * @brief This function handles Memory management fault. */ void MemManage_Handler(void) { /* USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ /* USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** * @brief This function handles Prefetch fault, memory access fault. */ void BusFault_Handler(void) { /* USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_BusFault_IRQn 0 */ /* USER CODE END W1_BusFault_IRQn 0 */ } } /** * @brief This function handles Undefined instruction or illegal state. */ void UsageFault_Handler(void) { /* USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ /* USER CODE END W1_UsageFault_IRQn 0 */ } } /** * @brief This function handles System service call via SWI instruction. */ void SVC_Handler(void) { /* USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */ /* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** * @brief This function handles Debug monitor. */ void DebugMon_Handler(void) { /* USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** * @brief This function handles Pendable request for system service. */ void PendSV_Handler(void) { /* USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */ /* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32F1xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f1xx.s). */ /******************************************************************************/ /** * @brief This function handles DMA1 channel2 global interrupt. */ void DMA1_Channel2_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel2_IRQn 0 */ /* USER CODE END DMA1_Channel2_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart3_tx); /* USER CODE BEGIN DMA1_Channel2_IRQn 1 */ /* USER CODE END DMA1_Channel2_IRQn 1 */ } /** * @brief This function handles DMA1 channel3 global interrupt. */ void DMA1_Channel3_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel3_IRQn 0 */ /* USER CODE END DMA1_Channel3_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart3_rx); /* USER CODE BEGIN DMA1_Channel3_IRQn 1 */ /* USER CODE END DMA1_Channel3_IRQn 1 */ } /** * @brief This function handles DMA1 channel4 global interrupt. */ void DMA1_Channel4_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */ /* USER CODE END DMA1_Channel4_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart1_tx); /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */ /* USER CODE END DMA1_Channel4_IRQn 1 */ } /** * @brief This function handles DMA1 channel5 global interrupt. */ void DMA1_Channel5_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */ /* USER CODE END DMA1_Channel5_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart1_rx); /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */ /* USER CODE END DMA1_Channel5_IRQn 1 */ } /** * @brief This function handles DMA1 channel6 global interrupt. */ void DMA1_Channel6_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel6_IRQn 0 */ /* USER CODE END DMA1_Channel6_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart2_rx); /* USER CODE BEGIN DMA1_Channel6_IRQn 1 */ /* USER CODE END DMA1_Channel6_IRQn 1 */ } /** * @brief This function handles DMA1 channel7 global interrupt. */ void DMA1_Channel7_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel7_IRQn 0 */ /* USER CODE END DMA1_Channel7_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart2_tx); /* USER CODE BEGIN DMA1_Channel7_IRQn 1 */ /* USER CODE END DMA1_Channel7_IRQn 1 */ } /** * @brief This function handles USART1 global interrupt. */ void USART1_IRQHandler(void) { /* USER CODE BEGIN USART1_IRQn 0 */ //�жϿ��б�־λ�Ƿ���λ if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET) { __HAL_UART_CLEAR_IDLEFLAG(&huart1);//��������жϱ�־λ HAL_UART_DMAStop(&huart1);//ֹͣDMA�������� usart1_data.len = MAX - __HAL_DMA_GET_COUNTER(huart1.hdmarx);//����˴ν��յ������ݳ��� usart1_data.rdflag = 1;//���ý�����ɱ�־ // #if debug //�����ã����Խ��յ�������ת����ȥ������һ������֮�������¿���DMA���� if(usart1_data.rdflag == 1 && usart3_data.sdflag == 0) { // printf("USART1接收: %s\n", usart1_data.rbuff); // HAL_UART_Transmit_DMA(&huart1,usart1_data.rbuff,usart1_data.len); usart3_data.sdflag = 1; if(HAL_UART_Transmit_DMA(&huart3,usart1_data.rbuff,usart1_data.len) != HAL_OK) { printf("USART3发送失败\n"); // 调试打印 usart3_data.sdflag = 0; } HAL_Delay(10); memset(usart1_data.rbuff, 0, usart1_data.len); usart1_data.rdflag = 0; HAL_UART_Receive_DMA(&huart1, usart1_data.rbuff, MAX); } // #endif } /* USER CODE END USART1_IRQn 0 */ HAL_UART_IRQHandler(&huart1); /* USER CODE BEGIN USART1_IRQn 1 */ /* USER CODE END USART1_IRQn 1 */ } /** * @brief This function handles USART2 global interrupt. */ void USART2_IRQHandler(void) { /* USER CODE BEGIN USART2_IRQn 0 */ uint32_t tmp_flag = 0; uint32_t temp; tmp_flag =__HAL_UART_GET_FLAG(&huart2,UART_FLAG_IDLE); //获取IDLE标志位 if((tmp_flag != RESET)) //idle标志被置位 { __HAL_UART_CLEAR_IDLEFLAG(&huart2); //清除标志位 HAL_UART_DMAStop(&huart2); //停止DMA传输,防止串行总线其他帧的干扰 temp = __HAL_DMA_GET_COUNTER(&hdma_usart2_rx); //获取DMA中未传输的数据个数 usart2_data.len = MAX - temp; //总计数减去未传输的数据个数,得到实际接收的数据个数 usart2_data.rdflag = 1; // 接收完成标志位置1 //如果是从设备,此处可以用条件语句判断是否应该应答主机的呼叫(从设备地址与呼叫地址一致),如果是就发送(应答)。下面是直接发送收到的信息 RS485_Usart2_DMA_Send(usart2_data.rbuff,usart2_data.len); //RS485发送数据 usart2_data.rdflag = 0; // 接收完成标志位置0 //下面的语句通常在回调函数内调用,在此处调用也可以 //HAL_UART_Receive_DMA(&huart2,usart2_data.rbuff,MAX);//重新打开DMA接收 } /* USER CODE END USART2_IRQn 0 */ HAL_UART_IRQHandler(&huart2); /* USER CODE BEGIN USART2_IRQn 1 */ /* USER CODE END USART2_IRQn 1 */ } /** * @brief This function handles USART3 global interrupt. */ void USART3_IRQHandler(void) { /* USER CODE BEGIN USART3_IRQn 0 */ printf("USART3中断触发\n"); // 新增:打印中断触发提示 if (__HAL_UART_GET_FLAG(&huart3, UART_FLAG_IDLE) != RESET) { printf("USART3检测到空闲中断\n"); // 新增:确认IDLE标志触发 __HAL_UART_CLEAR_IDLEFLAG(&huart3);//��������жϱ�־λ HAL_UART_DMAStop(&huart3);//ֹͣDMA�������� usart3_data.len = MAX - __HAL_DMA_GET_COUNTER(huart3.hdmarx);//����˴ν��յ������ݳ��� usart3_data.rdflag = 1;//���ý�����ɱ�־ // #if debug //�����ã����Խ��յ�������ת����ȥ������һ������֮�������¿���DMA���� if(usart3_data.rdflag == 1) { printf("4G:%s\n",usart3_data.rbuff); HAL_UART_Transmit_DMA(&huart1,usart3_data.rbuff,usart3_data.len); HAL_Delay(10); memset(usart3_data.rbuff, 0, usart3_data.len); usart3_data.rdflag = 0; HAL_UART_Receive_DMA(&huart3, usart3_data.rbuff, MAX); } // #endif } /* USER CODE END USART3_IRQn 0 */ HAL_UART_IRQHandler(&huart3); /* USER CODE BEGIN USART3_IRQn 1 */ /* USER CODE END USART3_IRQn 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ 目前代码实现串口一转发接收到的AT指令到串口三,已知串口三与4G模块通信,为何通过串口一发送AT指令,没有回复,它不打印USART3发送失败,也不打印printf("4G:%s\n",usart3_data.rbuff);且串口一正常接收到AT指令并能打印

这是main.c和usart.c的代码,看看能不能将数字0.1.2正确发送给串口3。main.c代码“#include "./SYSTEM/sys/sys.h" #include "./SYSTEM/usart/usart.h" #include "./SYSTEM/delay/delay.h" #include "./USMART/usmart.h" #include "./BSP/LED/led.h" #include "./BSP/LCD/lcd.h" #include "./BSP/ADC/adc.h" #include "./stm32f1xx_it.h" #include "./BSP/BEEP/beep.h" #include "./BSP/KEY/key.h" #include "./BSP/EXTI/exti.h" #include <math.h> #include <string.h> // 字符串处理 #include <stdarg.h> // 添加变参支持 // 蓝牙相关定义 #define BLE_USART USART3 // 蓝牙使用USART3 #define BLE_BAUDRATE 115200 // 蓝牙模块波特率 #define BLE_CONNECTED_GPIO GPIOA #define BLE_CONNECTED_PIN GPIO_PIN_4 // STA状态引脚PA4 // 震动模式定义(数字形式) #define VIBRATION_OFF 0 // 停止震动 #define VIBRATION_SHORT 1 // 短震动 #define VIBRATION_LONG 2 // 长震动 // 标准定义 #define ADC_DMA_BUF_SIZE 200 /* ADC DMA采集 BUF大小 */ // 震动马达控制引脚定义 #define VIBRATION_MOTOR_PORT GPIOC #define VIBRATION_MOTOR_PIN GPIO_PIN_0 // 震动状态变量 static uint8_t current_vibration_mode = VIBRATION_OFF; static uint32_t last_vibration_time = 0; uint16_t g_adc_dma_buf[ADC_DMA_BUF_SIZE]; /* ADC DMA BUF */ uint8_t sendbuf[20]; uint8_t alert_status = 0; // 0=正常, 1=警告, 2=报警 uint16_t i; uint16_t adc_CO; uint32_t sum; float temp; uint16_t THRESHOLD=100; // 报警阈值 (根据实际传感器量程调整) uint16_t WARN=2; extern uint8_t g_adc_dma_sta; /* DMA传输状态标志, 0,未完成; 1, 已完成 */ //功能 void Check_Alerts(void); void button(void); void ControlVibrationMotor(uint8_t mode); void VibrationMotor_Init(void); void BLE_Init(void); // 蓝牙初始化函数 //void BLE_SendCommand(char cmd); // 蓝牙发送命令函数 uint8_t Is_BLE_Connected(void); // 蓝牙连接状态检测 float adc_to_eField(uint16_t adc_value, float cal_slope, float cal_offset, float v_ref) { // 1. ADC转电压(带数字滤波) static float filtered_voltage = 0.0f; // 滤波后电压值 const float filter_factor = 0.2f; // 低通滤波系数 float raw_voltage = (float)adc_value / 4095.0f * v_ref; filtered_voltage = filtered_voltage * (1 - filter_factor) + raw_voltage * filter_factor; // 2. 应用校准公式(线性转换) float e_field = (filtered_voltage - 0.8) * 100; // 修正零点偏移 // 3. 灵敏度增强处理 const float noise_threshold = 0.05f; // 噪声阈值 if(fabsf(e_field) < noise_threshold) { e_field = 0.0f; // 抑制微小波动 } // 4. 确保物理有效性 e_field = (e_field < 0.0f) ? 0.0f : e_field; return e_field; } void VibrationMotor_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; // 使能GPIOC时钟 __HAL_RCC_GPIOC_CLK_ENABLE(); // 配置PC0为推挽输出 GPIO_InitStruct.Pin = VIBRATION_MOTOR_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(VIBRATION_MOTOR_PORT, &GPIO_InitStruct); // 初始状态关闭 HAL_GPIO_WritePin(VIBRATION_MOTOR_PORT, VIBRATION_MOTOR_PIN, GPIO_PIN_RESET); } // 控制震动马达 (简化版) void ControlVibrationMotor(uint8_t mode) { uint32_t current_time = HAL_GetTick(); switch(mode) { case VIBRATION_OFF: HAL_GPIO_WritePin(VIBRATION_MOTOR_PORT, VIBRATION_MOTOR_PIN, GPIO_PIN_RESET); break; case VIBRATION_SHORT: if(current_time - last_vibration_time > 1000) { // 短震动 - 200ms开启 HAL_GPIO_WritePin(VIBRATION_MOTOR_PORT, VIBRATION_MOTOR_PIN, GPIO_PIN_SET); last_vibration_time = current_time; } else if(current_time - last_vibration_time > 200) { HAL_GPIO_WritePin(VIBRATION_MOTOR_PORT, VIBRATION_MOTOR_PIN, GPIO_PIN_RESET); } break; case VIBRATION_LONG: // 长震动 - 持续开启 HAL_GPIO_WritePin(VIBRATION_MOTOR_PORT, VIBRATION_MOTOR_PIN, GPIO_PIN_SET); break; } } // 蓝牙初始化 void BLE_Init(void) { usart_init(115200); /* 串口初始化为115200 */ delay_ms(100); //发送AT指令配置蓝牙模块 u3_printf("AT+UART=115200,8,0,1\r\n"); delay_ms(100); u3_printf("AT+MODE=M\r\n"); // 设置为主设备模式 delay_ms(100); u3_printf("AT+CONNADD=3CAB726F689C\r\n"); // 连接从机MAC地址(需替换) delay_ms(100); u3_printf("AT+AUTOCONN=ON\r\n"); // 开启自动重连*/ } // 发送蓝牙命令 /*void BLE_SendCommand(char cmd) { USART3_RX_STA = 0; if ((uint32_t)cmd <= 0XFF) { while ((USART3->SR & 0X40) == 0); //等待上一次数据发送完成 USART3->DR = (uint32_t)cmd; } else u3_printf("%s\r\n", cmd);//发送命令 }*/ // 检测蓝牙连接状态 uint8_t Is_BLE_Connected(void) { // 当STA引脚为高电平时表示已连接 return HAL_GPIO_ReadPin(BLE_CONNECTED_GPIO, BLE_CONNECTED_PIN); } void Ble_IoInit_Enhanced(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_AFIO_CLK_ENABLE(); __HAL_AFIO_REMAP_SWJ_NOJTAG();// 禁用JTAG但保留SWD调试接口 // WKUP引脚配置PA15 GPIO_InitStruct.Pin = GPIO_PIN_15; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); // STA引脚配置PA4 GPIO_InitStruct.Pin = GPIO_PIN_4; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); // 唤醒序列 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_RESET); HAL_Delay(50); HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_SET); HAL_Delay(100); usart_init(115200); /* 串口初始化为115200 */ } //主函数 int main(void) { HAL_Init(); /* 初始化HAL库 */ sys_stm32_clock_init(RCC_PLL_MUL9); /* 设置时钟, 72Mhz */ delay_init(72); /* 延时初始化 */ usart_init(115200); /* 串口初始化为115200 */ // usart3_init(115200); led_init(); /* 初始化LED */ lcd_init(); /* 初始化LCD */ adc_init(); extix_init(); /* 初始化外部中断输入 */ beep_init(); /* 初始化蜂鸣器 */ key_init(); /* 初始化按键 */ VibrationMotor_Init(); BLE_Init(); // 初始化蓝牙模块 Ble_IoInit_Enhanced(); Ble_ReceData(); /* 优化中断优先级设置 */ HAL_NVIC_SetPriority(ADC_ADCX_DMACx_IRQn, 0, 0); // ADC最高优先级 HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 1, 0); // DMA中等优先级 HAL_NVIC_SetPriority(USART3_IRQn, 2, 0); // 蓝牙最低优先级 HAL_NVIC_EnableIRQ(USART3_IRQn); /* 初始化ADC DMA采集 */ adc_dma_init((uint32_t)&g_adc_dma_buf); /* LCD显示初始化 */ lcd_show_string(30, 50, 300, 24, 24, "The system is working.", RED); lcd_show_string(30, 90, 300, 24, 24, "WARN:2 v/m ", BLUE); lcd_show_string(30, 130, 300, 24, 24, "THRESHOLD= 100v/m ", BLUE); lcd_show_string(30, 170, 300, 32, 24, "VALUE: v/m", BLUE); /* 启动ADC DMA采集 */ adc_dma_enable(ADC_DMA_BUF_SIZE); while (1) { Check_Alerts(); button(); ControlVibrationMotor(current_vibration_mode); /* 计算DMA采集到的ADC数据的平均值 */ if (g_adc_dma_sta == 1) { sum = 0; for (i = 0; i < ADC_DMA_BUF_SIZE; i++) /* 累加 */ { sum += g_adc_dma_buf[i]; } adc_CO = sum / ADC_DMA_BUF_SIZE; /* 取平均值 */ temp = adc_to_eField(adc_CO, 0.8f, // 校准斜率 (uT/V) 100.0f, // 校准偏移 (uT) 3.3f); // ADC参考电压 /* 显示结果 */ lcd_show_xnum(120, 170, temp, 4, 24, 0, RED); /* 显示电磁场强度值 */ g_adc_dma_sta = 0; /* 清除DMA采集完成状态标志 */ adc_dma_enable(ADC_DMA_BUF_SIZE); /* 启动下一次ADC DMA采集 */ } HAL_Delay(100); } } void Check_Alerts(void) { char *num0 = "0"; char *num1 = "1"; char *num2 = "2"; if (temp > THRESHOLD) // 超过临界值 { LED0(0); // 红灯亮 current_vibration_mode = VIBRATION_LONG; // 长震动模式 //USART_SendData(USART3, '2');//向串口3发送数据 HAL_UART_Transmit(& g_uart3_handle, (uint8_t*)num2, strlen(num2), 100); while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); } else if (temp >= WARN && temp <= THRESHOLD) // 警告范围内 { LED1(1); // 绿灯灭 LED0(0); // 红灯亮 current_vibration_mode = VIBRATION_SHORT; // 短震动模式 //USART_SendData(USART3, '1');//向串口3发送数据 HAL_UART_Transmit(& g_uart3_handle, (uint8_t*)num1, strlen(num1), 100); while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); } else // 正常范围 { LED1(0); // 绿灯亮 LED0(1); // 红灯灭 current_vibration_mode = VIBRATION_OFF; // 停止震动 //USART_SendData(USART3, '0');//向串口3发送数据 HAL_UART_Transmit(& g_uart3_handle, (uint8_t*)num0, strlen(num0), 100); while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); } // 控制蜂鸣器(可选) if (temp > THRESHOLD) { //BEEP(1); // 报警时蜂鸣器响 } else { BEEP(0); // 正常时蜂鸣器关闭 } } void button(void) { if (KEY1 == 0) // 按键1按下,增加阈值 { HAL_Delay(50); if(THRESHOLD < 150) { THRESHOLD += 10; if(THRESHOLD > 150) THRESHOLD = 150; } lcd_show_xnum(185, 130, THRESHOLD, 4, 24, 0, BLUE); // 更新显示 while (!KEY1); // 等待按键释放 } else if (KEY0 == 0) // 按键0按下,减小阈值 { HAL_Delay(50); if(THRESHOLD > 1) { THRESHOLD -= 10; if(THRESHOLD < 1) THRESHOLD = 1; } lcd_show_xnum(185, 130, THRESHOLD, 4, 24, 0, BLUE); // 更新显示 while (!KEY0); // 等待按键释放 } }”和“#include "./SYSTEM/sys/sys.h" #include "./SYSTEM/usart/usart.h" #include <string.h> #include <stdio.h> #include <stdarg.h> #include "./SYSTEM/delay/delay.h" #define USART_FLAG_CTS ((uint16_t)0x0200) #define USART3_MAX_RECV_LEN 1024 #define USART3_MAX_SEND_LEN 600 uint8_t USART3_RX_BUF[USART3_MAX_RECV_LEN] = {0}; uint8_t USART3_TX_BUF[USART3_MAX_SEND_LEN] = {0}; uint16_t USART3_RX_STA = 0; uint8_t alarm_data = 0; volatile uint8_t usart3_tx_busy; /* 如果使用os,则包括下面的头文件即可. */ #if SYS_SUPPORT_OS #include "os.h" /* os 使用 */ #endif /******************************************************************************************/ /* 加入以下代码, 支持printf函数, 而不需要选择use MicroLIB */ #if 1 #if (__ARMCC_VERSION >= 6010050) /* 使用AC6编译器时 */ __asm(".global __use_no_semihosting\n\t"); /* 声明不使用半主机模式 */ __asm(".global __ARM_use_no_argv \n\t"); /* AC6下需要声明main函数为无参数格式,否则部分例程可能出现半主机模式 */ #else /* 使用AC5编译器时, 要在这里定义__FILE 和 不使用半主机模式 */ #pragma import(__use_no_semihosting) struct __FILE { int handle; }; #endif /* 不使用半主机模式,至少需要重定义_ttywrch\_sys_exit\_sys_command_string函数,以同时兼容AC6和AC5模式 */ int _ttywrch(int ch) { ch = ch; return ch; } /* 定义_sys_exit()以避免使用半主机模式 */ void _sys_exit(int x) { x = x; } char *_sys_command_string(char *cmd, int len) { return NULL; } /* FILE 在 stdio.h里面定义. */ FILE __stdout; /* MDK下需要重定义fputc函数, printf函数最终会通过调用fputc输出字符串到串口 */ int fputc(int ch, FILE *f) { while ((USART_UX->SR & 0X40) == 0); /* 等待上一个字符发送完成 */ USART_UX->DR = (uint8_t)ch; /* 将要发送的字符 ch 写入到DR寄存器 */ return ch; } #endif /******************************************************************************************/ void USART_SendData(USART_TypeDef* USARTx, uint16_t Data)//给串口发送数据的函数 { assert_param(IS_USART_ALL_PERIPH(USART3)); assert_param(IS_USART_DATA(Data)); USART3->DR = (Data & (uint16_t)0x01FF); } FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG)//状态检测函数 { FlagStatus bitstatus = RESET; assert_param(IS_USART_ALL_PERIPH(USART3)); assert_param(IS_USART_FLAG(USART_FLAG)); if (USART_FLAG == USART_FLAG_CTS) { assert_param(IS_USART_123_PERIPH(USART3)); } if ((USART3->SR & USART_FLAG) != (uint16_t)RESET) { bitstatus = SET; } else { bitstatus = RESET; } return bitstatus; } void u3_printf(char *fmt, ...) { uint16_t i, j; va_list ap; va_start(ap, fmt); vsprintf((char *)USART3_TX_BUF, fmt, ap); va_end(ap); i = strlen((const char *)USART3_TX_BUF); //此次发送数据的长度 for (j = 0; j < i; j++) //循环发送数据 { while (USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); //循环发送,直到发送完毕 USART_SendData(USART3, USART3_TX_BUF[j]); } } void Ble_ReceData(void)//蓝牙接收数据处理 { uint16_t i = 0; uint16_t len = 0; //有数据来了 if (USART3_RX_STA & 0x8000) { len = USART3_RX_STA & 0X7FFF; USART3_RX_BUF[len] = 0; //添加结束符 USART3_RX_STA = 0; printf("R:"); for (i = 0; i < len; i++) { while (USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); //循环发送,直到发送完毕 USART_SendData(USART3, USART3_RX_BUF[i]); } memset((char *)USART3_RX_BUF, 0x00, len); //串口接收缓冲区清0 u3_printf("\r\n"); } } //////////////////////////////////////////////////////////////////// #if USART_EN_RX /*如果使能了接收*/ /* 接收缓冲, 最大USART_REC_LEN个字节. */ uint8_t g_usart_rx_buf[USART_REC_LEN]; uint16_t g_usart_rx_sta = 0; uint8_t g_rx_buffer[RXBUFFERSIZE]; /* HAL库使用的串口接收缓冲 */ UART_HandleTypeDef g_uart3_handle; /* UART句柄 */ /*串口X初始化函数*/ void usart_init(uint32_t baudrate) { /*UART 初始化设置*/ g_uart3_handle.Instance = USART_UX; /* USART_UX */ g_uart3_handle.Init.BaudRate = baudrate; /* 波特率 */ g_uart3_handle.Init.WordLength = UART_WORDLENGTH_8B; /* 字长为8位数据格式 */ g_uart3_handle.Init.StopBits = UART_STOPBITS_1; /* 一个停止位 */ g_uart3_handle.Init.Parity = UART_PARITY_NONE; /* 无奇偶校验位 */ g_uart3_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE; /* 无硬件流控 */ g_uart3_handle.Init.Mode = UART_MODE_TX_RX; /* 收发模式 */ HAL_UART_Init(&g_uart3_handle); /* HAL_UART_Init()会使能UART1 */ /* 该函数会开启接收中断:标志位UART_IT_RXNE,并且设置接收缓冲以及接收缓冲接收最大数据量 */ HAL_UART_Receive_IT(&g_uart3_handle, (uint8_t *)g_rx_buffer, RXBUFFERSIZE); } /** * @brief UART底层初始化函数 * @param huart: UART句柄类型指针 * @note 此函数会被HAL_UART_Init()调用 * 完成时钟使能,引脚配置,中断配置 * @retval 无 */ void HAL_UART_MspInit(UART_HandleTypeDef *huart) { GPIO_InitTypeDef gpio_init_struct; if (huart->Instance == USART_UX) /* 如果是串口3,进行串口3 MSP初始化 */ { USART_TX_GPIO_CLK_ENABLE(); /* 使能串口TX脚时钟 */ USART_RX_GPIO_CLK_ENABLE(); /* 使能串口RX脚时钟 */ USART_UX_CLK_ENABLE(); /* 使能串口时钟 */ gpio_init_struct.Pin = USART_TX_GPIO_PIN; /* 串口发送引脚号 */ gpio_init_struct.Mode = GPIO_MODE_AF_PP; /* 复用推挽输出 */ gpio_init_struct.Pull = GPIO_PULLUP; /* 上拉 */ gpio_init_struct.Speed = GPIO_SPEED_FREQ_HIGH; /* IO速度设置为高速 */ HAL_GPIO_Init(USART_TX_GPIO_PORT, &gpio_init_struct); gpio_init_struct.Pin = USART_RX_GPIO_PIN; /* 串口RX脚 模式设置 */ gpio_init_struct.Mode = GPIO_MODE_AF_INPUT; HAL_GPIO_Init(USART_RX_GPIO_PORT, &gpio_init_struct); /* 串口RX脚 必须设置成输入模式 */ #if USART_EN_RX HAL_NVIC_EnableIRQ(USART_UX_IRQn); /* 使能USART3中断通道 */ HAL_NVIC_SetPriority(USART_UX_IRQn, 3, 3); /* 组2,最低优先级:抢占优先级3,子优先级3 */ #endif } } /** * @brief 串口数据接收回调函数 数据处理在这里进行 * @param huart:串口句柄 * @retval 无 */ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { uint8_t usart3_tx_busy = 0; // 发送状态标志 if (huart->Instance == USART_UX) /* 如果是串口1 */ { if ((g_usart_rx_sta & 0x8000) == 0) /* 接收未完成 */ { if (g_usart_rx_sta & 0x4000) /* 接收到了0x0d(即回车键) */ { if (g_rx_buffer[0] != 0x0a) /* 接收到的不是0x0a(即不是换行键) */ { g_usart_rx_sta = 0; /* 接收错误,重新开始 */ } else /* 接收到的是0x0a(即换行键) */ { g_usart_rx_sta |= 0x8000; /* 接收完成了 */ } } else /* 还没收到0X0d(即回车键) */ { if (g_rx_buffer[0] == 0x0d) g_usart_rx_sta |= 0x4000; else { g_usart_rx_buf[g_usart_rx_sta & 0X3FFF] = g_rx_buffer[0]; g_usart_rx_sta++; if (g_usart_rx_sta > (USART_REC_LEN - 1)) { g_usart_rx_sta = 0; /* 接收数据错误,重新开始接收 */ } } } } usart3_tx_busy = 0; // 清除发送忙标志 HAL_UART_Receive_IT(&g_uart3_handle, (uint8_t *)g_rx_buffer, RXBUFFERSIZE); } } // 发送完成回调函数 void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART3) { usart3_tx_busy = 0; // 清除发送忙标志 } } /** * @brief 串口1中断服务函数 * @param 无 * @retval 无 */ void USART_UX_IRQHandler(void) { #if SYS_SUPPORT_OS /* 使用OS */ OSIntEnter(); #endif HAL_UART_IRQHandler(&g_uart3_handle); /* 调用HAL库中断处理公用函数 */ #if SYS_SUPPORT_OS /* 使用OS */ OSIntExit(); #endif } #endif”

单片机甲:/* 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" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include <string.h> #include <stdio.h> // 添加stdio.h以支持sprintf函数 /* 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 ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ uint8_t rxBuffer1[20]; // USART1接收缓冲区 uint8_t rxBuffer3[20]; // USART3接收缓冲区 uint8_t txBuffer[50]; // 发送缓冲区 uint8_t irStatus = 0; // 红外传感器状态 uint8_t lastIrStatus = 0; // 上一次红外传感器状态 /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ void IR_Detection(void); // 添加函数声明 /* 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_TIM2_Init(); MX_USART1_UART_Init(); MX_USART3_UART_Init(); /* USER CODE BEGIN 2 */ HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); // 启动USART1接收中断 HAL_UART_Receive_IT(&huart1, rxBuffer1, 1); // 启动USART3接收中断,波特率9600 HAL_UART_Receive_IT(&huart3, rxBuffer3, 1); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ // 调用红外检测函数 IR_Detection(); // 根据红外传感器状态控制PWM输出 if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_15) == GPIO_PIN_SET) { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2, 0); } else { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2, 180); } // 添加延时以避免过度占用CPU 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}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ // 统一的UART接收回调函数 void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART1) { // USART1数据处理逻辑 // 例如:可以在这里添加对USART1接收到的数据的处理 // 重新启动接收 HAL_UART_Receive_IT(&huart1, rxBuffer1, 1); } else if(huart->Instance == USART3) { // USART3数据处理逻辑 // 例如:可以在这里添加对USART3接收到的数据的处理 // 重新启动接收 HAL_UART_Receive_IT(&huart3, rxBuffer3, 1); } } // 红外传感器检测函数 void IR_Detection(void) { // 读取红外传感器状态 irStatus = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_15); // 根据当前状态发送对应信息 if(irStatus == GPIO_PIN_SET) { // 障碍物检测到 sprintf((char*)txBuffer, "IR Sensor: No Obstacle\r\n"); } else { // 无障碍物 sprintf((char*)txBuffer, "IR Sensor: Obstacle Detected\r\n"); } // 通过两个串口发送信息 HAL_UART_Transmit(&huart1, txBuffer, strlen((char*)txBuffer), 100); HAL_UART_Transmit(&huart3, txBuffer, strlen((char*)txBuffer), 100); // 添加1秒延时 HAL_Delay(500); } /* 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 */ 单片机乙:/* 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" #include "adc.h" #include "tim.h" #include "usart.h" #include "gpio.h" #include <stdio.h> #include <string.h> /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* ??LED?? */ #define LED_PIN GPIO_PIN_13 #define LED_GPIO_PORT GPIOC /* ???? */ #define FILTER_DEPTH 5 // ???????? /* ???? */ #define LIGHT_THRESHOLD_LOW 1000 // ????? #define LIGHT_THRESHOLD_HIGH 3000 // ????? /* ?????? */ #define MOTOR_MIN_SPEED 50 // ??????(????) #define MOTOR_MAX_SPEED 199 // ??????(???????) /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ uint16_t light_value = 0; // ????? uint16_t light_filtered = 0; // ??????? uint16_t motor_speed = 0; // ???? uint16_t filter_buffer[FILTER_DEPTH]; // ????? uint8_t filter_index = 0; // ???? uint8_t led_state = 0; // LED?? char uart_buffer[100]; // ????? uint8_t rxBuffer1[20]; // USART1????? - ???? uint8_t rxBuffer3[20]; // USART3????? - ???? /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ uint16_t Read_LightSensor(void); uint16_t ApplyFilter(uint16_t new_value); void Control_Motor(uint16_t light_value); void Send_Data_To_UART(uint16_t light_value, uint16_t motor_speed); /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /** * ???????? */ uint16_t Read_LightSensor(void) { uint16_t adc_value = 0; /* ??ADC?? */ if(HAL_ADC_Start(&hadc1) != HAL_OK) { Error_Handler(); } /* ?????? */ if(HAL_ADC_PollForConversion(&hadc1, 10) == HAL_OK) { /* ??ADC? */ adc_value = HAL_ADC_GetValue(&hadc1); } return adc_value; } /** * ?????? */ uint16_t ApplyFilter(uint16_t new_value) { uint32_t sum = 0; /* ???????? */ filter_buffer[filter_index] = new_value; filter_index = (filter_index + 1) % FILTER_DEPTH; /* ????? */ for(int i = 0; i < FILTER_DEPTH; i++) { sum += filter_buffer[i]; } return (uint16_t)(sum / FILTER_DEPTH); } /** * ?????? */ void Control_Motor(uint16_t light_value) { // ????????????? // ??ADC????0-4095 // ???????MOTOR_MIN_SPEED-MOTOR_MAX_SPEED // ?????,?????? motor_speed = (light_value * (MOTOR_MAX_SPEED - MOTOR_MIN_SPEED)) / 4095 + MOTOR_MIN_SPEED; // ???????? if(motor_speed > MOTOR_MAX_SPEED) motor_speed = MOTOR_MAX_SPEED; if(motor_speed < MOTOR_MIN_SPEED) motor_speed = 0; // ??????????,???? // ??PWM??? __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, motor_speed); } /** * ??????? */ void Send_Data_To_UART(uint16_t light_value, uint16_t motor_speed) { /* ????? */ sprintf(uart_buffer, "Light: %d, Motor Speed: %d\r\n", light_value, motor_speed); /* ???? */ HAL_UART_Transmit(&huart1, (uint8_t *)uart_buffer, strlen(uart_buffer), 100); } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* ???????? */ for(int i = 0; i < FILTER_DEPTH; i++) { filter_buffer[i] = 0; } /* 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_ADC1_Init(); MX_USART1_UART_Init(); MX_USART3_UART_Init(); MX_TIM4_Init(); /* USER CODE BEGIN 2 */ /* ??PWM?? */ HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1); /* ??USART3???? */ HAL_UART_Receive_IT(&huart3, rxBuffer3, 1); /* ??????? */ HAL_UART_Transmit(&huart1, (uint8_t *)"System initialized! Light sensor and motor control enabled.\r\n", 62, 100); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ /* ????? */ light_value = Read_LightSensor(); /* ???? */ light_filtered = ApplyFilter(light_value); /* ?????? */ Control_Motor(light_filtered); /* ??????????? */ Send_Data_To_UART(light_filtered, motor_speed); /* ????????LED - ????????? */ if(light_filtered < LIGHT_THRESHOLD_LOW) { led_state = 1; // ???,LED?? } else if(light_filtered > LIGHT_THRESHOLD_HIGH) { led_state = 0; // ???,LED?? } HAL_GPIO_WritePin(LED_GPIO_PORT, LED_PIN, led_state ? GPIO_PIN_SET : 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}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC; PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ // UART?????? void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART1) { // ??USART1?????? // ?????? HAL_UART_Receive_IT(&huart1, rxBuffer1, 1); } else if(huart->Instance == USART3) { // ??USART3?????? // ??:????????????????? // ?????? HAL_UART_Receive_IT(&huart3, rxBuffer3, 1); } } /* 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 */ 串口无法给对方发送信息

/* 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" #include "dma.h" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* 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 ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { if(huart == &huart2) { RS485_2_RX; // RS485 ?????? memset(usart2_data.rbuff, 0, usart2_data.len);//???????????? HAL_UART_Receive_DMA(&huart2,usart2_data.rbuff,MAX);//?????DMA???? usart2_data.sdflag = 0; //????????????? } } /* 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_DMA_Init(); MX_USART1_UART_Init(); MX_USART2_UART_Init(); MX_USART3_UART_Init(); MX_TIM6_Init(); /* USER CODE BEGIN 2 */ RS485_2_TX; HAL_UART_Transmit(&huart1,(uint8_t *)"123456",3,1000); printf("串口\r\n"); HAL_Delay(1); RS485_2_RX;//RS485进入接收模式 Uart1_Config(); Uart2_Config(); Uart3_Config(); //4G // Lte_Check();//确认设备连接 // Close_Heart();//关闭心跳包 /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { // HAL_Delay(1500); // HAL_GPIO_TogglePin(LED1_GPIO_Port,LED1_Pin); if(Device_Net_State==0) { G4_Connect_Net(); } else if(Device_Net_State==1) { MQTT_Connect(); } // else if(Device_Net_State==2) // { // if(PUBLISH_Period[0]>=PUBLISH_Period[1]) // {//定时器6中断累加,需要初始化 // PUBLISH_Period[0]=0; // MQTT_Publish();//上传数据 // } // } HAL_Delay(1000); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ struct usart usart1_data = {0}; struct usart usart2_data = {0}; struct usart usart3_data = {0}; /* USER CODE END 0 */ UART_HandleTypeDef huart1; UART_HandleTypeDef huart2; UART_HandleTypeDef huart3; DMA_HandleTypeDef hdma_usart1_rx; DMA_HandleTypeDef hdma_usart1_tx; DMA_HandleTypeDef hdma_usart2_rx; DMA_HandleTypeDef hdma_usart2_tx; DMA_HandleTypeDef hdma_usart3_rx; DMA_HandleTypeDef hdma_usart3_tx; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } /* USART2 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART2_Init 2 */ /* USER CODE END USART2_Init 2 */ } /* USART3 init function */ void MX_USART3_UART_Init(void) { /* USER CODE BEGIN USART3_Init 0 */ /* USER CODE END USART3_Init 0 */ /* USER CODE BEGIN USART3_Init 1 */ /* USER CODE END USART3_Init 1 */ huart3.Instance = USART3; huart3.Init.BaudRate = 115200; huart3.Init.WordLength = UART_WORDLENGTH_8B; huart3.Init.StopBits = UART_STOPBITS_1; huart3.Init.Parity = UART_PARITY_NONE; huart3.Init.Mode = UART_MODE_TX_RX; huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart3.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&huart3) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART3_Init 2 */ /* USER CODE END USART3_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART1 DMA Init */ /* USART1_RX Init */ hdma_usart1_rx.Instance = DMA1_Channel5; hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_rx.Init.Mode = DMA_NORMAL; hdma_usart1_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart1_rx); /* USART1_TX Init */ hdma_usart1_tx.Instance = DMA1_Channel4; hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_tx.Init.Mode = DMA_NORMAL; hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx); /* USART1 interrupt Init */ HAL_NVIC_SetPriority(USART1_IRQn, 1, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } else if(uartHandle->Instance==USART2) { /* USER CODE BEGIN USART2_MspInit 0 */ /* USER CODE END USART2_MspInit 0 */ /* USART2 clock enable */ __HAL_RCC_USART2_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ GPIO_InitStruct.Pin = GPIO_PIN_2; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_3; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART2 DMA Init */ /* USART2_RX Init */ hdma_usart2_rx.Instance = DMA1_Channel6; hdma_usart2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart2_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart2_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart2_rx.Init.Mode = DMA_NORMAL; hdma_usart2_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart2_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart2_rx); /* USART2_TX Init */ hdma_usart2_tx.Instance = DMA1_Channel7; hdma_usart2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart2_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart2_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart2_tx.Init.Mode = DMA_NORMAL; hdma_usart2_tx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart2_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart2_tx); /* USART2 interrupt Init */ HAL_NVIC_SetPriority(USART2_IRQn, 3, 0); HAL_NVIC_EnableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspInit 1 */ /* USER CODE END USART2_MspInit 1 */ } else if(uartHandle->Instance==USART3) { /* USER CODE BEGIN USART3_MspInit 0 */ /* USER CODE END USART3_MspInit 0 */ /* USART3 clock enable */ __HAL_RCC_USART3_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /**USART3 GPIO Configuration PB10 ------> USART3_TX PB11 ------> USART3_RX */ GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_11; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* USART3 DMA Init */ /* USART3_RX Init */ hdma_usart3_rx.Instance = DMA1_Channel3; hdma_usart3_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart3_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart3_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart3_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart3_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart3_rx.Init.Mode = DMA_NORMAL; hdma_usart3_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart3_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart3_rx); /* USART3_TX Init */ hdma_usart3_tx.Instance = DMA1_Channel2; hdma_usart3_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart3_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart3_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart3_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart3_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart3_tx.Init.Mode = DMA_NORMAL; hdma_usart3_tx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart3_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart3_tx); /* USART3 interrupt Init */ HAL_NVIC_SetPriority(USART3_IRQn, 2, 0); HAL_NVIC_EnableIRQ(USART3_IRQn); /* USER CODE BEGIN USART3_MspInit 1 */ /* USER CODE END USART3_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USART1 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); HAL_DMA_DeInit(uartHandle->hdmatx); /* USART1 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } else if(uartHandle->Instance==USART2) { /* USER CODE BEGIN USART2_MspDeInit 0 */ /* USER CODE END USART2_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART2_CLK_DISABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3); /* USART2 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); HAL_DMA_DeInit(uartHandle->hdmatx); /* USART2 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspDeInit 1 */ /* USER CODE END USART2_MspDeInit 1 */ } else if(uartHandle->Instance==USART3) { /* USER CODE BEGIN USART3_MspDeInit 0 */ /* USER CODE END USART3_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART3_CLK_DISABLE(); /**USART3 GPIO Configuration PB10 ------> USART3_TX PB11 ------> USART3_RX */ HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10|GPIO_PIN_11); /* USART3 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); HAL_DMA_DeInit(uartHandle->hdmatx); /* USART3 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART3_IRQn); /* USER CODE BEGIN USART3_MspDeInit 1 */ /* USER CODE END USART3_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ //重定向printf int fputc(int c,FILE *f) { HAL_UART_Transmit(&huart1,(uint8_t *)&c,1,1000); return c; } void Uart1_Config(void) { HAL_UART_Receive_DMA(&huart1, usart1_data.rbuff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);//使能串口1空闲中断 } void Uart2_Config(void) { HAL_UART_Receive_DMA(&huart2, usart2_data.rbuff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart2,UART_IT_IDLE);//使能串口2空闲中断 } void Uart3_Config(void) { HAL_UART_Receive_DMA(&huart3, usart3_data.rbuff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart3,UART_IT_IDLE);//使能串口3空闲中断 } //函数名称:void RS485_Usart3_DMA_Send(uint8_t *buf,uint8_t len) //功能描述:串口2采用RS485总线实现DMA发送 //参数说明:*buf 数据帧的指针,len数据帧的长度 void RS485_Usart2_DMA_Send(uint8_t *buf,uint8_t len) { uint8_t i; if(usart2_data.sdflag==0) //如果串口发送处于完成状态 { RS485_2_TX; //发送控制置位到发送状态——使能高电平正在发送 usart2_data.sdflag=1; //发送完成标识置位———有发送 for( i=0;i<10;i++); //短暂延时,使EN进入高电平稳定状态 if(HAL_UART_Transmit_DMA(&huart2, buf,len)!= HAL_OK) //判断是否发送正常,如果出现异常则进入异常中断函数 { Error_Handler(); } } } /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * @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" #include "stm32f1xx_it.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "usart.h" #include "string.h" #include "tim.h" #include "4G.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ extern TIM_HandleTypeDef htim6; extern DMA_HandleTypeDef hdma_usart1_rx; extern DMA_HandleTypeDef hdma_usart1_tx; extern DMA_HandleTypeDef hdma_usart2_rx; extern DMA_HandleTypeDef hdma_usart2_tx; extern DMA_HandleTypeDef hdma_usart3_rx; extern DMA_HandleTypeDef hdma_usart3_tx; extern UART_HandleTypeDef huart1; extern UART_HandleTypeDef huart2; extern UART_HandleTypeDef huart3; /* USER CODE BEGIN EV */ /* USER CODE END EV */ /******************************************************************************/ /* Cortex-M3 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles Non maskable interrupt. */ void NMI_Handler(void) { /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ while (1) { } /* USER CODE END NonMaskableInt_IRQn 1 */ } /** * @brief This function handles Hard fault interrupt. */ void HardFault_Handler(void) { /* USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_HardFault_IRQn 0 */ /* USER CODE END W1_HardFault_IRQn 0 */ } } /** * @brief This function handles Memory management fault. */ void MemManage_Handler(void) { /* USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ /* USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** * @brief This function handles Prefetch fault, memory access fault. */ void BusFault_Handler(void) { /* USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_BusFault_IRQn 0 */ /* USER CODE END W1_BusFault_IRQn 0 */ } } /** * @brief This function handles Undefined instruction or illegal state. */ void UsageFault_Handler(void) { /* USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ /* USER CODE END W1_UsageFault_IRQn 0 */ } } /** * @brief This function handles System service call via SWI instruction. */ void SVC_Handler(void) { /* USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */ /* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** * @brief This function handles Debug monitor. */ void DebugMon_Handler(void) { /* USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** * @brief This function handles Pendable request for system service. */ void PendSV_Handler(void) { /* USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */ /* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32F1xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f1xx.s). */ /******************************************************************************/ /** * @brief This function handles DMA1 channel2 global interrupt. */ void DMA1_Channel2_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel2_IRQn 0 */ /* USER CODE END DMA1_Channel2_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart3_tx); /* USER CODE BEGIN DMA1_Channel2_IRQn 1 */ /* USER CODE END DMA1_Channel2_IRQn 1 */ } /** * @brief This function handles DMA1 channel3 global interrupt. */ void DMA1_Channel3_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel3_IRQn 0 */ /* USER CODE END DMA1_Channel3_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart3_rx); /* USER CODE BEGIN DMA1_Channel3_IRQn 1 */ /* USER CODE END DMA1_Channel3_IRQn 1 */ } /** * @brief This function handles DMA1 channel4 global interrupt. */ void DMA1_Channel4_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */ /* USER CODE END DMA1_Channel4_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart1_tx); /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */ /* USER CODE END DMA1_Channel4_IRQn 1 */ } /** * @brief This function handles DMA1 channel5 global interrupt. */ void DMA1_Channel5_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */ /* USER CODE END DMA1_Channel5_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart1_rx); /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */ /* USER CODE END DMA1_Channel5_IRQn 1 */ } /** * @brief This function handles DMA1 channel6 global interrupt. */ void DMA1_Channel6_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel6_IRQn 0 */ /* USER CODE END DMA1_Channel6_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart2_rx); /* USER CODE BEGIN DMA1_Channel6_IRQn 1 */ /* USER CODE END DMA1_Channel6_IRQn 1 */ } /** * @brief This function handles DMA1 channel7 global interrupt. */ void DMA1_Channel7_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel7_IRQn 0 */ /* USER CODE END DMA1_Channel7_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart2_tx); /* USER CODE BEGIN DMA1_Channel7_IRQn 1 */ /* USER CODE END DMA1_Channel7_IRQn 1 */ } /** * @brief This function handles USART1 global interrupt. */ void USART1_IRQHandler(void) { /* USER CODE BEGIN USART1_IRQn 0 */ //�жϿ��б�־λ�Ƿ���λ if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET) { __HAL_UART_CLEAR_IDLEFLAG(&huart1);//��������жϱ�־λ HAL_UART_DMAStop(&huart1);//ֹͣDMA�������� usart1_data.len = MAX - __HAL_DMA_GET_COUNTER(huart1.hdmarx);//����˴ν��յ������ݳ��� usart1_data.rdflag = 1;//���ý�����ɱ�־ // #if debug //�����ã����Խ��յ�������ת����ȥ������һ������֮�������¿���DMA���� if(usart1_data.rdflag == 1 && usart3_data.sdflag == 0) { // printf("USART1接收: %s\n", usart1_data.rbuff); // HAL_UART_Transmit_DMA(&huart1,usart1_data.rbuff,usart1_data.len); usart3_data.sdflag = 1; if(HAL_UART_Transmit(&huart3,usart1_data.rbuff,usart1_data.len,100) != HAL_OK) { printf("USART3发送失败\n"); // 调试打印 } memset(usart1_data.rbuff, 0, usart1_data.len); usart1_data.rdflag = 0; usart3_data.sdflag = 0; HAL_UART_Receive_DMA(&huart1, usart1_data.rbuff, MAX); } // #endif } /* USER CODE END USART1_IRQn 0 */ HAL_UART_IRQHandler(&huart1); /* USER CODE BEGIN USART1_IRQn 1 */ /* USER CODE END USART1_IRQn 1 */ } /** * @brief This function handles USART2 global interrupt. */ void USART2_IRQHandler(void) { /* USER CODE BEGIN USART2_IRQn 0 */ uint32_t tmp_flag = 0; uint32_t temp; tmp_flag =__HAL_UART_GET_FLAG(&huart2,UART_FLAG_IDLE); //获取IDLE标志位 if((tmp_flag != RESET)) //idle标志被置位 { __HAL_UART_CLEAR_IDLEFLAG(&huart2); //清除标志位 HAL_UART_DMAStop(&huart2); //停止DMA传输,防止串行总线其他帧的干扰 temp = __HAL_DMA_GET_COUNTER(&hdma_usart2_rx); //获取DMA中未传输的数据个数 usart2_data.len = MAX - temp; //总计数减去未传输的数据个数,得到实际接收的数据个数 usart2_data.rdflag = 1; // 接收完成标志位置1 //如果是从设备,此处可以用条件语句判断是否应该应答主机的呼叫(从设备地址与呼叫地址一致),如果是就发送(应答)。下面是直接发送收到的信息 RS485_Usart2_DMA_Send(usart2_data.rbuff,usart2_data.len); //RS485发送数据 usart2_data.rdflag = 0; // 接收完成标志位置0 //下面的语句通常在回调函数内调用,在此处调用也可以 //HAL_UART_Receive_DMA(&huart2,usart2_data.rbuff,MAX);//重新打开DMA接收 } /* USER CODE END USART2_IRQn 0 */ HAL_UART_IRQHandler(&huart2); /* USER CODE BEGIN USART2_IRQn 1 */ /* USER CODE END USART2_IRQn 1 */ } /** * @brief This function handles USART3 global interrupt. */ void USART3_IRQHandler(void) { /* USER CODE BEGIN USART3_IRQn 0 */ // printf("USART3中断触发\n"); // 新增:打印中断触发提示 if (__HAL_UART_GET_FLAG(&huart3, UART_FLAG_IDLE) != RESET) { // printf("USART3检测到空闲中断\n"); // 新增:确认IDLE标志触发 __HAL_UART_CLEAR_IDLEFLAG(&huart3);//��������жϱ�־λ HAL_UART_DMAStop(&huart3);//ֹͣDMA�������� usart3_data.len = MAX - __HAL_DMA_GET_COUNTER(huart3.hdmarx);//����˴ν��յ������ݳ��� usart3_data.rdflag = 1;//���ý�����ɱ�־ // #if debug //�����ã����Խ��յ�������ת����ȥ������һ������֮�������¿���DMA���� if(usart3_data.rdflag == 1) { // printf("4G:%s\n",usart3_data.rbuff); HAL_UART_Transmit(&huart1,usart3_data.rbuff,usart3_data.len,100); memcpy(G4.R_Buff,usart3_data.rbuff,usart3_data.len); G4.R_Cont = usart3_data.len; memset(usart3_data.rbuff, 0, usart3_data.len); usart3_data.rdflag = 0; HAL_UART_Receive_DMA(&huart3, usart3_data.rbuff, MAX); } // #endif } /* USER CODE END USART3_IRQn 0 */ HAL_UART_IRQHandler(&huart3); /* USER CODE BEGIN USART3_IRQn 1 */ /* USER CODE END USART3_IRQn 1 */ } /** * @brief This function handles TIM6 global interrupt. */ void TIM6_IRQHandler(void) { /* USER CODE BEGIN TIM6_IRQn 0 */ //在此写状态机的计时 //1.判断中断是否发生 if((TIM6->SR & (0x01<<0))!=0) { //2.执行中断服务函数内容 PUBLISH_Period[0]++; //3.清除中断标志位 TIM6->SR &= ~(0x01<<0); } /* USER CODE END TIM6_IRQn 0 */ HAL_TIM_IRQHandler(&htim6); /* USER CODE BEGIN TIM6_IRQn 1 */ /* USER CODE END TIM6_IRQn 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ #include "4G.h" struct WH_LTE_7S1 G4; uint8_t Connect_Step; uint8_t Device_Net_State; //单字节发送函数 void SendByte(uint8_t data) { HAL_UART_Transmit(&huart3,&data,1,1000); } //发送字符串 //参数 字符串的首地址 void SendStr(uint8_t *Str) { while(*Str != '\0') {//*Str++ (1)先算*Str (2)再算Str++ SendByte(*Str++); } } //发送数组 //参数1 数组的首地址 //参数2 数组的长度 void SendBuff(uint8_t *Buff , uint16_t Length) { for(uint16_t i=0;i<Length;i++) { SendByte(Buff[i]); //两种发送都可以 // ESP_SendByte(*Buff++); } } //清除接收缓冲区 void R_BUFF_CLEAR(void) { memset(G4.R_Buff,0,sizeof(G4.R_Buff)); G4.R_Cont=0; } //确认设备连接 //uint8_t Lte_Check(void) //{ // if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT\r\nOK",(uint8_t *)"usr.cn#\r\nOK",G4.R_Buff,500,1)) // { // printf("%d\n",G4.R_Cont); // printf("%s",G4.R_Buff); // printf("4G module is functioning properly. \n"); // return 1; // } // return 0; //} //关闭心跳包 //uint8_t Close_Heart(void) //{ // if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+HEARTEN=OFF\r\nOK",(uint8_t *)"usr.cn#\r\nOK",G4.R_Buff,500,1)) // { // return 1; // } // return 0; //} //链接服务器 uint8_t SetSeverInfomation(uint8_t *SeverIP,uint16_t SeverPORT) { char buff[128] = {0}; printf("SeverIP:%s \r\nSeverPort:%d\r\n",SeverIP,SeverPORT); sprintf(buff,"usr.cn#AT+SOCKA=TCP,%s,%d\r\n",SeverIP,SeverPORT); if(SendCMD_CheckRES((uint8_t *)buff,(uint8_t *)"usr.cn#\r\nOK",G4.R_Buff,1000,1)) { return 1; } return 0; } //重启4G模块使配置生效 //uint8_t RestartLte(void) //{ // if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+S\r\nOK",(uint8_t *)"usr.cn#\r\nOK",G4.R_Buff,10000,1)) // { // return 1; // } // return 0; //} void G4_Connect_Net(void) { switch(Connect_Step) { case 0://确认设备连接 printf("1、测试设备\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT\r\nOK",(uint8_t *)"usr.cn#\r\nOK",G4.R_Buff,500,1)==1) Connect_Step++; break; case 1://关闭心跳包 printf("2、关闭心跳\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+HEARTEN=OFF\r\nOK",(uint8_t *)"usr.cn#\r\nOK",G4.R_Buff,500,1)==1) Connect_Step++; break; case 2: printf("3、退出套接字\r\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+SDPEN=OFF\r\n",(uint8_t *)"OK",G4.R_Buff,100,1)==1) Connect_Step++; break; case 3: printf("4、退出注册\r\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+REGEN=OFF\r\n",(uint8_t *)"OK",G4.R_Buff,100,1)==1) Connect_Step++; break; case 4: printf("5、同步NTP服务器\r\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+NTPEN=ON\r\n",(uint8_t *)"OK",G4.R_Buff,10000,1)==1) Connect_Step++; break; case 5: printf("6、设置时间60s\r\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+NTPTM=60\r\n",(uint8_t *)"OK",G4.R_Buff,10000,1)==1) Connect_Step++; break; case 6://链接服务器 printf("7、链接华为云\n"); if(SetSeverInfomation((uint8_t *)HostName,PORT)==1) Connect_Step++; break; case 7://重启4G模块使配置生效 printf("8、重启模块使能配置\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+S\r\nOK",(uint8_t *)"usr.cn#\r\nOK",G4.R_Buff,10000,1) ==1) Connect_Step++; break; case 8: printf("9、查看已链接服务器\n"); if(SendCMD_CheckRES((uint8_t *)"usr.cn#AT+SOCKALK\r\n",(uint8_t *)"Connected",G4.R_Buff,1000,1) == 1) { Connect_Step=0; // Connect_Step++; Device_Net_State=1; //设备网络状态置1 } break; case 9: // HAL_Delay(500); // MQTT_Connect(); // Connect_Step=0; //联网步骤清0 // HAL_Delay(1000); break; } } //检测发送AT指令后,是否正确回复 /* 参数1 要发送的命令 参数2 期望的回复 参数3 接收缓冲区 参数4 超时时间 单位:ms 参数5 是否需要检测回复 1需要检测回复 0不需要检测回复 返回值:1 查找成功 0 查找失败 */ uint8_t SendCMD_CheckRES(uint8_t *cmd,uint8_t *res,uint8_t *buff,uint16_t timeout,uint8_t check_flag) { //1.清除接收缓冲区,让接收到数据从头接受 R_BUFF_CLEAR(); //2.发送指定的AT指令 SendStr(cmd); //3.判断是否需要检测回复 if(check_flag==0) {//不需要检测回复 HAL_Delay(timeout); return 1; } while(strstr((char *)buff,(char *)res)==NULL) {//未查找到期望的回复 HAL_Delay(1); timeout--; if(timeout==0) {//超过等待的时间还未等到,返回查找失败 return 0; } } //查找到期望的回复 return 1; } /* strcmp 两个字符串完全相同 strstr 母串中查找子串 */ #include "ali.h" uint8_t LEDSwitch_State=0; uint8_t Connect_flag = 0; //打包连接报文并发送 //注意:连接报文只发送1次 void MQTT_Connect(void) { MQTTPacket_connectData data = MQTTPacket_connectData_initializer; int len = 0; data.clientID.cstring = ClientID; //客户端ID data.keepAliveInterval = 100; //保持连接时间 超过1.5*60的时间未上报数据,平台显示离线 96页手册图例3.5 data.cleansession = 1; //是否清理会话 图例 3.4的位1 data.username.cstring = Username; //用户名 data.password.cstring = Password; //密码 //参数1 打包之后数据存放的缓冲区 //参数2 该缓冲区的大小,避免数组越界 //参数3 连接报文相关的参数 //返回值 成功 打包之后的有效长度 失败 -1 len = MQTTSerialize_connect(G4.S_Buff, Buff_Length, &data); if(len<=0) { printf("连接报文打包失败\r\n"); } printf("拼接connect连接报文成功 报文长度:%d\r\n",len); if(Connect_flag == 0) { R_BUFF_CLEAR(); //发送之前清除一下接收缓冲区 HAL_UART_Transmit(&huart1,G4.S_Buff,len,1000);//只是为了调试使用,通过串口1查看要发送给串口3的数据 HAL_UART_Transmit(&huart3,G4.S_Buff,len,1000); //通过串口3发送函数,将数据发送给4G模块 Connect_flag = 1; } HAL_Delay(5000); printf("\r\n接收到的数据为%s\r\n",G4.R_Buff); if(G4.R_Buff[0]==0x20&&G4.R_Buff[1]==0x02&&G4.R_Buff[2]==0x00&&G4.R_Buff[3]==0x00) {//20 02 00 00是正确的连接应答 Device_Net_State=2; //设备的网络状态修改 printf("连接报文应答成功\r\n"); } else { printf("连接报文应答失败\r\n"); R_BUFF_CLEAR(); } } //{"id":1735270458995,"params":{"temperature":11,"Humidity":22,"LEDSwitch":0,"TemperatureThreshold":33,"LightLux":44,"Smoke_Value":55},"version":"1.0","method":"thing.event.property.post"} //打包发布报文并发送 void MQTT_Publish(void) { MQTTString topicString = MQTTString_initializer; topicString.cstring = Publish_Topic; int len=0; char payload[300] ={0}; //更改下面的格式一定要注意是否符合JSON格式 //需要改 snprintf(payload,sizeof(payload), "{\"services\":[{\"properties\":{\"temp\":%d},\"service_id\":\"dtu\",\"event_time\":null}]}" ,26); int payloadlen = strlen(payload); //strlen是字符串的长度 sizeof数组的长度 //参数1 打包之后数据存放的缓冲区 //参数2 该缓冲区的大小,避免数组越界 //参数3 DUP QOS==0的话,DUP必须是0 //参数4 QOS /*Qos选择0 0 1 2 2最靠谱*/ //参数5 Retained 填0 1 保留该消息,作为问候消息 0不需要保留该消息 //参数6 报文标识符 Qos==0 无报文标识符 //参数7 主题名 //参数8 有效载荷的数组首地址 //参数9 有效载荷的长度 //返回值 成功 打包之后的有效长度 失败 -1 /sys/a1P0lkJ9Jw0/Device_202/thing/event/property/post len = MQTTSerialize_publish(G4.S_Buff, Buff_Length, 0, 0, 0, 0, topicString, (unsigned char*)payload, payloadlen); if(len<=0) { printf("发布报文打包失败\r\n"); } R_BUFF_CLEAR(); //发送之前清除一下接收缓冲区 HAL_UART_Transmit(&huart1,G4.S_Buff,len,1000); //只是为了调试使用,通过串口1查看要发送给串口3的数据 SendBuff(G4.S_Buff,len); //通过串口3发送函数,将数据发送给4G模块 } //订阅下发主题 void MQTT_Subscribe(void) { int msgid = 1; int req_qos = 0; int len = 0; MQTTString topicString = MQTTString_initializer; topicString.cstring = Subcribe_Topic; //参数1 打包之后数据存放的缓冲区 //参数2 该缓冲区的大小,避免数组越界 //参数3 DUP QOS==0的话,DUP必须是0 //参数4 报文标识符 Qos==0 无报文标识符,参数随便给 //参数5 订阅的主题数量 可以支持1次订阅多个主题 //参数6 待订阅的主题 //参数7 主题的消息质量等级 //返回值 成功 打包之后的有效长度 失败 -1 len = MQTTSerialize_subscribe(G4.S_Buff, Buff_Length, 0, msgid, 1, &topicString, &req_qos); if(len<=0) { printf("订阅报文打包失败\r\n"); } R_BUFF_CLEAR(); //发送之前清除一下接收缓冲区 HAL_UART_Transmit(&huart1,G4.S_Buff,len,1000); //只是为了调试使用,通过串口1查看要发送给串口3的数据 SendBuff(G4.S_Buff,len); //通过串口3发送函数,将数据发送给4G模块 // Delay_ms(1000); HAL_Delay(1000); if(G4.R_Buff[0]==0x90) {//是正确的订阅应答 90 03 00 01 01 Device_Net_State=3; //设备的网络状态修改 printf("订阅报文应答成功\r\n"); } else { printf("订阅报文应答失败\r\n"); } } //发送心跳 void MQTT_Ping(void) { int len = 0; //参数1 打包之后数据存放的缓冲区 //参数2 该缓冲区的大小,避免数组越界 //返回值 成功 打包之后的有效长度 失败 -1 len=MQTTSerialize_pingreq(G4.S_Buff, Buff_Length); if(len<=0) { printf("心跳报文打包失败\r\n"); } R_BUFF_CLEAR(); //发送之前清除一下接收缓冲区 HAL_UART_Transmit(&huart1,G4.S_Buff,len,1000); //只是为了调试使用,通过串口1查看要发送给串口3的数据 SendBuff(G4.S_Buff,len); //通过串口3发送函数,将数据发送给4G模块 } 为何在发送连接报文后,收不到服务器返回的连接报文应答

/* 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" #include "dma.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* 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 ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* 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_DMA_Init(); MX_USART1_UART_Init(); MX_USART2_UART_Init(); /* USER CODE BEGIN 2 */ printf("串口二\n"); HAL_UART_Transmit(&huart2,"123456",3,1000); // Uart1_Config(); Uart2_Config(); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { // HAL_Delay(1500); // HAL_GPIO_TogglePin(LED1_GPIO_Port,LED1_Pin); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ uint16_t MAX = 1024; struct usart usart1_data = {0}; struct usart usart2_data = {0}; /* USER CODE END 0 */ UART_HandleTypeDef huart1; UART_HandleTypeDef huart2; DMA_HandleTypeDef hdma_usart1_rx; DMA_HandleTypeDef hdma_usart2_rx; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } /* USART2 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART2_Init 2 */ /* USER CODE END USART2_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART1 DMA Init */ /* USART1_RX Init */ hdma_usart1_rx.Instance = DMA1_Channel5; hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_rx.Init.Mode = DMA_NORMAL; hdma_usart1_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart1_rx); /* USART1 interrupt Init */ HAL_NVIC_SetPriority(USART1_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } else if(uartHandle->Instance==USART2) { /* USER CODE BEGIN USART2_MspInit 0 */ /* USER CODE END USART2_MspInit 0 */ /* USART2 clock enable */ __HAL_RCC_USART2_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ GPIO_InitStruct.Pin = GPIO_PIN_2; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_3; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART2 DMA Init */ /* USART2_RX Init */ hdma_usart2_rx.Instance = DMA1_Channel6; hdma_usart2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart2_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart2_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart2_rx.Init.Mode = DMA_NORMAL; hdma_usart2_rx.Init.Priority = DMA_PRIORITY_LOW; if (HAL_DMA_Init(&hdma_usart2_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart2_rx); /* USART2 interrupt Init */ HAL_NVIC_SetPriority(USART2_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspInit 1 */ /* USER CODE END USART2_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USART1 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); /* USART1 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } else if(uartHandle->Instance==USART2) { /* USER CODE BEGIN USART2_MspDeInit 0 */ /* USER CODE END USART2_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART2_CLK_DISABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3); /* USART2 DMA DeInit */ HAL_DMA_DeInit(uartHandle->hdmarx); /* USART2 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspDeInit 1 */ /* USER CODE END USART2_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ //重定向printf int fputc(int ch, FILE *f) { uint8_t temp[1] = { (uint8_t)ch }; HAL_UART_Transmit(&huart2, temp, 1, HAL_MAX_DELAY); return ch; } void Uart1_Config(void) { HAL_UART_Receive_DMA(&huart1, usart1_data.buff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);//���������ж� } void Uart2_Config(void) { RS485_2_RX; HAL_UART_Receive_DMA(&huart2, usart2_data.buff, MAX);//����DMA���գ������ݱ�����usart1_data.buff�У�MAXΪ1024 __HAL_UART_ENABLE_IT(&huart2,UART_IT_IDLE);//���������ж� } /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * @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" #include "stm32f1xx_it.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "usart.h" #include <string.h> /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ extern DMA_HandleTypeDef hdma_usart1_rx; extern DMA_HandleTypeDef hdma_usart2_rx; extern UART_HandleTypeDef huart1; extern UART_HandleTypeDef huart2; /* USER CODE BEGIN EV */ /* USER CODE END EV */ /******************************************************************************/ /* Cortex-M3 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles Non maskable interrupt. */ void NMI_Handler(void) { /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ while (1) { } /* USER CODE END NonMaskableInt_IRQn 1 */ } /** * @brief This function handles Hard fault interrupt. */ void HardFault_Handler(void) { /* USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_HardFault_IRQn 0 */ /* USER CODE END W1_HardFault_IRQn 0 */ } } /** * @brief This function handles Memory management fault. */ void MemManage_Handler(void) { /* USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ /* USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** * @brief This function handles Prefetch fault, memory access fault. */ void BusFault_Handler(void) { /* USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_BusFault_IRQn 0 */ /* USER CODE END W1_BusFault_IRQn 0 */ } } /** * @brief This function handles Undefined instruction or illegal state. */ void UsageFault_Handler(void) { /* USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ /* USER CODE END W1_UsageFault_IRQn 0 */ } } /** * @brief This function handles System service call via SWI instruction. */ void SVC_Handler(void) { /* USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */ /* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** * @brief This function handles Debug monitor. */ void DebugMon_Handler(void) { /* USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** * @brief This function handles Pendable request for system service. */ void PendSV_Handler(void) { /* USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */ /* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32F1xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f1xx.s). */ /******************************************************************************/ /** * @brief This function handles DMA1 channel5 global interrupt. */ void DMA1_Channel5_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */ /* USER CODE END DMA1_Channel5_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart1_rx); /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */ /* USER CODE END DMA1_Channel5_IRQn 1 */ } /** * @brief This function handles DMA1 channel6 global interrupt. */ void DMA1_Channel6_IRQHandler(void) { /* USER CODE BEGIN DMA1_Channel6_IRQn 0 */ /* USER CODE END DMA1_Channel6_IRQn 0 */ HAL_DMA_IRQHandler(&hdma_usart2_rx); /* USER CODE BEGIN DMA1_Channel6_IRQn 1 */ /* USER CODE END DMA1_Channel6_IRQn 1 */ } /** * @brief This function handles USART1 global interrupt. */ void USART1_IRQHandler(void) { /* USER CODE BEGIN USART1_IRQn 0 */ //�жϿ��б�־λ�Ƿ���λ if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET) { __HAL_UART_CLEAR_IDLEFLAG(&huart1);//��������жϱ�־λ HAL_UART_DMAStop(&huart1);//ֹͣDMA�������� usart1_data.len = MAX - __HAL_DMA_GET_COUNTER(huart1.hdmarx);//����˴ν��յ������ݳ��� usart1_data.flag = 1;//���ý�����ɱ�־ // #if debug //�����ã����Խ��յ�������ת����ȥ������һ������֮�������¿���DMA���� if(usart1_data.flag == 1) { HAL_UART_Transmit(&huart1,usart1_data.buff,usart1_data.len,100*usart1_data.len); HAL_Delay(10); memset(usart1_data.buff, 0, usart1_data.len); usart1_data.flag = 0; HAL_UART_Receive_DMA(&huart1, usart1_data.buff, MAX); } // #endif } /* USER CODE END USART1_IRQn 0 */ HAL_UART_IRQHandler(&huart1); /* USER CODE BEGIN USART1_IRQn 1 */ /* USER CODE END USART1_IRQn 1 */ } /** * @brief This function handles USART2 global interrupt. */ void USART2_IRQHandler(void) { /* USER CODE BEGIN USART2_IRQn 0 */ //�жϿ��б�־λ�Ƿ���λ if (__HAL_UART_GET_FLAG(&huart2, UART_FLAG_IDLE) != RESET) { __HAL_UART_CLEAR_IDLEFLAG(&huart2);//��������жϱ�־λ HAL_UART_DMAStop(&huart2);//ֹͣDMA�������� usart2_data.len = MAX - __HAL_DMA_GET_COUNTER(huart2.hdmarx);//����˴ν��յ������ݳ��� usart2_data.flag = 1;//���ý�����ɱ�־ printf("usart2_data.flag = %s",&usart2_data.flag); // #if debug //�����ã����Խ��յ�������ת����ȥ������һ������֮�������¿���DMA���� if(usart2_data.flag == 1) { RS485_2_TX; HAL_Delay(1); HAL_UART_Transmit(&huart2,usart2_data.buff,usart2_data.len,100*usart2_data.len); HAL_Delay(1); memset(usart2_data.buff, 0, usart2_data.len); usart2_data.flag = 0; printf("usart2_data.flag = %s",&usart2_data.flag); RS485_2_RX; HAL_Delay(1); HAL_UART_Receive_DMA(&huart2, usart2_data.buff, MAX); } // #endif } /* USER CODE END USART2_IRQn 0 */ HAL_UART_IRQHandler(&huart2); /* USER CODE BEGIN USART2_IRQn 1 */ /* USER CODE END USART2_IRQn 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ 为何串口2不打印,并且通过串口助手给它发送数据它也不进入空闲中断

/********************************************************************************************************* * * File : ws_W25Qx.c * Hardware Environment: * Build Environment : RealView MDK-ARM Version: 4.20 * Version : V1.0 * By : * * (c) Copyright 2005-2011, WaveShare * http://www.waveshare.net * All Rights Reserved * *********************************************************************************************************/ #include "W25QXX.h" /** * @brief Initializes the W25Q128FV interface. * @retval None */ uint8_t BSP_W25Qx_Init(void) { /* Reset W25Qxxx */ BSP_W25Qx_Reset(); return BSP_W25Qx_GetStatus(); } /** * @brief This function reset the W25Qx. * @retval None */ static void BSP_W25Qx_Reset(void) { uint8_t cmd[2] = {RESET_ENABLE_CMD,RESET_MEMORY_CMD}; W25Qx_Enable(); /* Send the reset command */ HAL_SPI_Transmit(&hspi2, cmd, 2, W25Qx_TIMEOUT_VALUE); W25Qx_Disable(); } /** * @brief Reads current status of the W25Q128FV. * @retval W25Q128FV memory status */ static uint8_t BSP_W25Qx_GetStatus(void) { uint8_t cmd[] = {READ_STATUS_REG1_CMD}; uint8_t status; W25Qx_Enable(); /* Send the read status command */ HAL_SPI_Transmit(&hspi2, cmd, 1, W25Qx_TIMEOUT_VALUE); /* Reception of the data */ HAL_SPI_Receive(&hspi2,&status, 1, W25Qx_TIMEOUT_VALUE); W25Qx_Disable(); /* Check the value of the register */ if((status & W25Q128FV_FSR_BUSY) != 0) { return W25Qx_BUSY; } else { return W25Qx_OK; } } /** * @brief This function send a Write Enable and wait it is effective. * @retval None */ uint8_t BSP_W25Qx_WriteEnable(void) { uint8_t cmd[] = {WRITE_ENABLE_CMD}; uint32_t tickstart = HAL_GetTick(); /*Select the FLASH: Chip Select low */ W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi2, cmd, 1, W25Qx_TIMEOUT_VALUE); /*Deselect the FLASH: Chip Select high */ W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() == W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Qx_TIMEOUT_VALUE) { return W25Qx_TIMEOUT; } } return W25Qx_OK; } /** * @brief Read Manufacture/Device ID. * @param return value address * @retval None */ void BSP_W25Qx_Read_ID(uint8_t *ID) { uint8_t cmd[4] = {READ_ID_CMD,0x00,0x00,0x00}; W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi2, cmd, 4, W25Qx_TIMEOUT_VALUE); /* Reception of the data */ HAL_SPI_Receive(&hspi2,ID, 2, W25Qx_TIMEOUT_VALUE); W25Qx_Disable(); } /** * @brief Reads an amount of data from the QSPI memory. * @param pData: Pointer to data to be read * @param ReadAddr: Read start address * @param Size: Size of data to read * @retval QSPI memory status */ uint8_t BSP_W25Qx_Read(uint8_t* pData, uint32_t ReadAddr, uint32_t Size) { uint8_t cmd[4]; /* Configure the command */ cmd[0] = READ_CMD; cmd[1] = (uint8_t)(ReadAddr >> 16); cmd[2] = (uint8_t)(ReadAddr >> 8); cmd[3] = (uint8_t)(ReadAddr); W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi2, cmd, 4, W25Qx_TIMEOUT_VALUE); /* Reception of the data */ if (HAL_SPI_Receive(&hspi2, pData,Size,W25Qx_TIMEOUT_VALUE) != HAL_OK) { return W25Qx_ERROR; } W25Qx_Disable(); return W25Qx_OK; } /** * @brief Writes an amount of data to the QSPI memory. * @param pData: Pointer to data to be written * @param WriteAddr: Write start address * @param Size: Size of data to write,No more than 256byte. * @retval QSPI memory status */ uint8_t BSP_W25Qx_Write(uint8_t* pData, uint32_t WriteAddr, uint32_t Size) { uint8_t cmd[4]; uint32_t end_addr, current_size, current_addr; uint32_t tickstart = HAL_GetTick(); /* Calculation of the size between the write address and the end of the page */ current_addr = 0; while (current_addr <= WriteAddr) { current_addr += W25Q128FV_PAGE_SIZE; } current_size = current_addr - WriteAddr; /* Check if the size of the data is less than the remaining place in the page */ if (current_size > Size) { current_size = Size; } /* Initialize the adress variables */ current_addr = WriteAddr; end_addr = WriteAddr + Size; /* Perform the write page by page */ do { /* Configure the command */ cmd[0] = PAGE_PROG_CMD; cmd[1] = (uint8_t)(current_addr >> 16); cmd[2] = (uint8_t)(current_addr >> 8); cmd[3] = (uint8_t)(current_addr); /* Enable write operations */ BSP_W25Qx_WriteEnable(); W25Qx_Enable(); /* Send the command */ if (HAL_SPI_Transmit(&hspi2,cmd, 4, W25Qx_TIMEOUT_VALUE) != HAL_OK) { return W25Qx_ERROR; } /* Transmission of the data */ if (HAL_SPI_Transmit(&hspi2, pData,current_size, W25Qx_TIMEOUT_VALUE) != HAL_OK) { return W25Qx_ERROR; } W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() == W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Qx_TIMEOUT_VALUE) { return W25Qx_TIMEOUT; } } /* Update the address and size variables for next page programming */ current_addr += current_size; pData += current_size; current_size = ((current_addr + W25Q128FV_PAGE_SIZE) > end_addr) ? (end_addr - current_addr) : W25Q128FV_PAGE_SIZE; } while (current_addr < end_addr); return W25Qx_OK; } /** * @brief Erases the specified block of the QSPI memory. * @param BlockAddress: Block address to erase * @retval QSPI memory status */ uint8_t BSP_W25Qx_Erase_Block(uint32_t Address) { uint8_t cmd[4]; uint32_t tickstart = HAL_GetTick(); cmd[0] = SECTOR_ERASE_CMD; cmd[1] = (uint8_t)(Address >> 16); cmd[2] = (uint8_t)(Address >> 8); cmd[3] = (uint8_t)(Address); /* Enable write operations */ BSP_W25Qx_WriteEnable(); /*Select the FLASH: Chip Select low */ W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi2, cmd, 4, W25Qx_TIMEOUT_VALUE); /*Deselect the FLASH: Chip Select high */ W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() == W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Q128FV_SECTOR_ERASE_MAX_TIME) { return W25Qx_TIMEOUT; } } return W25Qx_OK; } /** * @brief Erases the entire QSPI memory.This function will take a very long time. * @retval QSPI memory status */ uint8_t BSP_W25Qx_Erase_Chip(void) { uint8_t cmd[4]; uint32_t tickstart = HAL_GetTick(); cmd[0] = SECTOR_ERASE_CMD; /* Enable write operations */ BSP_W25Qx_WriteEnable(); /*Select the FLASH: Chip Select low */ W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi2, cmd, 1, W25Qx_TIMEOUT_VALUE); /*Deselect the FLASH: Chip Select high */ W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() != W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Q128FV_BULK_ERASE_MAX_TIME) { return W25Qx_TIMEOUT; } } return W25Qx_OK; } /********************************************************************************************************* * * File : W25Qx.h * Hardware Environment: * Build Environment : RealView MDK-ARM Version: 5.15 * Version : V1.0 * By : * * (c) Copyright 2005-2015, WaveShare * http://www.waveshare.net * All Rights Reserved * *********************************************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __W25QXX_H #define __W25QXX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx.h" #include "spi.h" /** @addtogroup BSP * @{ */ /** @addtogroup Components * @{ */ /** @addtogroup W25Q128FV * @{ */ /** @defgroup W25Q128FV_Exported_Types * @{ */ /** * @} */ /** @defgroup W25Q128FV_Exported_Constants * @{ */ /** * @brief W25Q128FV Configuration */ #define W25Q128FV_FLASH_SIZE 0x1000000 /* 128 MBits => 16MBytes */ #define W25Q128FV_SECTOR_SIZE 0x10000 /* 256 sectors of 64KBytes */ #define W25Q128FV_SUBSECTOR_SIZE 0x1000 /* 4096 subsectors of 4kBytes */ #define W25Q128FV_PAGE_SIZE 0x100 /* 65536 pages of 256 bytes */ #define W25Q128FV_DUMMY_CYCLES_READ 4 #define W25Q128FV_DUMMY_CYCLES_READ_QUAD 10 #define W25Q128FV_BULK_ERASE_MAX_TIME 250000 #define W25Q128FV_SECTOR_ERASE_MAX_TIME 3000 #define W25Q128FV_SUBSECTOR_ERASE_MAX_TIME 800 #define W25Qx_TIMEOUT_VALUE 1000 /** * @brief W25Q128FV Commands */ /* Reset Operations */ #define RESET_ENABLE_CMD 0x66 #define RESET_MEMORY_CMD 0x99 #define ENTER_QPI_MODE_CMD 0x38 #define EXIT_QPI_MODE_CMD 0xFF /* Identification Operations */ #define READ_ID_CMD 0x90 #define DUAL_READ_ID_CMD 0x92 #define QUAD_READ_ID_CMD 0x94 #define READ_JEDEC_ID_CMD 0x9F /* Read Operations */ #define READ_CMD 0x03 #define FAST_READ_CMD 0x0B #define DUAL_OUT_FAST_READ_CMD 0x3B #define DUAL_INOUT_FAST_READ_CMD 0xBB #define QUAD_OUT_FAST_READ_CMD 0x6B #define QUAD_INOUT_FAST_READ_CMD 0xEB /* Write Operations */ #define WRITE_ENABLE_CMD 0x06 #define WRITE_DISABLE_CMD 0x04 /* Register Operations */ #define READ_STATUS_REG1_CMD 0x05 #define READ_STATUS_REG2_CMD 0x35 #define READ_STATUS_REG3_CMD 0x15 #define WRITE_STATUS_REG1_CMD 0x01 #define WRITE_STATUS_REG2_CMD 0x31 #define WRITE_STATUS_REG3_CMD 0x11 /* Program Operations */ #define PAGE_PROG_CMD 0x02 #define QUAD_INPUT_PAGE_PROG_CMD 0x32 /* Erase Operations */ #define SECTOR_ERASE_CMD 0x20 #define CHIP_ERASE_CMD 0xC7 #define PROG_ERASE_RESUME_CMD 0x7A #define PROG_ERASE_SUSPEND_CMD 0x75 /* Flag Status Register */ #define W25Q128FV_FSR_BUSY ((uint8_t)0x01) /*!< busy */ #define W25Q128FV_FSR_WREN ((uint8_t)0x02) /*!< write enable */ #define W25Q128FV_FSR_QE ((uint8_t)0x02) /*!< quad enable */ #define W25Qx_Enable() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_RESET) #define W25Qx_Disable() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_SET) #define W25Qx_OK ((uint8_t)0x00) #define W25Qx_ERROR ((uint8_t)0x01) #define W25Qx_BUSY ((uint8_t)0x02) #define W25Qx_TIMEOUT ((uint8_t)0x03) uint8_t BSP_W25Qx_Init(void); static void BSP_W25Qx_Reset(void); static uint8_t BSP_W25Qx_GetStatus(void); uint8_t BSP_W25Qx_WriteEnable(void); void BSP_W25Qx_Read_ID(uint8_t *ID); uint8_t BSP_W25Qx_Read(uint8_t* pData, uint32_t ReadAddr, uint32_t Size); uint8_t BSP_W25Qx_Write(uint8_t* pData, uint32_t WriteAddr, uint32_t Size); uint8_t BSP_W25Qx_Erase_Block(uint32_t Address); uint8_t BSP_W25Qx_Erase_Chip(void); /** * @} */ /** @defgroup W25Q128FV_Exported_Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __W25Qx_H */ /* 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" #include "spi.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "stm32f1xx_hal.h" #include <stdio.h> #include <string.h> #include "W25QXX.h" uint8_t wData[0x100]; uint8_t rData[0x100]; uint32_t i; uint8_t ID[2]; extern UART_HandleTypeDef huart1; //声明串口 /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /** * 函数功能: 重定向c库函数printf到DEBUG_USARTx * 输入参数: 无 * 返 回 值: 无 * 说 明:无 */ int fputc(int ch, FILE *f) { HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff); return ch; } /** * 函数功能: 重定向c库函数getchar,scanf到DEBUG_USARTx * 输入参数: 无 * 返 回 值: 无 * 说 明:无 */ int fgetc(FILE *f) { uint8_t ch = 0; HAL_UART_Receive(&huart1, &ch, 1, 0xffff); return ch; } /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* 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_SPI2_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ printf("\r\n SPI-W25Qxxx Example \r\n\r\n"); /*##-1- Read the device ID ########################*/ BSP_W25Qx_Init(); BSP_W25Qx_Read_ID(ID); printf(" W25Qxxx ID is : 0x%02X 0x%02X \r\n\r\n",ID[0],ID[1]); /*##-2- Erase Block ##################################*/ if(BSP_W25Qx_Erase_Block(0) == W25Qx_OK) printf(" SPI Erase Block ok\r\n"); else Error_Handler(); /*##-3- Written to the flash ########################*/ /* fill buffer */ for(i =0;i<0x100;i ++) { wData[i] = i; rData[i] = 0; } if(BSP_W25Qx_Write(wData,0x00,0x100)== W25Qx_OK) printf(" SPI Write ok\r\n"); else Error_Handler(); /*##-4- Read the flash ########################*/ if(BSP_W25Qx_Read(rData,0x00,0x100)== W25Qx_OK) printf(" SPI Read ok\r\n\r\n"); else Error_Handler(); printf("SPI Read Data : \r\n"); for(i =0;i<0x100;i++) printf("0x%02X ",rData[i]); printf("\r\n\r\n"); /*##-5- check date ########################*/ if(memcmp(wData,rData,0x100) == 0 ) printf(" W25Q128FV SPI Test OK\r\n"); else printf(" W25Q128FV SPI Test False\r\n"); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file gpio.c * @brief This file provides code for the configuration * of all used GPIO pins. ****************************************************************************** * @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 "gpio.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /*----------------------------------------------------------------------------*/ /* Configure GPIO */ /*----------------------------------------------------------------------------*/ /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(SPI2_CS_GPIO_Port, SPI2_CS_Pin, GPIO_PIN_RESET); /*Configure GPIO pin : PtPin */ GPIO_InitStruct.Pin = SPI2_CS_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(SPI2_CS_GPIO_Port, &GPIO_InitStruct); } /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file spi.c * @brief This file provides code for the configuration * of the SPI instances. ****************************************************************************** * @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 "spi.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ SPI_HandleTypeDef hspi2; /* SPI2 init function */ void MX_SPI2_Init(void) { /* USER CODE BEGIN SPI2_Init 0 */ /* USER CODE END SPI2_Init 0 */ /* USER CODE BEGIN SPI2_Init 1 */ /* USER CODE END SPI2_Init 1 */ hspi2.Instance = SPI2; hspi2.Init.Mode = SPI_MODE_MASTER; hspi2.Init.Direction = SPI_DIRECTION_2LINES; hspi2.Init.DataSize = SPI_DATASIZE_8BIT; hspi2.Init.CLKPolarity = SPI_POLARITY_LOW; hspi2.Init.CLKPhase = SPI_PHASE_1EDGE; hspi2.Init.NSS = SPI_NSS_SOFT; hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi2.Init.TIMode = SPI_TIMODE_DISABLE; hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi2.Init.CRCPolynomial = 10; if (HAL_SPI_Init(&hspi2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN SPI2_Init 2 */ /* USER CODE END SPI2_Init 2 */ } void HAL_SPI_MspInit(SPI_HandleTypeDef* spiHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(spiHandle->Instance==SPI2) { /* USER CODE BEGIN SPI2_MspInit 0 */ /* USER CODE END SPI2_MspInit 0 */ /* SPI2 clock enable */ __HAL_RCC_SPI2_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /**SPI2 GPIO Configuration PB13 ------> SPI2_SCK PB14 ------> SPI2_MISO PB15 ------> SPI2_MOSI */ GPIO_InitStruct.Pin = GPIO_PIN_13|GPIO_PIN_15; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_14; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* USER CODE BEGIN SPI2_MspInit 1 */ /* USER CODE END SPI2_MspInit 1 */ } } void HAL_SPI_MspDeInit(SPI_HandleTypeDef* spiHandle) { if(spiHandle->Instance==SPI2) { /* USER CODE BEGIN SPI2_MspDeInit 0 */ /* USER CODE END SPI2_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_SPI2_CLK_DISABLE(); /**SPI2 GPIO Configuration PB13 ------> SPI2_SCK PB14 ------> SPI2_MISO PB15 ------> SPI2_MOSI */ HAL_GPIO_DeInit(GPIOB, GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15); /* USER CODE BEGIN SPI2_MspDeInit 1 */ /* USER CODE END SPI2_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 *//* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ UART_HandleTypeDef huart1; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ UART_HandleTypeDef huart1; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ UART_HandleTypeDef huart1; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * @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" #include "stm32f1xx_it.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ /* USER CODE BEGIN EV */ /* USER CODE END EV */ /******************************************************************************/ /* Cortex-M3 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles Non maskable interrupt. */ void NMI_Handler(void) { /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ while (1) { } /* USER CODE END NonMaskableInt_IRQn 1 */ } /** * @brief This function handles Hard fault interrupt. */ void HardFault_Handler(void) { /* USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_HardFault_IRQn 0 */ /* USER CODE END W1_HardFault_IRQn 0 */ } } /** * @brief This function handles Memory management fault. */ void MemManage_Handler(void) { /* USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ /* USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** * @brief This function handles Prefetch fault, memory access fault. */ void BusFault_Handler(void) { /* USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_BusFault_IRQn 0 */ /* USER CODE END W1_BusFault_IRQn 0 */ } } /** * @brief This function handles Undefined instruction or illegal state. */ void UsageFault_Handler(void) { /* USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ /* USER CODE END W1_UsageFault_IRQn 0 */ } } /** * @brief This function handles System service call via SWI instruction. */ void SVC_Handler(void) { /* USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */ /* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** * @brief This function handles Debug monitor. */ void DebugMon_Handler(void) { /* USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** * @brief This function handles Pendable request for system service. */ void PendSV_Handler(void) { /* USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */ /* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32F1xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f1xx.s). */ /******************************************************************************/ /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_hal_msp.c * @brief This file provides code for the MSP Initialization * and de-Initialization codes. ****************************************************************************** * @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" /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN Define */ /* USER CODE END Define */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN Macro */ /* USER CODE END Macro */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* External functions --------------------------------------------------------*/ /* USER CODE BEGIN ExternalFunctions */ /* USER CODE END ExternalFunctions */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * Initializes the Global MSP. */ void HAL_MspInit(void) { /* USER CODE BEGIN MspInit 0 */ /* USER CODE END MspInit 0 */ __HAL_RCC_AFIO_CLK_ENABLE(); __HAL_RCC_PWR_CLK_ENABLE(); /* System interrupt init*/ /** NOJTAG: JTAG-DP Disabled and SW-DP Enabled */ __HAL_AFIO_REMAP_SWJ_NOJTAG(); /* USER CODE BEGIN MspInit 1 */ /* USER CODE END MspInit 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */

/********************************************************************************************************* * * File : W25Qx.h * Hardware Environment: * Build Environment : RealView MDK-ARM Version: 5.15 * Version : V1.0 * By : * * (c) Copyright 2005-2015, WaveShare * http://www.waveshare.net * All Rights Reserved * *********************************************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __W25QXX_H #define __W25QXX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx.h" #include "spi.h" /** @addtogroup BSP * @{ */ /** @addtogroup Components * @{ */ /** @addtogroup W25Q128FV * @{ */ /** @defgroup W25Q128FV_Exported_Types * @{ */ /** * @} */ /** @defgroup W25Q128FV_Exported_Constants * @{ */ /** * @brief W25Q128FV Configuration */ #define W25Q128FV_FLASH_SIZE 0x1000000 /* 128 MBits => 16MBytes */ #define W25Q128FV_SECTOR_SIZE 0x10000 /* 256 sectors of 64KBytes */ #define W25Q128FV_SUBSECTOR_SIZE 0x1000 /* 4096 subsectors of 4kBytes */ #define W25Q128FV_PAGE_SIZE 0x100 /* 65536 pages of 256 bytes */ #define W25Q128FV_DUMMY_CYCLES_READ 4 #define W25Q128FV_DUMMY_CYCLES_READ_QUAD 10 #define W25Q128FV_BULK_ERASE_MAX_TIME 250000 #define W25Q128FV_SECTOR_ERASE_MAX_TIME 3000 #define W25Q128FV_SUBSECTOR_ERASE_MAX_TIME 800 #define W25Qx_TIMEOUT_VALUE 1000 /** * @brief W25Q128FV Commands */ /* Reset Operations */ #define RESET_ENABLE_CMD 0x66 #define RESET_MEMORY_CMD 0x99 #define ENTER_QPI_MODE_CMD 0x38 #define EXIT_QPI_MODE_CMD 0xFF /* Identification Operations */ #define READ_ID_CMD 0x90 #define DUAL_READ_ID_CMD 0x92 #define QUAD_READ_ID_CMD 0x94 #define READ_JEDEC_ID_CMD 0x9F /* Read Operations */ #define READ_CMD 0x03 #define FAST_READ_CMD 0x0B #define DUAL_OUT_FAST_READ_CMD 0x3B #define DUAL_INOUT_FAST_READ_CMD 0xBB #define QUAD_OUT_FAST_READ_CMD 0x6B #define QUAD_INOUT_FAST_READ_CMD 0xEB /* Write Operations */ #define WRITE_ENABLE_CMD 0x06 #define WRITE_DISABLE_CMD 0x04 /* Register Operations */ #define READ_STATUS_REG1_CMD 0x05 #define READ_STATUS_REG2_CMD 0x35 #define READ_STATUS_REG3_CMD 0x15 #define WRITE_STATUS_REG1_CMD 0x01 #define WRITE_STATUS_REG2_CMD 0x31 #define WRITE_STATUS_REG3_CMD 0x11 /* Program Operations */ #define PAGE_PROG_CMD 0x02 #define QUAD_INPUT_PAGE_PROG_CMD 0x32 /* Erase Operations */ #define SECTOR_ERASE_CMD 0x20 #define CHIP_ERASE_CMD 0xC7 #define PROG_ERASE_RESUME_CMD 0x7A #define PROG_ERASE_SUSPEND_CMD 0x75 /* Flag Status Register */ #define W25Q128FV_FSR_BUSY ((uint8_t)0x01) /*!< busy */ #define W25Q128FV_FSR_WREN ((uint8_t)0x02) /*!< write enable */ #define W25Q128FV_FSR_QE ((uint8_t)0x02) /*!< quad enable */ #define W25Qx_Enable() HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_RESET) #define W25Qx_Disable() HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_SET) #define W25Qx_OK ((uint8_t)0x00) #define W25Qx_ERROR ((uint8_t)0x01) #define W25Qx_BUSY ((uint8_t)0x02) #define W25Qx_TIMEOUT ((uint8_t)0x03) uint8_t BSP_W25Qx_Init(void); static void BSP_W25Qx_Reset(void); static uint8_t BSP_W25Qx_GetStatus(void); uint8_t BSP_W25Qx_WriteEnable(void); void BSP_W25Qx_Read_ID(uint8_t *ID); uint8_t BSP_W25Qx_Read(uint8_t* pData, uint32_t ReadAddr, uint32_t Size); uint8_t BSP_W25Qx_Write(uint8_t* pData, uint32_t WriteAddr, uint32_t Size); uint8_t BSP_W25Qx_Erase_Block(uint32_t Address); uint8_t BSP_W25Qx_Erase_Chip(void); /** * @} */ /** @defgroup W25Q128FV_Exported_Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __W25Qx_H */ /********************************************************************************************************* * * File : ws_W25Qx.c * Hardware Environment: * Build Environment : RealView MDK-ARM Version: 4.20 * Version : V1.0 * By : * * (c) Copyright 2005-2011, WaveShare * http://www.waveshare.net * All Rights Reserved * *********************************************************************************************************/ #include "W25QXX.h" /** * @brief Initializes the W25Q128FV interface. * @retval None */ uint8_t BSP_W25Qx_Init(void) { /* Reset W25Qxxx */ BSP_W25Qx_Reset(); return BSP_W25Qx_GetStatus(); } /** * @brief This function reset the W25Qx. * @retval None */ static void BSP_W25Qx_Reset(void) { uint8_t cmd[2] = {RESET_ENABLE_CMD,RESET_MEMORY_CMD}; W25Qx_Enable(); /* Send the reset command */ HAL_SPI_Transmit(&hspi1, cmd, 2, W25Qx_TIMEOUT_VALUE); W25Qx_Disable(); } /** * @brief Reads current status of the W25Q128FV. * @retval W25Q128FV memory status */ static uint8_t BSP_W25Qx_GetStatus(void) { uint8_t cmd[] = {READ_STATUS_REG1_CMD}; uint8_t status; W25Qx_Enable(); /* Send the read status command */ HAL_SPI_Transmit(&hspi1, cmd, 1, W25Qx_TIMEOUT_VALUE); /* Reception of the data */ HAL_SPI_Receive(&hspi1,&status, 1, W25Qx_TIMEOUT_VALUE); W25Qx_Disable(); /* Check the value of the register */ if((status & W25Q128FV_FSR_BUSY) != 0) { return W25Qx_BUSY; } else { return W25Qx_OK; } } /** * @brief This function send a Write Enable and wait it is effective. * @retval None */ uint8_t BSP_W25Qx_WriteEnable(void) { uint8_t cmd[] = {WRITE_ENABLE_CMD}; uint32_t tickstart = HAL_GetTick(); /*Select the FLASH: Chip Select low */ W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi1, cmd, 1, W25Qx_TIMEOUT_VALUE); /*Deselect the FLASH: Chip Select high */ W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() == W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Qx_TIMEOUT_VALUE) { return W25Qx_TIMEOUT; } } return W25Qx_OK; } /** * @brief Read Manufacture/Device ID. * @param return value address * @retval None */ void BSP_W25Qx_Read_ID(uint8_t *ID) { uint8_t cmd[4] = {READ_ID_CMD,0x00,0x00,0x00}; W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi1, cmd, 4, W25Qx_TIMEOUT_VALUE); /* Reception of the data */ HAL_SPI_Receive(&hspi1,ID, 2, W25Qx_TIMEOUT_VALUE); W25Qx_Disable(); } /** * @brief Reads an amount of data from the QSPI memory. * @param pData: Pointer to data to be read * @param ReadAddr: Read start address * @param Size: Size of data to read * @retval QSPI memory status */ uint8_t BSP_W25Qx_Read(uint8_t* pData, uint32_t ReadAddr, uint32_t Size) { uint8_t cmd[4]; /* Configure the command */ cmd[0] = READ_CMD; cmd[1] = (uint8_t)(ReadAddr >> 16); cmd[2] = (uint8_t)(ReadAddr >> 8); cmd[3] = (uint8_t)(ReadAddr); W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi1, cmd, 4, W25Qx_TIMEOUT_VALUE); /* Reception of the data */ if (HAL_SPI_Receive(&hspi1, pData,Size,W25Qx_TIMEOUT_VALUE) != HAL_OK) { return W25Qx_ERROR; } W25Qx_Disable(); return W25Qx_OK; } /** * @brief Writes an amount of data to the QSPI memory. * @param pData: Pointer to data to be written * @param WriteAddr: Write start address * @param Size: Size of data to write,No more than 256byte. * @retval QSPI memory status */ uint8_t BSP_W25Qx_Write(uint8_t* pData, uint32_t WriteAddr, uint32_t Size) { uint8_t cmd[4]; uint32_t end_addr, current_size, current_addr; uint32_t tickstart = HAL_GetTick(); /* Calculation of the size between the write address and the end of the page */ current_addr = 0; while (current_addr <= WriteAddr) { current_addr += W25Q128FV_PAGE_SIZE; } current_size = current_addr - WriteAddr; /* Check if the size of the data is less than the remaining place in the page */ if (current_size > Size) { current_size = Size; } /* Initialize the adress variables */ current_addr = WriteAddr; end_addr = WriteAddr + Size; /* Perform the write page by page */ do { /* Configure the command */ cmd[0] = PAGE_PROG_CMD; cmd[1] = (uint8_t)(current_addr >> 16); cmd[2] = (uint8_t)(current_addr >> 8); cmd[3] = (uint8_t)(current_addr); /* Enable write operations */ BSP_W25Qx_WriteEnable(); W25Qx_Enable(); /* Send the command */ if (HAL_SPI_Transmit(&hspi1,cmd, 4, W25Qx_TIMEOUT_VALUE) != HAL_OK) { return W25Qx_ERROR; } /* Transmission of the data */ if (HAL_SPI_Transmit(&hspi1, pData,current_size, W25Qx_TIMEOUT_VALUE) != HAL_OK) { return W25Qx_ERROR; } W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() == W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Qx_TIMEOUT_VALUE) { return W25Qx_TIMEOUT; } } /* Update the address and size variables for next page programming */ current_addr += current_size; pData += current_size; current_size = ((current_addr + W25Q128FV_PAGE_SIZE) > end_addr) ? (end_addr - current_addr) : W25Q128FV_PAGE_SIZE; } while (current_addr < end_addr); return W25Qx_OK; } /** * @brief Erases the specified block of the QSPI memory. * @param BlockAddress: Block address to erase * @retval QSPI memory status */ uint8_t BSP_W25Qx_Erase_Block(uint32_t Address) { uint8_t cmd[4]; uint32_t tickstart = HAL_GetTick(); cmd[0] = SECTOR_ERASE_CMD; cmd[1] = (uint8_t)(Address >> 16); cmd[2] = (uint8_t)(Address >> 8); cmd[3] = (uint8_t)(Address); /* Enable write operations */ BSP_W25Qx_WriteEnable(); /*Select the FLASH: Chip Select low */ W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi1, cmd, 4, W25Qx_TIMEOUT_VALUE); /*Deselect the FLASH: Chip Select high */ W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() == W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Q128FV_SECTOR_ERASE_MAX_TIME) { return W25Qx_TIMEOUT; } } return W25Qx_OK; } /** * @brief Erases the entire QSPI memory.This function will take a very long time. * @retval QSPI memory status */ uint8_t BSP_W25Qx_Erase_Chip(void) { uint8_t cmd[4]; uint32_t tickstart = HAL_GetTick(); cmd[0] = SECTOR_ERASE_CMD; /* Enable write operations */ BSP_W25Qx_WriteEnable(); /*Select the FLASH: Chip Select low */ W25Qx_Enable(); /* Send the read ID command */ HAL_SPI_Transmit(&hspi1, cmd, 1, W25Qx_TIMEOUT_VALUE); /*Deselect the FLASH: Chip Select high */ W25Qx_Disable(); /* Wait the end of Flash writing */ while(BSP_W25Qx_GetStatus() != W25Qx_BUSY); { /* Check for the Timeout */ if((HAL_GetTick() - tickstart) > W25Q128FV_BULK_ERASE_MAX_TIME) { return W25Qx_TIMEOUT; } } return W25Qx_OK; } /* 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" #include "spi.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "stm32f1xx_hal.h" #include <stdio.h> #include <string.h> #include "W25QXX.h" uint8_t wData[0x100]; uint8_t rData[0x100]; uint32_t i; uint8_t ID[2]; extern UART_HandleTypeDef huart1; //声明串口 /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /** * 函数功能: 重定向c库函数printf到DEBUG_USARTx * 输入参数: 无 * 返 回 值: 无 * 说 明:无 */ int fputc(int ch, FILE *f) { HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff); return ch; } /** * 函数功能: 重定向c库函数getchar,scanf到DEBUG_USARTx * 输入参数: 无 * 返 回 值: 无 * 说 明:无 */ int fgetc(FILE *f) { uint8_t ch = 0; HAL_UART_Receive(&huart1, &ch, 1, 0xffff); return ch; } /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* 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_SPI1_Init(); /* USER CODE BEGIN 2 */ printf("\r\n SPI-W25Qxxx Example \r\n\r\n"); /*##-1- Read the device ID ########################*/ BSP_W25Qx_Init(); BSP_W25Qx_Read_ID(ID); printf(" W25Qxxx ID is : 0x%02X 0x%02X \r\n\r\n",ID[0],ID[1]); /*##-2- Erase Block ##################################*/ if(BSP_W25Qx_Erase_Block(0) == W25Qx_OK) printf(" SPI Erase Block ok\r\n"); else Error_Handler(); /*##-3- Written to the flash ########################*/ /* fill buffer */ for(i =0;i<0x100;i ++) { wData[i] = i; rData[i] = 0; } if(BSP_W25Qx_Write(wData,0x00,0x100)== W25Qx_OK) printf(" SPI Write ok\r\n"); else Error_Handler(); /*##-4- Read the flash ########################*/ if(BSP_W25Qx_Read(rData,0x00,0x100)== W25Qx_OK) printf(" SPI Read ok\r\n\r\n"); else Error_Handler(); printf("SPI Read Data : \r\n"); for(i =0;i<0x100;i++) printf("0x%02X ",rData[i]); printf("\r\n\r\n"); /*##-5- check date ########################*/ if(memcmp(wData,rData,0x100) == 0 ) printf(" W25Q128FV SPI Test OK\r\n"); else printf(" W25Q128FV SPI Test False\r\n"); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file gpio.c * @brief This file provides code for the configuration * of all used GPIO pins. ****************************************************************************** * @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 "gpio.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /*----------------------------------------------------------------------------*/ /* Configure GPIO */ /*----------------------------------------------------------------------------*/ /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_RESET); /*Configure GPIO pin : PtPin */ GPIO_InitStruct.Pin = SPI1_CS_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(SPI1_CS_GPIO_Port, &GPIO_InitStruct); } /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file spi.c * @brief This file provides code for the configuration * of the SPI instances. ****************************************************************************** * @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 "spi.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ SPI_HandleTypeDef hspi1; /* SPI1 init function */ void MX_SPI1_Init(void) { /* USER CODE BEGIN SPI1_Init 0 */ /* USER CODE END SPI1_Init 0 */ /* USER CODE BEGIN SPI1_Init 1 */ /* USER CODE END SPI1_Init 1 */ hspi1.Instance = SPI1; hspi1.Init.Mode = SPI_MODE_MASTER; hspi1.Init.Direction = SPI_DIRECTION_2LINES; hspi1.Init.DataSize = SPI_DATASIZE_8BIT; hspi1.Init.CLKPolarity = SPI_POLARITY_LOW; hspi1.Init.CLKPhase = SPI_PHASE_1EDGE; hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.CRCPolynomial = 10; if (HAL_SPI_Init(&hspi1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN SPI1_Init 2 */ /* USER CODE END SPI1_Init 2 */ } void HAL_SPI_MspInit(SPI_HandleTypeDef* spiHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(spiHandle->Instance==SPI1) { /* USER CODE BEGIN SPI1_MspInit 0 */ /* USER CODE END SPI1_MspInit 0 */ /* SPI1 clock enable */ __HAL_RCC_SPI1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**SPI1 GPIO Configuration PA5 ------> SPI1_SCK PA6 ------> SPI1_MISO PA7 ------> SPI1_MOSI */ GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_7; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_6; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN SPI1_MspInit 1 */ /* USER CODE END SPI1_MspInit 1 */ } } void HAL_SPI_MspDeInit(SPI_HandleTypeDef* spiHandle) { if(spiHandle->Instance==SPI1) { /* USER CODE BEGIN SPI1_MspDeInit 0 */ /* USER CODE END SPI1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_SPI1_CLK_DISABLE(); /**SPI1 GPIO Configuration PA5 ------> SPI1_SCK PA6 ------> SPI1_MISO PA7 ------> SPI1_MOSI */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7); /* USER CODE BEGIN SPI1_MspDeInit 1 */ /* USER CODE END SPI1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @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 "usart.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ UART_HandleTypeDef huart1; /* USART1 init function */ 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 = 115200; 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; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * @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" #include "stm32f1xx_it.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ /* USER CODE BEGIN EV */ /* USER CODE END EV */ /******************************************************************************/ /* Cortex-M3 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles Non maskable interrupt. */ void NMI_Handler(void) { /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ while (1) { } /* USER CODE END NonMaskableInt_IRQn 1 */ } /** * @brief This function handles Hard fault interrupt. */ void HardFault_Handler(void) { /* USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_HardFault_IRQn 0 */ /* USER CODE END W1_HardFault_IRQn 0 */ } } /** * @brief This function handles Memory management fault. */ void MemManage_Handler(void) { /* USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ /* USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** * @brief This function handles Prefetch fault, memory access fault. */ void BusFault_Handler(void) { /* USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_BusFault_IRQn 0 */ /* USER CODE END W1_BusFault_IRQn 0 */ } } /** * @brief This function handles Undefined instruction or illegal state. */ void UsageFault_Handler(void) { /* USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ /* USER CODE END W1_UsageFault_IRQn 0 */ } } /** * @brief This function handles System service call via SWI instruction. */ void SVC_Handler(void) { /* USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */ /* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** * @brief This function handles Debug monitor. */ void DebugMon_Handler(void) { /* USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** * @brief This function handles Pendable request for system service. */ void PendSV_Handler(void) { /* USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */ /* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32F1xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f1xx.s). */ /******************************************************************************/ /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_hal_msp.c * @brief This file provides code for the MSP Initialization * and de-Initialization codes. ****************************************************************************** * @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" /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN Define */ /* USER CODE END Define */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN Macro */ /* USER CODE END Macro */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* External functions --------------------------------------------------------*/ /* USER CODE BEGIN ExternalFunctions */ /* USER CODE END ExternalFunctions */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * Initializes the Global MSP. */ void HAL_MspInit(void) { /* USER CODE BEGIN MspInit 0 */ /* USER CODE END MspInit 0 */ __HAL_RCC_AFIO_CLK_ENABLE(); __HAL_RCC_PWR_CLK_ENABLE(); /* System interrupt init*/ /** NOJTAG: JTAG-DP Disabled and SW-DP Enabled */ __HAL_AFIO_REMAP_SWJ_NOJTAG(); /* USER CODE BEGIN MspInit 1 */ /* USER CODE END MspInit 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ 这段代码串口打印出来的都是0x00,是什么原因,要怎么改,使用的芯片为stm32f103rct6,cpol设置为low cpha设置为1Edge,SPI1_sck、SPI1_miso、SPI1_mosi分别对应的引脚为PA5、PA6、PA7

/* 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" #include "spi.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ #include "stdio.h" #include "string.h" #define W25Q128_WRITE_ENABLE 0x06 #define W25Q128_PAGE_PROGRAM 0x02 #define W25Q128_READ_STATUS_REG 0x05 #define W25Q128_READ_DATA 0x03 #define CS1_L HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET); #define CS1_H HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET); /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ void W25Q128_Write_Enable(void) { uint8_t cmd = W25Q128_WRITE_ENABLE; CS1_L HAL_SPI_Transmit(&hspi1, &cmd, 1, 1000); CS1_H } void W25Q128_Write_Page(uint32_t address, uint8_t* pBuffer, uint16_t numBytes) { uint8_t txData[256]; txData[0] = W25Q128_PAGE_PROGRAM; txData[1] = (address >> 16) & 0xFF; txData[2] = (address >> 8) & 0xFF; txData[3] = address & 0xFF; for(int i = 0; i < numBytes; i++) { txData[4 + i] = pBuffer[i]; } W25Q128_Write_Enable(); CS1_L HAL_SPI_Transmit(&hspi1, txData, 4 + numBytes, 1000); CS1_H } void W25Q128_Read_Data(uint32_t address, uint8_t* pBuffer, uint16_t numBytes) { uint8_t txData[4]; txData[0] = W25Q128_READ_DATA; txData[1] = (address >> 16) & 0xFF; txData[2] = (address >> 8) & 0xFF; txData[3] = address & 0xFF; CS1_L HAL_SPI_Transmit(&hspi1, txData, 4, 1000); HAL_SPI_Receive(&hspi1, pBuffer, numBytes, 1000); CS1_H } /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* 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_SPI1_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ char AN[20]; uint8_t r; /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ W25Q128_Read_Data(r,(uint8_t *)AN, strlen((uint8_t *)AN)); sprintf(AN, "%d\n", r); HAL_UART_Transmit(&huart1, (uint8_t *)AN, strlen((uint8_t *)AN), 10); HAL_Delay(1000); } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ 改错

串口无数据,我这里面有lora通信模块和·adc采集模块还有stm32wle5控制温湿度传感器aht20通过串口显示数据* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2022 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" #include "i2c.h" #include "app_lorawan.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "AHT20.h" #include <stdio.h> #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 ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ float temperature,humidity; char message[50]; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* 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_USART1_UART_Init(); MX_I2C1_Init(); MX_GPIO_Init(); //MX_LoRaWAN_Init(); /* USER CODE BEGIN 2 */ AHT20_Init(); float temperature , humidity ; char message [50]; /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { AHT20_Read( &temperature , &humidity); //??AHT20 sprintf(message ,"wendu: %.lf c , shidu: %.lf %%\r\n",temperature , humidity); HAL_UART_Transmit(&huart2, (uint8_t*)message,strlen(message) , HAL_MAX_DELAY); HAL_Delay(1000); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* 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 LSE Drive Capability */ HAL_PWR_EnableBkUpAccess(); __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW); /** Configure the main internal regulator output voltage */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /** Initializes the CPU, AHB and APB buses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE|RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.LSEState = RCC_LSE_ON; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT; RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Configure the SYSCLKSource, HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK3|RCC_CLOCKTYPE_HCLK |RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1 |RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.AHBCLK3Divider = RCC_SYSCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ #include "aht20.h" #define AHT20_ADDRESS 0x70 void AHT20_Init () { uint8_t readBuffer; HAL_Delay(40); HAL_I2C_Master_Receive(&hi2c1, AHT20_ADDRESS, &readBuffer, 1, HAL_MAX_DELAY); if((readBuffer & 0x08) == 0x00) { uint8_t sendBuffer [3] = {0xBE , 0x08 , 0x00}; HAL_I2C_Master_Transmit(&hi2c1, AHT20_ADDRESS, sendBuffer, 3, HAL_MAX_DELAY); } } void AHT20_Read(float *Temperature , float *Humidity) { uint8_t sendBuffer [3] = {0xAC , 0x33 , 0x00}; uint8_t readBuffer [6]; HAL_I2C_Master_Transmit(&hi2c1, AHT20_ADDRESS, sendBuffer, 3, HAL_MAX_DELAY); HAL_Delay(75); HAL_I2C_Master_Receive(&hi2c1, AHT20_ADDRESS, readBuffer, 6, HAL_MAX_DELAY); if((readBuffer[0] & 0x80) == 0x00) { uint32_t date = 0; date = ((uint32_t )readBuffer[3] >> 4) + ((uint32_t )readBuffer[2] << 4) + ((uint32_t )readBuffer[1] << 12);//?????????. *Humidity = date * 100.0f / (1 << 20); date = (((uint32_t )readBuffer[3] & 0x0F)<< 16) + ((uint32_t )readBuffer[4] << 8) + (uint32_t )readBuffer[5];//& 0x0F: ??????????????0x0F????????0x0F???????00001111,???????readBuffer[3]????,???????? *Temperature = date * 200.0f / (1 << 20) - 50; } }/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.h * @brief : Header for main.c file. * This file contains the common defines of the application. ****************************************************************************** * @attention * * Copyright (c) 2022 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 */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MAIN_H #define __MAIN_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32wlxx_hal.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Exported types ------------------------------------------------------------*/ /* USER CODE BEGIN ET */ /* USER CODE END ET */ /* Exported constants --------------------------------------------------------*/ /* USER CODE BEGIN EC */ /* USER CODE END EC */ /* Exported macro ------------------------------------------------------------*/ /* USER CODE BEGIN EM */ /* USER CODE END EM */ /* Exported functions prototypes ---------------------------------------------*/ void Error_Handler(void); /* USER CODE BEGIN EFP */ /* USER CODE END EFP */ /* Private defines -----------------------------------------------------------*/ #define RTC_N_PREDIV_S 10 #define RTC_PREDIV_S ((1<<RTC_N_PREDIV_S)-1) #define RTC_PREDIV_A ((1<<(15-RTC_N_PREDIV_S))-1) #define LED2_Pin GPIO_PIN_3 #define LED2_GPIO_Port GPIOB #define LED3_Pin GPIO_PIN_4 #define LED3_GPIO_Port GPIOB #define LED1_Pin GPIO_PIN_5 #define LED1_GPIO_Port GPIOB #define BUT1_Pin GPIO_PIN_0 #define BUT1_GPIO_Port GPIOA #define BUT1_EXTI_IRQn EXTI0_IRQn #define USARTx_TX_Pin GPIO_PIN_2 #define USARTx_TX_GPIO_Port GPIOA #define USARTx_RX_Pin GPIO_PIN_3 #define USARTx_RX_GPIO_Port GPIOA #define USE_HAL_DRIVER #define STM32WL55xx /* USER CODE BEGIN Private defines */ /* USER CODE END Private defines */ #ifdef __cplusplus } #endif #endif /* __MAIN_H */ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2022 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" #include "i2c.h" #include "app_lorawan.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "AHT20.h" #include <stdio.h> #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 ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ float temperature,humidity; char message[50]; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* 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_USART1_UART_Init(); MX_USART2_UART_Init(); MX_I2C1_Init(); MX_GPIO_Init(); //MX_LoRaWAN_Init(); /* USER CODE BEGIN 2 */ AHT20_Init(); float temperature , humidity ; char message [50]; HAL_UART_Transmit(&huart2, (uint8_t*)"System Start\r\n", 13, HAL_MAX_DELAY); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { AHT20_Read( &temperature , &humidity); sprintf(message ,"wendu: %.lf c , shidu: %.lf %%\r\n",temperature , humidity); HAL_UART_Transmit(&huart2, (uint8_t*)message,strlen(message) , HAL_MAX_DELAY); HAL_Delay(1000); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* 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 LSE Drive Capability */ HAL_PWR_EnableBkUpAccess(); __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW); /** Configure the main internal regulator output voltage */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /** Initializes the CPU, AHB and APB buses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE|RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.LSEState = RCC_LSE_ON; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT; RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Configure the SYSCLKSource, HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK3|RCC_CLOCKTYPE_HCLK |RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1 |RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.AHBCLK3Divider = RCC_SYSCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* 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 */ /* * aht20.h * * Created on: Apr 25, 2024 * Author: lenovo */ #ifndef INC_AHT20_H_ #define INC_AHT20_H_ #include "i2c.h" void AHT20_Init (); void AHT20_Read(float *Temperature , float *Humidity); #endif /* INC_AHT20_H_ */

大家在看

recommend-type

Delphi 在 DBGrid 里面显示分组统计的源代码

Delphi程序在 DBGrid 里面显示分类统计,也就是小计。用 ClientDataSet 的 TAggregateField 的方法,也可以用 DBGridEh。本程序演示了这两种方法。
recommend-type

硬件测试板级测试电源测试用例汇总华为

电源测试用例集.pdf
recommend-type

sony_imx335.zip

IMX335 驱动代码
recommend-type

信贷管理系统需求规格说明书

目录 第1章 1.1 背景概括 …………………………………………………… 5 1.2 可行性分析……………………………………………………… 7 (1) 经济可行性………………………………………………… 7 (2)操作可行性………………………………………………… 8 (3)技术可行性………………………………………………… (4)系统特点……………………………………………………… 8 第2章 需求分析………………………………………………………… 9 4.1 功能……………………………………………… 11 4.2 目标 4.3 业务流程设计……………………………………………… 11 (1) 存款管理……………………………………………………… 9 (2) 贷款管理…………………………………………………… 10 4.4 业务流程重组 4.5 数据流程图………………………………………………… 13 第3章 总体设计………………………………………………………… 11 第6章 详细设计………………………………………………………… 16 6.1 模块设计 ……………………………………………………… 16 6.2 代码设计……………………………………………………… 20 6.3 输入输出设计 ……………………………………………… 20 结束语 ……………………………………………………………………… 21 致谢 …………………………………………………………………………… 22 参考文献……………………………………………………………………… 23
recommend-type

stm32 蓝牙程序

stm32 开发板运行,通过手机蓝牙进行收发数据,需要的下载。

最新推荐

recommend-type

真题版2009年07月自学考试《计算机组成原理》历年真题.doc

真题版2009年07月自学考试《计算机组成原理》历年真题.doc
recommend-type

公司网络报告怎么做(15篇).docx

公司网络报告怎么做(15篇).docx
recommend-type

1.1算法与程序框图练习.ppt

1.1算法与程序框图练习.ppt
recommend-type

移动通信设备电结构解说.doc

移动通信设备电结构解说.doc
recommend-type

bitHEX-crx插件:提升cryptowat.ch与Binance平台易读性

根据给定文件信息,我们可以提炼出以下知识点: ### 标题知识点:bitHEX-crx插件 1. **插件名称解析**:该部分涉及一个名为“bitHEX”的插件,这里的“CRX”指的是Chrome扩展程序的文件格式。CRX文件是一种压缩包格式,用于在Google Chrome浏览器中安装扩展程序。这说明该插件是为Chrome浏览器设计的。 2. **插件功能定位**:标题直接表明了插件的功能特点,即调整和优化用户界面,特别是涉及到加密货币交易监控平台“cryptowat.ch”的界面颜色设置,以提升用户的视觉体验和阅读便利性。 ### 描述知识点:更改cryptowat.ch和Binance BASIC的颜色 1. **视觉优化目的**:“更改cryptowat.ch上的颜色”说明该插件的主要作用在于通过改变颜色配置,降低视觉上的饱和度,使得数字和线条的阅读变得更加轻松。 2. **平台适配性**:描述中提到的“至少现在是这样”,意味着插件在特定时间点上的功能可能仅限于调整“cryptowat.ch”的颜色设置。同时提到“和Binance BASIC以便于阅读”,表明该插件未来可能会扩展到对Binance等其他交易平台的颜色调整,提高用户在不同平台上的视觉体验。 3. **技术实现细节**:描述中还暗示了插件目前未能改变“交易平台画布上的饱和色”,表明该插件目前可能只影响了网页上的某些特定元素,而非全部。作者表示这一功能将在后续版本中实现。 ### 标签知识点:扩展程序 1. **软件分类**:标签“扩展程序”准确地揭示了bitHEX-crx的软件类型。扩展程序是可安装在浏览器上的小型软件包,用以增强或改变浏览器的默认功能。Chrome扩展程序特别流行于改变和自定义用户的网络浏览体验。 2. **使用环境**:该标签还表明该插件是专门为使用Google Chrome浏览器的用户设计的。Chrome浏览器作为全球使用最多的浏览器之一,有大量的用户基础,因此这类扩展程序的开发对提高用户体验具有重要意义。 ### 压缩包子文件的文件名称列表:bitHEX.crx 1. **文件格式说明**:从文件列表中我们得知该扩展程序的文件名是“bitHEX.crx”。CRX文件格式是专为Chrome浏览器扩展而设计,用户可以直接从Chrome网上应用店下载或通过开发者提供的URL安装CRX文件。 2. **安装方法**:用户获取该CRX文件后,可以通过简单的拖拽操作或在Chrome浏览器的“扩展程序”页面,启用“开发者模式”,然后点击“加载已解压的扩展程序”来安装该插件。 通过以上知识点的分析,我们可以得出,bitHEX-crx插件是一个针对加密货币交易监控平台用户界面的视觉优化Chrome扩展程序。它通过调整颜色设置来改善用户在使用特定金融交易平台时的视觉体验,目的是让数字和线条的显示更加清晰,以便用户能够舒适、高效地进行市场监控和交易操作。随着开发的推进,该插件未来可能会添加更多平台的颜色调整支持。
recommend-type

UnityML-Agents:相机使用与Python交互教程

### Unity ML-Agents:相机使用与Python交互教程 本文将深入探讨在Unity中为智能体添加相机、查看相机视角以及使用Python与Unity ML-Agents进行交互的详细过程。 #### 为智能体添加新相机 在Unity中,为智能体添加新相机可按以下步骤操作: 1. 使用层级面板,创建一个新相机作为“Balancing Ball”对象(智能体和球的父对象)的子对象。 2. 将新相机重命名为有意义的名称,如“Agent Camera”。 3. 调整新相机的位置,使其指向智能体和球。 4. 在层级面板中选择智能体,使用“Add Component”按钮添加“Camer
recommend-type

INA141仿真

INA141 是一款由 Texas Instruments(TI)生产的电流检测放大器,常用于高侧电流检测,具有较宽的共模电压范围和高精度的增益特性。对 INA141 芯片进行电路仿真时,通常可以使用主流的电路仿真工具如 **Pspice** 或 **Tina**,它们支持对电流检测电路的建模与分析。 ### 仿真方法 在进行 INA141 的电路仿真时,需构建一个完整的电流检测电路模型,包括输入端的采样电阻、负载、电源以及 INA141 的外围电路配置。以下是一个典型的仿真流程: 1. **搭建主电路模型**:将 INA141 的输入端连接至采样电阻两端,该电阻串联在电源与负载之间。
recommend-type

揭露不当行为:UT-Austin教授监控Chrome扩展

根据提供的文件信息,我们可以提炼出以下几点与“Professor Watch-crx插件”相关的知识点: 1. 插件功能定位: “Professor Watch-crx插件”是一款专为德克萨斯大学奥斯汀分校(UT-Austin)定制的Chrome扩展程序,旨在帮助学生和教师了解哪些教授曾经侵犯过学校性行为不当政策。该插件将相关信息整合到学校的课程目录中,以便用户在选课时能够掌握教师的相关背景信息。 2. 插件的作用和重要性: 插件提供了一种透明化的方式,使学生在选择课程和教授时能够做出知情的决定。在某些情况下,教授的不当行为可能会对学生的教育体验产生负面影响,因此该插件帮助用户避免潜在的风险。 3. 插件信息展示方式: 插件通过颜色编码来传达信息,具体如下: - 红色:表示UT的标题IX办公室已经确认某教授违反了性行为不当政策。 - 橙色:表示有主要媒体渠道报告了对某教授的不当行为指控,但截至2020年4月,UT的标题IX办公室尚未对此做出回应或提供相关信息。 4. 插件的数据来源和透明度: 插件中包含的信息来自于学生和教师的活动,并经过了一定的公开披露。该插件并非由德克萨斯大学创建或批准,它将用户引向一个外部网站(https://utmiscondone.wordpress.com/about-the-data/),以获取更多可公开获得的信息。 5. 插件的标签: 根据文件提供的信息,这款插件的标签是“扩展程序”(Extension),说明它属于Chrome浏览器的附加组件类别。 6. 插件文件名称: 插件的压缩包子文件名是“Professor_Watch.crx”,这是一个Chrome扩展程序的常用文件格式,用户可以通过Chrome浏览器直接下载并安装该插件。 7. 相关技术知识: - Chrome扩展程序开发涉及HTML、CSS和JavaScript等Web开发技术,以及Chrome扩展API。 - Chrome扩展程序可以利用各种浏览器提供的接口,如标签页、书签、历史记录、下载项和搜索等进行操作。 - 扩展程序的安装包为.crx文件,它是Chrome浏览器专用的打包格式,其中包含了扩展程序的所有资源和文件。 8. 法律与伦理考量: 使用此类插件可能会触及隐私权和诽谤等法律问题。开发者和用户需要注意不要侵犯他人名誉权,同时也要确保收集和发布的数据是准确和合法的。 9. 学术自由和言论自由的边界: 插件可能引发有关学术自由和言论自由边界的讨论。一方面,学生和教师需要在一个安全和支持的环境中学习和工作,另一方面,这也可能带来对教师声誉的不当影响。 通过这些知识点,我们可以看出“Professor Watch-crx插件”是一个旨在提高教育环境透明度和安全性的工具,它也引发了一系列关于个人隐私、信息准确性、法律义务和社会伦理的深入讨论。
recommend-type

UnityML-Agents合作学习与相机传感器应用指南

### Unity ML-Agents 合作学习与相机传感器应用指南 #### 合作学习环境搭建 在构建合作学习环境时,我们需要完成一系列的代码编写和配置工作。首先是环境管理器脚本部分,它的主要功能是重置定时器、旋转整个区域、为代理和方块分配随机位置和旋转,并将方块设置为活动状态。以下是相关代码: ```csharp item.BlockTransform.transform.SetPositionAndRotation(pos,rot); item.RigidBody.velocity = Vector3.zero; item.RigidBody.angularVelocity = Vec
recommend-type

edge下载linux

在Linux系统上下载和安装Microsoft Edge浏览器可以通过多种方式实现。以下是最常见的几种方法: ### 1. 从 Microsoft Edge Insider 网站下载安装包 Microsoft Edge Insider 网站提供了适用于 Linux 的 `.deb` 和 `.rpm` 安装包,用户可以直接访问该网站下载[^1]。这个方法的优势在于系统可以自动更新浏览器版本。 - 访问地址:[https://www.microsoftedgeinsider.com/zh-cn/download/](https://www.microsoftedgeinsider.com/zh