SysTick
- 1> SysTick硬件框图
- 2> SysTick的时钟源
- 3> 1ms定时_中断方式
- 4> 思考:无符号数 0 - 255 = ?
- 相关资料
1> SysTick硬件框图
SysTick属于Cotex-M3,是CPU外设;
SysTick: 位宽24bit, 递减计数,自动重装载;
2> SysTick的时钟源
HCLK 72MHz 经过8分频或1分频送给SysTick;
3> 1ms定时_中断方式
main.c:
#include "stm32f10x.h"
#include "bsp_led.h"
#include "bsp_systick.h"
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); // 中断优先级分组
LED_Init();
SysTick_Init();
while(1) {
LED_On();
SysTick_Delay(100);
LED_Off();
SysTick_Delay(100);
}
//return 0;
}
bsp_systick.c:
#include "bsp_systick.h"
uint32_t g_Tick;
/**
* @brief Initialize and start the SysTick counter and its interrupt.
* Configure the SysTick interrupt time for 1ms
* @param None
* @return None
*/
void SysTick_Init(void)
{
SysTick_Config(72000000 / 1000); // 1ms
// 设置SysTick中断优先级, SysTick_Config会对SysTick的优先级初始化
// 所以设置优先级的函数放到SysTick_Config函数之后
NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(NVIC_PriorityGroup_2, 0, 0));
}
/**
* @brief Provides accurate delay(in ms) based g_Tick++.
* @param Delay: specifies the delay time length, in milliseconds.
* @return None
*/
void SysTick_Delay(uint32_t Delay)
{
uint32_t tickstart = 0u;
tickstart = g_Tick;
while ((g_Tick - tickstart) < Delay) /* wait */;
}
stm32f10x_it.c:
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
g_Tick++; // 1ms++
}
4> 思考:无符号数 0 - 255 = ?
unsigned char a = 0;
unsigned char b = 255;
unsigned char c = 0;
c = a - b;
// 求c等于多少
解:
c = a - b; 可以写为 c = a + ( -b )
求-b, 负数是以补码形式存放的,
255 = 1111 1111,
所以255反码 = 0000 0000,
255补码等于反码+1,等于 0000 0001;
所以c = (0 - 255)
= (0000 0000 + 0000 0001) = 1;
那么 无符号数 1 - 255呢
1 - 255 = 0000 0001 + 0000 0001 = 2;
while ((g_Tick - tickstart) < Delay) /* wait */;
这句就利用了无符号数的减法,差点把我搞懵
相关资料
《ARM Cortex-M3 与 CortexM4权威指南》