STM32F103实现0.01秒倒计时秒表的程序
时间: 2023-11-10 17:06:20 浏览: 106
好的,下面是一个 STM32F103 实现 0.01 秒倒计时秒表的程序实现:
```c
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_tim.h"
#include "misc.h"
// 定义计数器变量和状态变量
volatile uint32_t TimeCounter = 0;
volatile uint8_t TimingFlag = 0;
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
if (TimingFlag == 1)
{
TimeCounter++;
}
}
}
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 1ms 中断
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM2, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置 PA0 为输入模式(按键)
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置 PA1 为输出模式(LED)
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void Timing_Start(void)
{
TimeCounter = 0;
TimingFlag = 1;
GPIO_SetBits(GPIOA, GPIO_Pin_1); // 点亮 LED
}
void Timing_Stop(void)
{
TimingFlag = 0;
GPIO_ResetBits(GPIOA, GPIO_Pin_1); // 熄灭 LED
}
int main(void)
{
// 初始化时钟和 GPIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_Configuration();
// 初始化定时器 TIM2
TIM2_Configuration();
while (1)
{
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == RESET)
{
// 按下按键,开始计时
Timing_Start();
while (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == RESET) {} // 等待按键释放
Timing_Stop();
// 显示计时结果
printf("%d.%02d seconds\r\n", TimeCounter / 100, TimeCounter % 100);
}
}
}
```
程序的原理是:通过定时器 TIM2 来实现 1ms 中断一次,每次中断时计数器 TimeCounter 加一,当按下按键时开始计时,按键释放时停止计时并显示结果。其中,计时器的计数单位为 0.01 秒,因此最大计时时间为 99.99 秒。
需要注意的是,使用 printf 函数需要先初始化串口通信,否则无法正常输出结果。另外,该程序只是一个简单的示例,实际应用中可能需要根据具体需求进行修改。
阅读全文