[经验]
【Nucleo G071评测】PWM呼吸灯
评测一个开发板的定时器功能,最简单的方式就是评测它的呼吸灯功能,呼吸灯是由PWM波实现的,PWM则是由定时器产生的。
打开CubeMX初始化PC6 PC8 PC9三个引脚,分别映射为定时器3的CH1 CH3 CH4通道,用于驱动RGB灯的三个引脚,设置定时器3不分频(即分频值为0),独立时钟,计数值为100上限:
调好了之后就可以直接接RGB灯了,初始化函数如下:
void TIM3_Init()
{
GPIO_InitTypeDef GPIO_InitStruct;
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_TIM3_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_8|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_TIM3;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
htim3.Instance = TIM3;
htim3.Init.Prescaler = 0;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 100;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
HAL_TIM_PWM_Init(&htim3);
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig);
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse=0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_3);
HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_4);
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_3);
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_4);
TIM3->CCR1=0;
TIM3->CCR3=0;
TIM3->CCR4=0;
}
通过TIM3的CCRX寄存器来修改三个通道的占空比:
TIM3->CCR1=0;
TIM3->CCR3=0;
TIM3->CCR4=0;
for(i=0;i<=100;i++)
{
TIM3->CCR1=i;
Delay_ms(5);
}
Delay_ms(500);
for(i=100;i>=0;i--)
{
TIM3->CCR1=i;
Delay_ms(5);
}
for(i=0;i<=100;i++)
{
TIM3->CCR3=i;
Delay_ms(5);
}
Delay_ms(500);
for(i=100;i>=0;i--)
{
TIM3->CCR3=i;
Delay_ms(5);
}
for(i=0;i<=100;i++)
{
TIM3->CCR4=i;
Delay_ms(5);
}
Delay_ms(500);
for(i=100;i>=0;i--)
{
TIM3->CCR4=i;
Delay_ms(5);
}
看看效果:
暂无评论,赶紧抢沙发吧