/** if you want to use pwm you can use the following instructions. * * STEP 1, open pwm driver framework support in the RT-Thread Settings file * * STEP 2, define macro related to the pwm * such as #define BSP_USING_PWM1 * * STEP 3, copy your pwm timer init function from stm32xxxx_hal_msp.c generated by stm32cubemx to the end if board.c file * such as void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base) and * void HAL_TIM_MspPostInit(TIM_HandleTypeDef* htim) * * STEP 4, modify your stm32xxxx_hal_config.h file to support pwm peripherals. define macro related to the peripherals * such as #define HAL_TIM_MODULE_ENABLED * */
這是官方給的標準步驟,我按照這個步驟進行了好幾遍都沒有成功,錯誤每次都是幾十個,(也多是我本身的問題),下面我分享下我成功的步驟。
STEP 1:
在RT-Thread Settings中使能PWM設備。
STEP 2:
註釋掉board.h中關於PWM的宏定義。
函數
#define BSP_USING_PWM1 //你所使用的PWM /*#define BSP_USING_PWM2*/ /*#define BSP_USING_PWM3*/ #define BSP_USING_PWM1_CH1 //你使用的通道
STEP 3:
使用STM32CudeMX生成stm32f1xx_hal_msp.c文件。
文件位於Src文件夾下,打開文件咱們複製HAL_TIM_MspPostInit函數到drv_pwm.c文件下
spa
void HAL_TIM_MspPostInit(TIM_HandleTypeDef* htim) { GPIO_InitTypeDef GPIO_InitStruct = { 0}; if(htim->Instance==TIM1) { /* USER CODE BEGIN TIM1_MspPostInit 0 */ /* USER CODE END TIM1_MspPostInit 0 */ __HAL_RCC_GPIOA_CLK_ENABLE(); /**TIM1 GPIO Configuration PA8 ------> TIM1_CH1 */ GPIO_InitStruct.Pin = GPIO_PIN_8; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN TIM1_MspPostInit 1 */ /* USER CODE END TIM1_MspPostInit 1 */ } }
在drv_pwm.c文件下修改一處code
static void pwm_get_channel(void) { #ifdef BSP_USING_PWM1_CH1 stm32_pwm_obj[PWM1_INDEX].channel |= 1 << 0; __HAL_RCC_TIM1_CLK_ENABLE(); //修改處使能定時器時鐘 #endif
STEP 4:
打開pwm_config.h文件,參照給的例子添加。默認是沒有TIM1的。
blog
#ifdef BSP_USING_PWM1 #ifndef PWM1_CONFIG #define PWM1_CONFIG \ { \ .tim_handle.Instance = TIM1, \ .name = "pwm1", \ .channel = 0 \ } #endif /* PWM1_CONFIG */ #endif /* BSP_USING_PWM2 */ #ifdef BSP_USING_PWM2 #ifndef PWM2_CONFIG #define PWM2_CONFIG \ { \ .tim_handle.Instance = TIM2, \ .name = "pwm2", \ .channel = 0 \ } #endif /* PWM2_CONFIG */ #endif /* BSP_USING_PWM2 */
最後打開stm32f1xx_hal_conf.h圖片
/*#define HAL_SRAM_MODULE_ENABLED */ #define HAL_TIM_MODULE_ENABLED //取消註釋 #define HAL_UART_MODULE_ENABLED /*#define HAL_USART_MODULE_ENABLED */ /*#define HAL_WWDG_MODULE_ENABLED */