STM32F030控制蜂鸣器
2019-05-23 来源:eefocus
(1)main()函数中:
int BeeTime=0;
int soundSta=0;
void main()
{
TIM2_Init();
soundBee(1);//长响一声
soundBee(0);//短响一声
}
void TIM2_Init()
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = (TIM_CLK / 200000) - 1;
TIM_TimeBaseStructure.TIM_Prescaler = 1999;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_SetAutoreload(TIM2, ((TIM_CLK / 200000) - 1));
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); // 打开捕获比较中断 TIM_IT_Update
TIM_Cmd(TIM2, ENABLE); //开启时钟
}
/***********************
功能:蜂鸣器启动
sta:1为成功,0为失败
***********************/
void soundBee(int sta)
{
DOOR_PWR1(1);
if(sta==1)
{
soundSta=0;
BeeTime = 80;
}else{
soundSta=1;
BeeTime = 20;
}
}
(2)hardware_conf.h函数中:
#define DOOR_PWR1(tmp) GPIOA->ODR=tmp?(GPIOA->ODR|1<<1):(GPIOA->ODR&(~(1<<1))) //蜂鸣器
(3)stm32f10x_it.c函数中:
extern int BeeTime;
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
if(BeeTime<0)
{
BeeTime++;
if(BeeTime==0)
{
DOOR_PWR1(1);
BeeTime=20;
}
}
if(BeeTime>0||soundSta==2)
{
if(BeeTime>0) BeeTime--;
if(BeeTime==0)
{
if(soundSta==0)
{
DOOR_PWR1(0);
}
else if(soundSta==1)
{
DOOR_PWR1(0);
BeeTime=-10;
soundSta=2;
}
else
{
DOOR_PWR1(0);
soundSta=0;
}
}
}
}
else if (TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_CC1);
}
}
上一篇:STM32F030控制LED
下一篇:STM32延时函数的四种方法