TIMx_ETR外部时钟源模式2配置方法

由于stm32中的时钟源对应的GPIO口都是ST原厂已经分配好的,可以查看数据手册了解,所以我们要将外部触发信号连接到对应的时钟源GPIO pin口,这样才能起到外部时钟源的作用。

例如:TIM3_ETR外部时钟源是接在PD2口的,如果你连接其他GPIO_Pin口,此时不会进入中断函数,也就没有起到外部时钟源的作用。

 

Timer.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "stm32f10x.h"
extern uint16_t Num;
 
void Timer_Init(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);
     
    //配置GPIO
    GPIO_InitTypeDef    GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOD,&GPIO_InitStructure);
     
    TIM_ETRClockMode2Config(TIM3, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_Inverted,0x00);
     
//  TIM_InternalClockConfig(TIM2);  //单片机上电自动默认TMI2,可不写
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStructure.TIM_Period = 10 -1;   // 0~65535
    TIM_TimeBaseInitStructure.TIM_Prescaler = 1 -1; // 0~65535
    TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
     
    TIM_ClearFlag(TIM3, TIM_FLAG_Update);   //避免刚好初始化就进入中断
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
 
    TIM_Cmd(TIM3,ENABLE);
     
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
     
    NVIC_InitTypeDef    NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
    NVIC_Init(&NVIC_InitStructure);
     
 
}
 
 
uint16_t Timer_GetCounter(void)
{
    return TIM_GetCounter(TIM3);
}
 
void TIM2_IRQHandler(void)
{
    if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET)
    {
        Num++;
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
    }
}

 Timer.h

1
2
3
4
5
6
7
#ifndef __TIMER_H
#define __TIMER_H
 
void Timer_Init(void);
uint16_t Timer_GetCounter(void);
 
#endif

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "stm32f10x.h"
#include "Delay.h"
#include "OLED.h"
#include "Timer.h"
 
uint16_t Num;
 
int main(void)
{
    OLED_Init();
    Timer_Init();
    OLED_ShowString(1, 1, "Num:");
    OLED_ShowString(2, 1, "CNT:");
 
    while(1)
    {      
        OLED_ShowNum(1, 5, Num, 5);
        OLED_ShowNum(2, 5, Timer_GetCounter(), 5);
    }
}

  

  

 

posted @   JRS077  阅读(1429)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示