下面是一个使用定时器、预定标器、外部和内部中断的代码示例,实现按一次按钮时,内置LED闪烁1.5秒,再次按下按钮时熄灭。请根据具体硬件平台和需求进行适当修改。
”`cpp
#include
// 定义按键引脚 #define BUTTON_PIN GPIO_Pin_0 #define BUTTON_PORT GPIOA
// 定义LED引脚 #define LED_PIN GPIO_Pin_13 #define LED_PORT GPIOD
void TIM2_Init(void) {
// 启用时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
// 设置计数周期为1ms(假设使用的系统时钟频率为84MHz)
uint16_t prescaler = 84 - 1;
uint16_t period = 1000 - 1;
// 初始化TIM2结构体
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Prescaler = prescaler;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = period;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置NVIC中断优先级(可选)
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01; // 中断优先级设置为较低的值
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// 启用更新中断
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
// 启动定时器
TIM_Cmd(TIM2, ENABLE);
}
void GPIO_Init(void) {
// 启用GPIOA和GPIOD的时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOD, ENABLE);
// 配置按键引脚为输入模式(上拉)
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(BUTTON_PORT, &GPIO_InitStructure);
// 配置LED引脚为输出模式
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
int main(void) {
// 初始化定时器和GPIO引脚
TIM2_Init();
GPIO_Init();
while (1) {
// 主循环处理其他任务...
}
}
void TIM2_IRQHandler(void) {
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) {
// 清除中断标志位
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
static uint8_t led_status = 0; // LED状态,0表示熄灭,1表示亮起
if (led_status == 1) { // 如果LED已经亮起,则需要熄灭
GPIO_SetBits(LED_PORT, LED_PIN); // 熄灭LED
led_status = 0;
} else { // 如果LED已经熄灭,则需要亮起
GPIO_ResetBits(LED_PORT, LED_PIN); // 点亮LED
led_status = 1;
}
}
}
”`
内容由零声教学AI助手提供,问题来源于学员提问




