记录高级定时器TIM1的配置过程
学习计数模式
通过蜂鸣器鸣叫展示代码
有源蜂鸣器:内部自带震荡体,通电就响
无源蜂鸣器:需要输出PWM
之前Delay初始化的时候,晶振被8分频了,变成9MHz的频率了吗,why?
为啥要先分频呢?小声BB……
给蜂鸣器新建一个Beep.c和Beep.h
Beep.c
1. #include "Beep.h" 2. 3. void Beep_Init(void) 4. { 5. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF, ENABLE); 6. 7. GPIO_InitTypeDef GPIO_InitStructure; 8. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出 9. GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; 10. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; 11. GPIO_Init(GPIOF, &GPIO_InitStructure); 12. 13. GPIO_SetBits(GPIOF, GPIO_Pin_0); //置高,蜂鸣器不响 14. } 15. 16. void TIM_UserConfig (uint16_t Period, uint16_t Prescaler) 17. { 18. RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); 19. 20. TIM_TimeBaseInitTypeDef TIM_InitStructure; 21. TIM_InitStructure.TIM_Period = Period; 22. TIM_InitStructure.TIM_Prescaler = Prescaler; 23. TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //不分割时钟 24. TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数 25. TIM_InitStructure.TIM_RepetitionCounter = 0; //重复计数次数,就是计数溢出即申请中断 26. TIM_TimeBaseInit(TIM1, &TIM_InitStructure); //初始化定时器 27. 28. TIM_ClearITPendingBit(TIM1, TIM_IT_Update);//清除 TIM1 的中断待处理位,先清除,再开启中断 29. TIM_ITConfig(TIM1, TIM_IT_Update | TIM_IT_Trigger, ENABLE);//开启计数器中断(定时器1,计数|触发中断源,使能) 30. TIM_Cmd(TIM1, ENABLE);//使能计数器 31. 32. NVIC_InitTypeDef NVIC_InitStructure; 33. NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); //设置中断分组0,主优先级0,抢占优先级3 34. NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn;//中断入口 35. NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; 36. NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; 37. NVIC_Init(&NVIC_InitStructure); 38. 39. } 40. 41. void TIM1_UP_IRQHandler(void) 42. { 43. //获取中断状态 44. if( TIM_GetITStatus(TIM1, TIM_IT_Update) != RESET ) //只要不等于0,就代表进来中断了 45. { 46. GPIO_WriteBit(GPIOF, GPIO_Pin_0, (BitAction)(!GPIO_ReadOutputDataBit(GPIOF, GPIO_Pin_0))); 47. //进入中断,先把这个TIM_IT_Update清零 48. TIM_ClearITPendingBit(TIM1, TIM_IT_Update); 49. } 50. } 51.
Beep.h
1. #ifndef __BEEP_H__ 2. #define __BEEP_H__ 3. 4. #include "stm32f10x.h" // Device header 5. 6. void Beep_Init(void); 7. void TIM_UserConfig (uint16_t Period, uint16_t Prescaler); 8. 9. #endif 10.
main.c
1. #include "stm32f10x.h" // Device header 2. #include "Delay.h" 3. #include "LED.h" 4. #include "Beep.h" 5. 6. int main(void) 7. { 8. Delay_Init(72); 9. LED_Init(); 10. Beep_Init(); 11. TIM_UserConfig (1000-1, 7200-1); 12. /* 72M 13. 如果7200分频,7200 0000 /7200 = 10000,就是1s计数10000 14. 1ms计数10个 100us计数1个 15. 16. 写1000,就是计数100ms */ 17. 18. while(1) 19. { 20. } 21. }
蜂鸣器模块接在GPIOF的PIN0上,100ms电平反转一次,0.2s一个周期,鸣叫一次,50%的占空比
这里可以用逻辑分析仪抓取一下PF0引脚的波形……