本帖最后由 yinxiangxv 于 2024-8-13 18:53 编辑
首先还是按照一般的 流程,用cube mx进行代码的生成:
选择相关芯片,进行相关时钟的配置,然后在定时器的通道,并使能相关的引脚,使其产生pwm信号。
具体操作过程和代码如下:
可以根据自己的需要开启调试接口
关于系统时钟,可以采用默认的,也可以自行设置一下,hclk设置为250也可以.
在tim.c文件中实现相关的函数:
/* USER CODE BEGIN 1 */
void UpdataFreData(int value)
{
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
htim2.Instance = TIM2;
htim2.Init.Prescaler = 24;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = value;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_OC_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = htim2.Init.Period/2;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1);
}
void UpdataDutyData(int value)
{
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
htim2.Instance = TIM2;
htim2.Init.Prescaler = 24;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 1999;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_OC_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 1999 * value/100 ;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1);
}
/* USER CODE END 1 */
并在头文件中进行声明
最后在main.c中进行调用
|