stm32之HAL库实现us延时方法
% E9 i7 N0 l3 O; q. RHAL_Delay()源码为ms级别的延时如下:+ v! Y! M& H2 L: X. u3 E2 \& i. r6 r# U
7 J2 H- x d/ Q- W; A/ l
- /**3 o$ J S! |8 M9 K# g' S
- * @brief This function provides accurate delay (in milliseconds) based + C8 z! o; s3 n
- * on variable incremented.
, T r9 B# ?. T% r - * @note In the default implementation , SysTick timer is the source of time base.
9 O: s+ p/ r5 m# e - * It is used to generate interrupts at regular time intervals where uwTick$ h8 Q3 V( x- Z! X* ~* ^& G2 m# [, z1 S
- * is incremented.
) I& J1 z5 l/ }5 E) X& e# l - * @note This function is declared as __weak to be overwritten in case of other, j j5 u, w6 N& ^6 M& c0 s/ y
- * implementations in user file.
9 Z6 Y" g1 i' M/ w5 |" l* U" [ - *
9 R" ~1 {( Y6 n! l7 {6 C" I - * @param Delay: specifies the delay time length, in milliseconds.
& v6 c. G/ |( h2 l! q, K% C - * @retval None/ P) G3 c1 ?5 w9 Y
- */- `! q1 f% p2 t) N/ f
- __weak void HAL_Delay(__IO uint32_t Delay)
* k h" a# t( j" P: ^! D5 | - {7 K& S! @ b: a: O
- uint32_t tickstart = 0U;
- T ?' p" P8 J4 b' s, j - tickstart = HAL_GetTick();9 z% \5 y( C. M" \ z: e# l- I9 X
- while((HAL_GetTick() - tickstart) < Delay)
5 l+ h: D- I6 a% r8 O$ I2 l - {
0 n4 f' [8 h% W1 T5 | - }0 y* W( w6 Z( A& w
- }
复制代码
5 R1 P* J/ d! ~$ i5 t' }3 D1 t( i下面是us级别的延时:
- h+ I! a: c. N& q) c* S! W8 Q- q- void HAL_Delay_us(uint32_t nus)
; m8 k' ~% X6 p4 Y9 L* b$ N - {
y8 _- [- P6 X - //将systic设置为1us中断
4 }3 t1 o5 e. ? - HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000000);
: h7 _0 p1 K1 a. D - //延时nus! J# H O/ f! v* p* K
- HAL_Delay(nus-1);! y) Z+ T" x% x; Z% u+ N
- //恢复systic中断为1ms3 |! t) w: K+ ~9 M$ `8 h2 T: q5 a
- HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
; T$ U8 R: X$ ~* q - }
复制代码
5 Q2 ~- U4 c$ f+ J$ h另外需要注意的一点是stm32H7里面时钟配置如下:
. }6 D/ v c1 s! r$ {: { z$ p4 g j" }! K
$ b& V# C+ K* j/ I/ g- j, i
7 w# [" A& V- D! z$ `7 v' y( F, E其中systic是系统时钟直接给systic的而不是HCLK,HAL_RCC_GetHCLKFreq()正好是系统时钟的1/2所以上面配置1us时钟源要改为如下:
4 R7 Y0 W/ B: k1 t1 H ?) n1 m' G8 z1 [2 ]
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()*2/1000000);
% X; U; G7 {5 Y; U/ D- K! t( N
4 F; Y. g: F+ [4 M1 d% w2 i, @$ B; x3 U7 [5 } T
|