STM32F407倒计时秒表设计的程序
时间: 2023-11-10 10:06:19 浏览: 61
以下是一个简单的倒计时和秒表程序的代码示例,仅供参考:
```c
#include "stm32f4xx.h"
#define LED_GPIO_PORT GPIOA
#define LED_GPIO_PIN GPIO_Pin_5
void Delay(__IO uint32_t nCount);
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure);
}
void TIM2_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 999; //1ms
TIM_TimeBaseStructure.TIM_Prescaler = 8399; //84MHz/8400=10kHz
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
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_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
void TIM2_IRQHandler(void)
{
static uint16_t ms_count = 0;
static uint16_t s_count = 0;
static uint16_t min_count = 0;
static uint16_t sec_count = 60;
static uint8_t mode = 0; //0:倒计时 1:秒表
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
ms_count++;
if (ms_count >= 10)
{
ms_count = 0;
if (mode == 0)
{
if (sec_count == 0)
{
if (min_count == 0)
{
GPIO_SetBits(LED_GPIO_PORT, LED_GPIO_PIN);
}
else
{
min_count--;
sec_count = 59;
}
}
else
{
sec_count--;
}
}
else
{
s_count++;
if (s_count >= 60)
{
s_count = 0;
min_count++;
}
}
}
}
}
int main(void)
{
LED_Init();
TIM2_Config();
while (1)
{
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == RESET)
{
Delay(50);
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == RESET)
{
GPIO_ResetBits(LED_GPIO_PORT, LED_GPIO_PIN);
sec_count = 5;
min_count = 0;
mode = 0;
}
}
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == RESET)
{
Delay(50);
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == RESET)
{
mode = 1;
s_count = 0;
min_count = 0;
sec_count = 0;
}
}
}
}
void Delay(__IO uint32_t nCount)
{
while (nCount--);
}
```
此代码示例使用TIM2作为计时器,1ms中断一次。在中断服务程序中,分别处理倒计时和秒表功能。在main函数中,使用GPIO口检测按键状态,来控制计时器的启动、停止和复位操作。注意,此代码仅为示例,实际使用时需要根据具体需求进行修改。
阅读全文