以下源码以定时器3为例,其他可以以此类推
) p- N' p4 [9 u8 E7 y* \! p
; t8 x1 [8 b6 w; K* _# T: i.c文件
) Z8 \- q- p, S( f- x- #include "Time.h"
6 y; n3 d8 u$ U7 K! G
8 J& ^1 u( s# @1 F6 s; }: i- void TIM3_Int_Init(uint32_t time_us)
2 U) E# i I4 S. S( l8 D; G3 h - {- E; f8 E$ y$ N. }; {
- TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
3 r+ J# f( a- f' {/ @ - NVIC_InitTypeDef NVIC_InitStructure;
" H: Y* x. j) @: w6 s - ' @* i; b- j! |3 Z' E2 q
- unsigned char prescaler = 1;
+ w$ n3 i$ X p0 |: Q3 X5 s - unsigned char clkDiv = 1;//根据“TIM_ClockDivision”的分频比来定/ E3 q) t# W% t" V, f ]
- unsigned long period = time_us*(SystemCoreClock/1000000) / (prescaler * clkDiv);/ Z) L g! e3 F: }. Z: K" `6 o
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
* Y1 V; p* [0 j- f) W9 S" Z - 4 i! U. `8 w8 i4 y3 H
- TIM_TimeBaseStructure.TIM_Period = period;
- _. N! e% G+ L0 ~! p4 c - TIM_TimeBaseStructure.TIM_Prescaler = prescaler - 1; //时钟再分频,会影响TIM_Period的效果" x! K7 u& U; i3 g
- TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; //时钟分频,会影响PWM的计数个数. F5 q. O8 ~% \
- TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;/ B$ A$ f! \) ^: G
- TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);8 I! b. o3 t: ]; }. L" h0 O2 |
- $ z/ E# |0 n. |6 @# a- M ]
- TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //使能指定的TIM3中断,允许更新中断
+ u2 w0 D1 ?% g8 Q$ |1 \ - 2 ~" B1 a1 K9 }& N9 O
- NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn;- ?: {) q" i' Y' I( P) @
- NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;. n$ r0 G; {$ i! V
- NVIC_InitStructure.NVIC_IRQChannelPriority=1;
- g# M1 e& e1 I" w% \ - NVIC_Init(&NVIC_InitStructure); 7 ~, N1 f+ {- D: n( ]4 T% P
/ e3 T' S, ?6 p0 P: Z& T6 E; z- TIM_Cmd(TIM3, ENABLE); , I; ~5 l7 @. s2 L( p+ \" b
- }9 y# Q( r; n( {0 {6 w5 k
- 8 n3 X2 C# _# ^ J" _7 n' V
- void TIM3_IRQHandler(void) //TIM3中断
; b. x/ h6 {5 } - {6 Q! M. Z! f; t8 S
- if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查TIM3更新中断发生与否
t: q' B$ G+ E, i - {
2 w# x+ R* U! }6 q" @. Z -
& s- t. q0 r7 d; v; y6 h1 A, A - TIM_ClearITPendingBit(TIM3, TIM_IT_Update); //清除TIMx更新中断标志
1 f" U4 s( q1 G$ X% ?0 X - 5 d8 u! M# Y4 Z5 O: [$ [/ x0 }
- }
* E9 y8 v+ J# I; Z - }
复制代码
/ b) Q M8 d# h* d9 \0 l.h文件
1 p h( a: Y6 Z# t" T6 [7 W. H- #ifndef _TIME_H+ M* h Q6 t7 h& ^+ t8 z3 z5 j
- #define _TIME_H, f }; f# O& N6 V0 x3 G
- #include "stm32f0xx.h"" F1 R' b% P4 ~+ x+ Y
- N: s- x" y7 j# G2 @6 I% \$ X( l- void TIM3_Int_Init(uint32_t time_us);
8 F% @' o1 q6 b - $ N2 y/ C( ~2 F6 j) r: b5 B) P0 s" O: e
- #endif
复制代码 , n8 Z1 C2 Y8 B* y3 }5 S/ O
0 O$ e& m, |; Z. Q0 e$ w
2 J% \0 [# g( q/ l' K9 \9 W) D) I |