用代码写一个单片机实现计时
时间: 2023-11-22 22:52:11 浏览: 37
以下是一个基于STM32单片机的计时器示例代码,可以实现以毫秒为单位的计时:
```c
#include "stm32f4xx.h"
volatile uint32_t time_ms = 0; // 计时变量,单位为毫秒
void SysTick_Handler(void)
{
time_ms++;
}
void delay_ms(uint32_t ms)
{
uint32_t start = time_ms;
while(time_ms - start < ms);
}
int main(void)
{
// 初始化系统时钟和SysTick定时器
SystemCoreClockUpdate();
SysTick_Config(SystemCoreClock / 1000);
// 设置GPIO
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
while(1)
{
GPIO_SetBits(GPIOA, GPIO_Pin_5); // 设置GPIO输出高电平
delay_ms(500); // 延时500毫秒
GPIO_ResetBits(GPIOA, GPIO_Pin_5); // 设置GPIO输出低电平
delay_ms(500); // 延时500毫秒
}
}
```
在上面的代码中,我们使用了STM32的SysTick定时器来实现计时功能。在每个毫秒的时候,SysTick_Handler()函数会被调用一次,time_ms变量会自增1。我们可以利用delay_ms()函数来实现延时功能,该函数会等待指定的毫秒数后返回。在主函数中,我们使用了一个LED来展示计时的效果:每隔500毫秒,LED会交替闪烁。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)