帮我用标注库函数写个一个能用于STM32f103c8t6芯片的程序要求:具体的功能是两个按键1和2,当按下1后,触发外部中断0,定时器3延时1s,用for循环去加达到10s的效果,10s之后报警。当2按下后,触发外部中断1,终止定时器3的工作并且清除报警程序
时间: 2024-06-08 19:11:05 浏览: 55
STM32F103C8T6例程.zip_STM32F103C8T6 AD_courtwai_exclaimedty8_stm32
5星 · 资源好评率100%
好的,根据您的需求,我为您编写了以下代码:
```C
#include "stm32f10x.h"
int main(void)
{
// 初始化GPIOA、GPIOB、NVIC、EXTI、TIM3
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
EXTI_InitStructure.EXTI_Line = EXTI_Line0 | EXTI_Line1;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 19999; // 定时器3的周期为2秒
TIM_TimeBaseStructure.TIM_Prescaler = 7199; // 定时器3的分频系数为7200
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
while (1) {}
}
void EXTI0_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line0) != RESET)
{
TIM_Cmd(TIM3, ENABLE); // 开启定时器3
GPIO_WriteBit(GPIOB, GPIO_Pin_6, Bit_RESET); // 报警灯熄灭
for (int i = 0; i < 10; i++)
{
while (TIM_GetFlagStatus(TIM3, TIM_FLAG_Update) == RESET);
TIM_ClearFlag(TIM3, TIM_FLAG_Update);
}
GPIO_WriteBit(GPIOB, GPIO_Pin_6, Bit_SET); // 报警灯亮起
while (1) {} // 死循环等待复位
}
}
void EXTI1_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line1) != RESET)
{
TIM_Cmd(TIM3, DISABLE); // 关闭定时器3
GPIO_WriteBit(GPIOB, GPIO_Pin_6, Bit_RESET); // 报警灯熄灭
EXTI_ClearITPendingBit(EXTI_Line1); // 清除中断标志位
}
}
```
这段代码使用了外部中断0和1来处理按键1和按键2的操作,定时器3用于实现延时功能。其中:
- 当按键1按下时,会触发外部中断0,并且开启定时器3,然后使用for循环加延时实现10秒的延时,最后点亮LED报警灯并进入死循环等待复位。
- 当按键2按下时,会触发外部中断1,然后关闭定时器3和LED报警灯,并清除中断标志位。
注意:本代码只是一个简单的示例,如果您要在实际项目中使用,还需要根据具体情况进行修改和完善。
阅读全文