SysTick系统定时器

1. 使用系统定时器实现流水灯效果。

2. 代码:

  main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "stm32f10x.h"
#include "bsp_led.h"
#include "bsp_systick.h"
 
int main(void)
{      
    LED_GPIO_Config();
    while(1)
    {
        //方法1
        /*绿灯*/
        GPIO_ResetBits(LED_G_GPIO_PORT,LED_G_GPIO_PIN); /*开灯*/
        SysTick_Delay_ms(500);
        GPIO_SetBits(LED_G_GPIO_PORT,LED_G_GPIO_PIN);   //关灯
        SysTick_Delay_ms(500); 
         
//      //方法2
//      LED_G(OFF); //关灯
//      SysTick_Delay_ms(500);
//      LED_G(ON);      /*开灯*/
//      SysTick_Delay_ms(500);
    }
 
}

  

  bsp_systick.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "bsp_systick.h"
 
void SysTick_Delay_us(uint32_t us)
{
    uint32_t i;
    SysTick_Config(72);
     
    for(i=0; i<us; i++)
    {
        while(!((SysTick->CTRL) & (1<<16)));
    }
     
    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}
 
void SysTick_Delay_ms(uint32_t ms)
{
    uint32_t i;
    SysTick_Config(72000);
     
    for(i=0; i<ms; i++)
    {
        while(!((SysTick->CTRL) & (1<<16)));
    }
     
    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}

  

  bsp_systick.h

1
2
3
4
5
6
7
8
9
10
#ifndef __bsp_systick_h
#define __bsp_systick_h
#include "stm32f10x.h"
#include "core_cm3.h"
 
void SysTick_Delay_us(uint32_t us);
void SysTick_Delay_ms(uint32_t ms);
 
 
#endif /*__bsp_systick_h*/

  

  bsp_led.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "bsp_led.h"
 
void LED_GPIO_Config(void)
{
    GPIO_InitTypeDef    GPIO_InitStruct;
     
    RCC_APB2PeriphClockCmd(LED_G_GPIO_CLK,ENABLE);
     
    GPIO_InitStruct.GPIO_Pin = LED_G_GPIO_PIN;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(LED_G_GPIO_PORT, &GPIO_InitStruct);
     
}

  

  bsp_led.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef __bsp_led_h
#define __bsp_led_h
 
#include "stm32f10x.h"
//方法1
#define LED_G_GPIO_PIN          GPIO_Pin_0
#define LED_G_GPIO_PORT         GPIOB
#define LED_G_GPIO_CLK          RCC_APB2Periph_GPIOB
 
//方法2
#define ON  1
#define OFF 0
#define LED_G(a)    if(a)   GPIO_SetBits(LED_G_GPIO_PORT,LED_G_GPIO_PIN);   \
                                    else GPIO_ResetBits(LED_G_GPIO_PORT,LED_G_GPIO_PIN);
                                     
 
void LED_GPIO_Config(void);
 
#endif /*__bsp_led_h*/

  

3. 参考资料

  • SysTick—系统定时器是属于 CM3 内核中的一个外设,内嵌在 NVIC 中。
  • 因为 SysTick 是属于 CM3 内核的外设,所以所有基于 CM3 内核的单片机都具有这个系统定时器,使得软件在 CM3 单片机中可以很容易的移植。
  • 编程要点
    • 设置重装载寄存器的值
    • 清除当前数值寄存器的值
    • 配置控制与状态寄存器
  • 原理图
  •  
  •  


4. 总结

 

posted @   JRS077  阅读(121)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示