|  | 【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--;
 }
 //......
 
 
 |