Date: 8-Nov-2011
1.硬件原理图
2. Buzzer寄存器设置
static void Buzzer_Port_Init(void){
//设置GPB0为PWM output
rGPBCON &= ~(0x3);
rGPBCON |= 0x2; //GPB0=TOUT0
//设置GPB0 Pull up function disabled
rGPBUP |= 0x1; //Pull up function disabled
}
3.TIMER0 控制框图
4.TIMER0寄存器设置
static void TIMER0_Port_Init(void){
//设置预分频器
rTCFG0 &= ~(0xff<<0);
rTCFG0 |= (0x3<<0); //prescaler 3+1
//设置分频比
rTCFG1 &= ~(0xf<<0);
rTCFG1 |= (0<<0); //mux = 1/2
//设置控制方式:Disable dead zone、Auto reload、Inverter off、Update TCNTB0 & TCMPB0、Stop
rTCON &=(0x1f<<0) ;
rTCON |= (0xa<<0); //01010
}
5.Auto-reload方式分析
当计数器TCNT减为0时,Auto-reload自动将计数缓冲器TCNTBn的数值拷贝到计数器TCNTn中。如果Auto-reload功能未使能,当TCNTn减为0时,TCNTn将停止计数。
6.代码分析 TIMER.c
#include "2440addr.h"
#include "option.h" //PCLK
#include "UART.h" //UART0_Printf()
//Buzzer寄存器设置
static void Buzzer_Port_Init(void){
rGPBCON &= ~(0x3);
rGPBCON |= 0x2; //GPB0=TOUT0
rGPBUP |= 0x1; //Pull up Function disabled
}
//TIMER0寄存器设置
static void TIMER0_Port_Init(void){
rTCFG0 &= ~(0xff<<0);
rTCFG0 |= (0x3<<0); //prescaler 3+1
rTCFG1 &= ~(0xf<<0);
rTCFG1 |= (0<<0); //mux = 1/2
rTCON &= ~(0x1f<<0);
rTCON |= (0xa<<0); //01010
}
//PWM输出频率设置
static void Buzzer_Frequency_Set(int Freq){
//定时时间为 (PCLK>>3)/(Freq)/(PCLK/8) = 1/(Freq)s
U32 val = (PCLK>>3)/(Freq+1000) - 1;
rTCNTB0 = val;
//PWM占空比
rTCMPB0 = val>>1; //50%方波输出
}
//启动TIMER0
static void TIMER0_Start(void){
rTCON |= (0x1<<0); //Start Timer0
rTCON &= ~(2<<0);
}
//停止TIMER0并关闭Buzzer
static void TIMER0_Stop(void){
rTCON &=(0xfffe<<0); //Stop Timer0
//关闭Buzzer
rGPBCON &= ~(0x3);
rGPBCON |= 0x1; //GPB0=OUTPUT
rGPBDAT &= ~(0x1); //Shut Buzzer
}
void Buzzer_PWM_Test(void){
U8 TmpChar;
int TmpFreq=1000;
Buzzer_Port_Init(); //Buzzer端口寄存器设置
TIMER0_Port_Init(); //TIMER0端口寄存器设置
Buzzer_Frequency_Set(TmpFreq); //PWM输出频率设置
TIMER0_Start(); //启动TIMER0
UART0_Printf("Press +/- to add/dec Frequency of Buzzer and ESC to exit\n");
//根据按键增大或减小PWM输出频率,或退出
while((TmpChar=UART0_GetKey())!=ESC_KEY)
{
if(TmpChar=='+')
{
if(TmpFreq<=2000)
Buzzer_Frequency_Set(TmpFreq+=100);
}
else
{
if(TmpChar=='-')
{
if(TmpFreq>=1000)
Buzzer_Frequency_Set(TmpFreq-=100);
}
}
}
TIMER0_Stop(); //停止TIMER0
}
7. 测试程序及结果
#include "UART.h"
#include "TIMER.h"
int Main(void)
{
UART0_Port_Init(115200); //UART0初始化
Buzzer_PWM_Test(); //PWM输出驱动蜂鸣器
while(1){
;
}
return 0;
}
按+/-增大/减小PWM的输出频率,蜂鸣器发出的声音也随之改变。