stm32之HAL库实现us延时方法
4 R" o% h8 m' x8 p! u. i jHAL_Delay()源码为ms级别的延时如下:9 w' A6 q) |+ u4 a
1 J2 L% n' N5 @
- /**
$ D/ a, U, T9 r- j4 j" A& e* F - * @brief This function provides accurate delay (in milliseconds) based 7 T; \# D. n' q
- * on variable incremented.
, `7 w4 T6 a# F. u1 T; y' ~9 Z - * @note In the default implementation , SysTick timer is the source of time base.
0 S3 t9 L$ y7 F - * It is used to generate interrupts at regular time intervals where uwTick# d* o- N3 C% B8 c
- * is incremented.
- i7 Y. {0 _: ]9 M7 } - * @note This function is declared as __weak to be overwritten in case of other. |1 }& q' D9 f( |
- * implementations in user file.( v6 g) W4 a2 Z5 P. y( L* T. a
- *
5 t" U& e: N6 l0 x& j - * @param Delay: specifies the delay time length, in milliseconds.
% _# O$ o- n4 J0 ^) i& O - * @retval None
+ z0 a8 I2 ^& M- z1 W% m) r" S* A% ]0 Z - */) D8 O2 d N* L% z5 F
- __weak void HAL_Delay(__IO uint32_t Delay)
8 L# E" U2 M3 {0 B" w5 A - {. H' r3 a2 [: ]3 s8 @+ P
- uint32_t tickstart = 0U;8 Z( n5 _% c2 L: Y- ]
- tickstart = HAL_GetTick();
1 V$ c3 W. K$ k9 y/ i9 a) D - while((HAL_GetTick() - tickstart) < Delay); a% a7 R7 U# \) |' S' R
- {0 c( e: R' U9 |5 W' ]$ d
- }) I o3 v0 ~) U& K: J
- }
复制代码
+ Z2 b6 l7 M/ u8 |1 T& d% N o下面是us级别的延时:
$ m; j3 z& `# p" s; A- void HAL_Delay_us(uint32_t nus)1 L6 ~( }0 u# c! c% c
- {
8 ~" c5 ? H1 I9 b2 x - //将systic设置为1us中断6 J: X, \! _% g7 F) D" c3 I
- HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000000);1 x+ {! q9 Y" z! ~9 v5 V3 h. z5 I
- //延时nus
# ~' A; d7 g) d/ g - HAL_Delay(nus-1);
0 B! J$ M; h2 j+ m8 f# V' o0 l - //恢复systic中断为1ms* ?' q, L/ y9 O$ B0 e: }$ V
- HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);! d! f* _5 ?: ^) S2 e @) D
- }
复制代码
3 g' S% a) @8 y另外需要注意的一点是stm32H7里面时钟配置如下:. ]& L- i7 x0 d( |, Y' w b; N
3 _ d; |* ~! s% b; H
4 h6 n# F9 I' e: [: K, z) K4 c. H& B" j
其中systic是系统时钟直接给systic的而不是HCLK,HAL_RCC_GetHCLKFreq()正好是系统时钟的1/2所以上面配置1us时钟源要改为如下:
: Y0 B3 c B. I0 z( W) D9 g- m4 Q% O5 \" ~
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()*2/1000000);
& ~# l- S) j! C% i8 j2 f3 E1 g1 c1 x8 v Z7 {
7 L- }, K/ G2 m9 s8 X8 y' P
|