rt-thread中的PWM在stm32单片机上的应用
1. RT_USING_PWM
要用PWM的device,首先就需要在rtconfig.h中定义RT_USING_PWM这个宏,很简单,配置里勾勾就实现了。
2. BSP_USING_PWM1
然后在board.h里看到这段相关代码:
/*-------------------------- PWM CONFIG BEGIN --------------------------*/
/** 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
*
*/
/*#define BSP_USING_PWM1*/
/*#define BSP_USING_PWM2*/
/*#define BSP_USING_PWM3*/
/*-------------------------- PWM CONFIG END --------------------------*/
这里已经说的很清楚了,按指示做。
我用了PWM1所以我定义了:
#define BSP_USING_PWM1
3. BSP_USING_PWM1_CH1
参考官网PWM驱动:
https://www.rt-thread.org/document/site/application-note/driver/pwm/an0037-rtthread-driver-pwm/#pwm_4
里面要配置Kconfig 文件。
其实,简单的方法就是在board.h文件里,定义使用通道的宏
#define BSP_USING_PWM1
#define BSP_USING_PWM1_CH1
我用的是PWM1的通道1,所以就这样定义了。
4. HAL_TIM_PWM_MspInit
然后是最关键的一步,在board.c文件中实现HAL_TIM_PWM_MspInit函数。
这个函数是cube mx生成的。我用的PWM1的CH1。
void HAL_TIM_PWM_MspInit(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_GPIOE_CLK_ENABLE();
/**TIM1 GPIO Configuration
PE9 ------> TIM1_CH1
*/
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/* USER CODE BEGIN TIM1_MspPostInit 1 */
/* USER CODE END TIM1_MspPostInit 1 */
}
}
后面调试和很久,发现端口总是没有PWM波形输出,后来发现,是差了一个调用函数。为了少修改,又不影响文件结构,我简化成:
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef* htim)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(htim->Instance==TIM1)
{
/* USER CODE BEGIN TIM1_MspPostInit 0 */
__HAL_RCC_TIM1_CLK_ENABLE(); /*这句是必须的!!!*/
/* USER CODE END TIM1_MspPostInit 0 */
__HAL_RCC_GPIOE_CLK_ENABLE();
/**TIM1 GPIO Configuration
PE9 ------> TIM1_CH1
*/
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/* USER CODE BEGIN TIM1_MspPostInit 1 */
//HAL_NVIC_SetPriority(TIM1_CC_IRQn, 0, 0);
//HAL_NVIC_EnableIRQ(TIM1_CC_IRQn);
/* USER CODE END TIM1_MspPostInit 1 */
}
}
__HAL_RCC_TIM1_CLK_ENABLE();需要曾经被调用过,在cubemx里,__HAL_RCC_TIM1_CLK_ENABLE();这个函数在其他函数里已经被调用过了,所以自动生成的HAL_TIM_PWM_MspInit()就没有再次调用,但是rt-thread里,就只能自己调用了。
这个问题解决后,剩下就没有难点了,按着指示还有例子,一步一步做下去就可以实现PWM控制了。