📄 pwm.c
字号:
#include <string.h>
#include "..\inc\44b.h"
#include "..\inc\44blib.h"
#include "..\inc\timer.h"
#define READ_COUNT2 (rTCNTO2 & 0xffff)
#define MaxBeepFreq 20000
#define MinBeepFreq 20
extern int Uart_GetIntNum(void);
void SetBeepPwm(unsigned short Freq, unsigned char HiRatio);
void StopBeepPwm(void);
void __irq TIMER2_int(void);
//volatile int isWdtInt;
unsigned int pwmcnt=0;
/****************************************
* PWM (BEEP) test *
****************************************/
void Test_Pwm(void)
{
int nFeq, nRatio;
sysUtilsLightLed (LED_ALL, FALSE);
Uart_Printf ("PWM Test,We use Timer2 to implement PWM.\n");
for (;;)
{
Uart_Printf("Please Input the Frequency F= (%d--%d): ", MinBeepFreq,MaxBeepFreq);
nFeq = Uart_GetIntNum1 ();
if (nFeq != 0)
{
if ((nFeq < MinBeepFreq) || (nFeq > MaxBeepFreq))
{
continue;
}
break;
}
Uart_Printf("Error Input, Please input it again.\n");
}
for (;;)
{
Uart_Printf("Please Input the ratio R= (1--99):");
nRatio = Uart_GetIntNum1 ();
if (nRatio != 0)
{
if ((nRatio < 1) || (nRatio > 99))
{
continue;
}
break;
}
Uart_Printf("Error Input, Please input it again.\n");
}
Uart_Printf("Feq=%d. Ratio=%d.\n", nFeq, nRatio);
rINTCON = 5; //irq enable, non vector mode
rINTMOD = 0; //All irq mode
rINTMSK =~(BIT_GLOBAL|BIT_TIMER2);//enable timer2 interrupt
pISR_TIMER2 = (unsigned int)TIMER2_int; //(unsigned)
rPDATE = 0x157; //Beep = 10
rPCONE = 0x596b; // tout2
rPUPE = 0xff;
SetBeepPwm (nFeq, nRatio);
while (Uart_GetKey () == 0);
StopBeepPwm();
}
void SetBeepPwm(unsigned short Freq, unsigned char HiRatio)
{
if(Freq>MaxBeepFreq)
{
Freq = MaxBeepFreq;
}
if(HiRatio>100)
{
HiRatio = 100;
}
rTCON &= 0xffff0fff; // clear manual update bit, stop Timer2
rTCFG0 &= 0xffff00ff; // set Timer 2&3 prescaler 0
rTCFG1 &= 0xfffff0ff; // set Timer 2 MUX 1/16
rTCFG1 |= 0x00000300;
rTCNTB2 = MCLK/(Freq*16); //if set inverter off, when TCNT2<=TCMP2, TOUT is high, TCNT2>TCMP2, TOUT is low
rTCMPB2 = (rTCNTB2*(100-HiRatio))/100; //if set inverter on, when TCNT2<=TCMP2, TOUT is low, TCNT2>TCMP2, TOUT is high
rTCON |= 0x00002000; // manual update
rTCON &= 0xffff0fff; // clear manal update bit
rTCON |= 0x0000d000; // auto reload, inverter on, start Timer 2
}
void StopBeepPwm(void)
{
rTCON &= ~0x1000;
rINTMSK |= (BIT_GLOBAL|BIT_TIMER2);
}
void __irq TIMER2_int(void)
{
rI_ISPC=BIT_TIMER2;
pwmcnt++;
return ;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -