STM32精確延遲1us和1ms的函數(shù)
延遲1us:
1 /*****************************************************
2 * 函 數(shù) 名 : delay_us
3 * 函數(shù)功能 : 延時(shí)函數(shù),延時(shí)us
4 * 輸 入 : i
5 * 輸 出 : 無
6 *******************************************************************************/
7 void delay_us(u32 i)
8 {
9 u32 temp;
10 SysTick-LOAD=9*i; /設(shè)置重裝數(shù)值, 72MHZ時(shí)
11 SysTick-CTRL=0X01; /使能,減到零是無動(dòng)作,采用外部時(shí)鐘源
12 SysTick-VAL=0; /清零計(jì)數(shù)器
13 do
14 {
15 temp=SysTick-CTRL; /讀取當(dāng)前倒計(jì)數(shù)值
16 }
17 while((temp0x01)(!(temp(116)))); /等待時(shí)間到達(dá)
18 SysTick-CTRL=0; /關(guān)閉計(jì)數(shù)器
19 SysTick-VAL=0; /清空計(jì)數(shù)器
20 }
延遲1ms:
1 /*****************************************************
2 * 函 數(shù) 名 : delay_ms
3 * 函數(shù)功能 : 延時(shí)函數(shù),延時(shí)ms
4 * 輸 入 : i
5 * 輸 出 : 無
6 ******************************************************/
7 void delay_ms(u32 i)
8 {
9 u32 temp;
10 SysTick-LOAD=9000*i; /設(shè)置重裝數(shù)值, 72MHZ時(shí)
11 SysTick-CTRL=0X01; /使能,減到零是無動(dòng)作,采用外部時(shí)鐘源
12 SysTick-VAL=0; /清零計(jì)數(shù)器
13 do
14 {
15 temp=SysTick-CTRL; /讀取當(dāng)前倒計(jì)數(shù)值
16 }
17 while((temp0x01)(!(temp(116)))); /等待時(shí)間到達(dá)
18 SysTick-CTRL=0; /關(guān)閉計(jì)數(shù)器
19 SysTick-VAL=0; /清空計(jì)數(shù)器
20 }
注意:以上兩函數(shù)中間的參數(shù)u32 i不能超過1800,舉例,想定時(shí)一分鐘,可以通過for循環(huán)讓delay_ms(1000)走60次,而不能使用delay_ms(60000),不然程序就出錯(cuò)了。