实验原理:
通过STM32的三个GPIO口来驱动LED灯的三个通道,设定GPIO为推挽输出模式,采
用灌电流的方式与LED连接,输出高电平LED灭,输出低电平LED亮,通过通用定时器TIM3
实现500ms定时,每500ms变换一次LED颜色。
核心代码:
void MX_TIM3_Init(void)
{
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig; htim3.Instance = TIM3;
htim3.Init.Prescaler = ;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = ;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
} sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
} sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
} }
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
static int counter = ; if(counter % == ){
LED_RED_ON;
LED_BLUE_OFF;
LED_GREEN_OFF;
}else if(counter % == ){
LED_RED_OFF;
LED_BLUE_ON;
LED_GREEN_OFF;
}else if(counter % == ){
LED_RED_OFF;
LED_BLUE_OFF;
LED_GREEN_ON;
}
counter ++;
}
源代码下载链接:
链接:http://pan.baidu.com/s/1kVeflcj 密码:z812
iCore4链接: