本帖最后由 jf_87001978 于 2022-12-22 21:47 编辑
源代码和开发文档地址:
https://gitee.com/mftang/n32-g45-xvl-stb.git
4.1 需求
4.2 代码实现
4.2.1 系统时钟分析
4.2.2 代码分析system clock = 144 M
debug 调试代码得到:
默认TIMCLKSEL = 0, 则TIME1/8 CLK = 144 M
通过以上分析可知: 定时器的工作频率为 144 000000,实现定时器部分代码
- void timer_Configuration(void)
- {
- uint16_t PrescalerValue = 0;
- TIM_TimeBaseInitType TIM_TimeBaseStructure;
- /* TIM1 clock enable */
- RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_TIM1, ENABLE);
- /*
- SystemCoreClock = 144 000000
- PrescalerValue = 144
- Period = 100
- time count: 1 us
- */
- PrescalerValue = 144 - 1;
-
- /* Time base configuration */
- TIM_TimeBaseStructure.Prescaler = 0;
- TIM_TimeBaseStructure.Period = 1000-1; // 中断计数器,1 ms 产生一个中断
- TIM_TimeBaseStructure.ClkDiv = TIM_CLK_DIV1;
- TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
- TIM_InitTimeBase(TIM1, &TIM_TimeBaseStructure);
- /* Prescaler configuration */
- TIM_ConfigPrescaler(TIM1, PrescalerValue, TIM_PSC_RELOAD_MODE_IMMEDIATE);
- /* TIM1 enable update irq */
- TIM_ConfigInt(TIM1, TIM_INT_UPDATE, ENABLE);
- /* TIM1 enable counter */
- TIM_Enable(TIM1, ENABLE);
- }
复制代码
配置中断参数:
- void timer_NVIC_Configuration(void)
复制代码
中断程序:
- void TIM1_UP_IRQHandler(void)
- {
- if (TIM_GetIntStatus(TIM1, TIM_INT_UPDATE) != RESET)
- {
- TIM_ClrIntPendingBit(TIM1, TIM_INT_UPDATE);
- LedBlink(GPIO_LED1, PIN_LED1); // 用于捕捉波形
- }
- }
复制代码
4.3 测试
硬件连接:
波形分析:
4.4 扩展实验
实现一个使用Timer -1 1s 定时功能, 监测LED 1s 闪烁一次
4.4.1 在中断函数中实现
- int count;
- void TIM1_UP_IRQHandler(void)
- {
- if (TIM_GetIntStatus(TIM1, TIM_INT_UPDATE) != RESET)
- {
- TIM_ClrIntPendingBit(TIM1, TIM_INT_UPDATE);
- if( (count % 1000) == 0)
- {
- LedBlink(GPIO_LED1, PIN_LED1); // 用于捕捉波形
- }
- count ++;
- }
- }
复制代码
波形图
4.4.2 修改配置参数实现初始化函数:
- void timer_Configuration(void)
- {
- uint16_t PrescalerValue = 0;
- TIM_TimeBaseInitType TIM_TimeBaseStructure;
- /* TIM1 clock enable */
- RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_TIM1, ENABLE);
- /*
- SystemCoreClock = 144 000000
- PrescalerValue = 144 00
- Period = 10000
- time count: 1 s
- */
- /* Compute the prescaler value */
- PrescalerValue = 14400 - 1;
-
- /* Time base configuration */
- TIM_TimeBaseStructure.Prescaler = 0;
- TIM_TimeBaseStructure.Period = 10000-1;
- TIM_TimeBaseStructure.ClkDiv = TIM_CLK_DIV1;
- TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
- TIM_InitTimeBase(TIM1, &TIM_TimeBaseStructure);
- /* Prescaler configuration */
- TIM_ConfigPrescaler(TIM1, PrescalerValue, TIM_PSC_RELOAD_MODE_IMMEDIATE);
- /* TIM1 enable update irq */
- TIM_ConfigInt(TIM1, TIM_INT_UPDATE, ENABLE);
- /* TIM1 enable counter */
- TIM_Enable(TIM1, ENABLE);
- }
复制代码
中断函数:
- static int count;
- void TIM1_UP_IRQHandler(void)
- {
- if (TIM_GetIntStatus(TIM1, TIM_INT_UPDATE) != RESET)
- {
- TIM_ClrIntPendingBit(TIM1, TIM_INT_UPDATE);
- // if( (count % 1000 ) == 0 )
- {
- LedBlink(GPIO_LED1, PIN_LED1);
- }
- count ++;
- }
- }
复制代码
波形图
|