本来想做个输出PWM波实验的,家里没有示波器。就做个基础的定时功能。采用的通用定时器TIM2来计时,并让LED等闪烁,突然觉得LED好有用啊。对于捕获比较功能暂时没有测试。STM32有的,GD32都有,这里也是直接采用STM32的固件库来完成代码。
1、初始化通用定时器2
void TimerInit(u16 arr,u16 psc) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct; NVIC_InitTypeDef NVIC_InitStruct; RCC_APB1PeriphClockCmd (RCC_APB1Periph_TIM2,ENABLE ); TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStruct.TIM_Period = arr; TIM_TimeBaseInitStruct.TIM_Prescaler = psc; TIM_TimeBaseInit (TIM2,&TIM_TimeBaseInitStruct); TIM_ITConfig (TIM2,TIM_IT_Update,ENABLE ); NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1; NVIC_Init(&NVIC_InitStruct); TIM_Cmd (TIM2,ENABLE); }
中断服务函数:
void TIM2_IRQHandler() { if(TIM_GetITStatus (TIM2,TIM_IT_Update) == SET) { gLedRunFlag ^= 1; TIM_ClearITPendingBit (TIM2,TIM_IT_Update); } }
主函数代码:
int main() { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); LedPinInit(); TimerInit(4999,7199); //500ms while(1) { if(gLedRunFlag != gLastLedFlag) { LedPowerSelect(gLedRunFlag); gLastLedFlag = gLedRunFlag; } } }
效果图:
定时器还是有挺多可以玩的,如果有个红外接收头可以利用捕获做个红外解码的实验。当然GD32的片内资源也完全不输给STM32。为了更好的玩板子,接下来准备把TFT彩屏点亮,想看看GD32的刷屏效果如何。