为了可控制报警声音时间的长短,我利用了定时器2的功能。具体做法是先配置定时器2计时为一秒,然后将设定的时间长度给一个变量,在定时器中断处理中对这个变量进行减1操作,当变量等于0时,关闭报警声音。
下面是定时器配置的代码:
- void timer_config(void)
- {
- /* -----------------------------------------------------------------------
- TIMER2CLK is 100KHz定时器2 CLK为100kHz
- TIMER2 channel0 duty cycle = (25000/ 50000)* 100 = 50%
- ----------------------------------------------------------------------- */
- timer_oc_parameter_struct timer_ocintpara; //定义数据结构
- timer_parameter_struct timer_initpara;
- rcu_periph_clock_enable(RCU_TIMER2); //开启时钟
- timer_deinit(TIMER2); //指定定时器
- /* TIMER configuration 定时器配置*/
- timer_initpara.prescaler = 719;
- timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
- timer_initpara.counterdirection = TIMER_COUNTER_UP;
- timer_initpara.period = 99999; //定时1000毫秒
- timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
- timer_initpara.repetitioncounter = 0;
- timer_init(TIMER2,&timer_initpara);
- timer_interrupt_enable(TIMER2, TIMER_INT_UP); //Enable TIMER2
- nvic_irq_enable(TIMER2_IRQn, 0); //Set priority to 0(0-2)
- /* auto-reload preload enable 自动重新加载预加载启用*/
- timer_auto_reload_shadow_enable(TIMER2);
- /* auto-reload preload enable */
- timer_enable(TIMER2);
- }
下面是定时器中断处理的代码:
- void TIMER2_IRQHandler(void)
- {
- if(RESET != timer_interrupt_flag_get(TIMER2, TIMER_INT_FLAG_UP))
- {
- if(time>0)
- time--;
- }
- timer_interrupt_flag_clear(TIMER2, TIMER_INT_FLAG_UP);
- }
在外部中断处理程序中设置报警模式,在主循环中获取报警标志时开启音乐IC的电源,并在到时后关闭音乐IC的电源:
- if(mode==110){
- alar++; //警情计数
- LCD_line_clear(3);
- LCD_line_clear(4);
- LCD_write_string(0,3,(uint8_t *) "报警记录");
- LCD_write_value(53,4,3,0,1,alar);
-
- date_write(); //添加警情记录
- LCD_write_value(18,2,3,0,1,recn);
- LCD_write_value(60,2,3,0,1,addr);
- mode = 0;
- if(ala8==4){ //启动音乐
- gpio_bit_set(GPIOA, GPIO_PIN_2);//发出启动信号
- delay_1ms(100);
- gpio_bit_reset(GPIOA, GPIO_PIN_2);//撤消启动信号
- }
- else{
- if(ala8>0) //指定报警声
- alarm_type(ala8-1);
- time = ala9; //报警声音时长
- gpio_bit_reset(GPIOA, GPIO_PIN_3);//启动报警声
- gd_eval_led_off(LED2);
- }
- }
- if(time==0){
- gpio_bit_set(GPIOA, GPIO_PIN_3); //关闭报警声
- gd_eval_led_off(LED2);
- }
- else
- LCD_write_value(53,3,3,0,0,time); //显示剩余时间
经测试,程序代码基本上达到要求,仅仅是我配置定时器时间为一秒,而实际测试发现低于一秒,大约为0.5秒左右,尚未查出原因。