From: http://caiyh.blog.163.com/blog/static/18670512220115152564613/
// ================================================ ===
// Name: Main. c
// Desc: tq2440pwm Test Procedure
// Set the frequency of the buzzer to tout for gpb0.
// Turn off the buzzer when the output is low
// Change the frequency by changing the clock frequency
// ================================================ ===
/* The header file contains */
# Include "def. H"
# Include "option. H"
# Include "2440addr. H"
Void delay_ms (u32 time)
{
// Timer 3 input clock frequency = pclk/{pre-division value + 1}/{division value}
// {Pre-division value} = 0 ~ 255
// {Frequency division value} = 2, 4, 8, 16
// Pclk: 50 MHz clock frequency: 6250 kHz scheduled 1 ms count: clock frequency * Scheduled time-1
U32 val = 50000000/(4*2)/1000-1;
Rt1_0 = (rt1_0 &~ (0xff <8) | (3 <8); // prescaler1 = 3 + 1
Rtcfg1 = (rtcfg1 &~ (0xf <12) | (0 <12); // MUX = 1/2
Rtcnint32 = val;
Rtcmpb3 = rtcnint32/2; // duty cycle: 50%
Rtcon = (rtcon &~ (0xf <16) | (0xb <16); // auto-Reload, disguised, manual update, start timer 3
Rtcon = (rtcon &~ (0x2 <16); // Manual Update prohibited
While (Time --) // wait for a scheduled end
{
While (rtcnto3 >=( Val> 1 ));
While (rtcnto3 <(Val> 1 ));
}
}
Void buzzer_freq_set (u32 freq)
{
// Timer 1 input clock frequency = pclk/{pre-division value + 1}/{division value}
// {Pre-division value} = 0 ~ 255
// {Frequency division value} = 2, 4, 8, 16
// Pclk: 50 MHz clock frequency: 6250 kHz scheduled 1 ms count: clock frequency * Scheduled time-1
// 50000000/(16*8) = 390625
Rgpbcon = (rgpbcon &~ 0x3) | 0x2; // set the gpb0 port to tout PWM 0b10
Rt1_0 = (rt1_0 &~ 0xff) | 15; // prescaler0 = 15 + 1
Rtcfg1 = (rtcfg1 &~ 0xf) | 0x2; // MUX = 1/8 0b0010
Rtcntb0 = 50000000/(16*8)/freq;
Rtcmpb0 = rtcntb0/2; // duty cycle: 50%
Rtcon = (rtcon &~ 0x1f) | 0xb; // disable dead zone, automatic heavy load, disguised form, manual update, start timer 3
Rtcon = (rtcon &~ 0x2); // Manual Update prohibited
}
Void buzzer_stop (void)
{
Rgpbcon = (rgpbcon &~ 0x3) | 0x1; // set the gpb0 port to output 0b01
Rgpbdat = (rgpbdat &~ 0x1); // gpb0 port output low-level turn off the buzzer
}
Void BEEP (u32 freq, u32 time)
{
Buzzer_freq_set (freq );
Delay_ms (time );
Buzzer_stop ();
}
Void main (void)
{
Beep (20000,100 );
While (1 );
}