|
【STM32入門級程序9】使用SysTick精確控制流水燈的流速 |
一派掌門 二十級 |
【main.c】 #include <stm32f10x.h>
int main(void) { GPIO_InitTypeDef init;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
init.GPIO_Pin = GPIO_Pin_All; init.GPIO_Speed = GPIO_Speed_50MHz; init.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOB, &init);
SysTick_Config(SystemCoreClock / 5); // 設定中斷觸發周期為五分之一秒,也就是0.2秒
GPIOB->ODR = 0x100;
while (1); } 【stm32f10x_it.c】 ....................................... ....................................... /** * @brief This function handles SysTick Handler. * @param None * @retval None */ // 這個函數每隔0.2秒執行一次 int nCounter = 0; void SysTick_Handler(void) { nCounter++; if (nCounter >= 5) // 當這個變量的值等於5時,就剛好是1秒 { nCounter = 0; GPIOB->ODR <<= 1; if (!GPIOB->ODR) GPIOB->ODR = 0x100; } } ......................................... ........................................
|
一派掌門 二十級 |
【說明】 SysTick_Config函數用於配置計時器。裏面的值越小,同一時間內計時器中斷的觸發次數就越少。 SysTick_Config(SystemCoreClock);剛好是1秒鐘觸發一次中斷,但是如果直接這樣寫會因為數字太大而出錯,如果寫成SysTick_Config(SystemCoreClock / 5);(0.2秒觸發一次)或者更小的數就不會出問題。 另外,SysTick_Config(SystemCoreClock / 1000);剛好是1毫秒觸發一次中斷,這個也很常用。
|
|
一派掌門 二十級 |
執行SysTick->CTRL = 0;就可以使計時器停止。 例如: int nCounter = 0; void SysTick_Handler(void) { nCounter++; if (nCounter >= 5) { nCounter = 0; GPIOB->ODR <<= 1;
if (!GPIOB->ODR) { GPIOB->ODR = 0x100; SysTick->CTRL = 0; // 當流水燈流完全部LED燈並回到起點後停止 } } }
|
|
一派掌門 二十級 |
【精確的delay延時函數】 /*[main.c]*/ //...... extern uint32_t systick_counter; // 精確延時n毫秒 void delay(uint32_t nms) { systick_counter = nms; while (systick_counter > 0); } //...... int main(void) { //...... SysTick_Config(SystemCoreClock / 1000); // 定時器中斷1ms觸發一次 //...... } /*[stm32f10x_it.c]*/ #include "stm32f10x_it.h" uint32_t systick_counter = 0; //...... void SysTick_Handler(void) { if (systick_counter > 0) systick_counter--; } //......
|
|