📄 pwm_t2.c
字号:
/*
File: pwm_t2.c
说明: PWM波形输出,定时器实现
Author:wolfe
Data: 2008.10
*/
#include "at89x52.h"
#include "ES51_II.h"
#include "es51_ii_lib.h"
// 输出到P1.0,直接观察LED1亮度粗略地判断.
sbit PWM_OUT = P1^0;
// 全局变量
bit bPWMFLAG;
unsigned int Revlue;
unsigned int Positive;
unsigned int Negative;
// timer2初始化程序
void InitTimer2(unsigned int value)
{
RCAP2H = value>>8;
RCAP2L = value;
T2MOD = 0x00; // 禁止定时时钟从P1.0输出.
// 计数方式与P1.1无关,采用加计数方式.
TH2 = RCAP2H;
TL2 = RCAP2L;
T2CON = 0x00; // 0000,0000 计数,自动重装方式.
}
// timer2中断程序
void T2OverflowINT(void) interrupt 5 using 0
{
PWM_OUT = !PWM_OUT;
TF2 = 0; //清零中断标志
RCAP2H = Revlue>>8; //重写RCAP寄存器
RCAP2L = Revlue;
if(0 == bPWMFLAG) //设置下一次RCAP2H的值
Revlue = Positive;
else
Revlue = Negative;
bPWMFLAG = !bPWMFLAG;
}
// 设置占空比(频率为1KHZ)
// 设置占空比范围:5.0%-95.0%;精确到小数后一位,
// 矩形波中占空比是指正脉冲与整个周期的比值.
void SetDutyCycle(float duty)
{
bPWMFLAG = 0;
PWM_OUT = 0; // PWM输出引脚初始状态为0
Positive = 0xffff - 10*duty;
Negative = 0xffff - 10*(100-duty);
InitTimer2(Negative);
}
// 启动PWM输出
#define ENPWMOUT() TR2=1
// 停止PWM输出
#define DISPWMOUT() TR2=0
void main()
{
EA = 1; // 开总中断
ET2 = 1; // 允许T2溢出中断
// 修改传递的参数,观察LED1灯的亮度.
SetDutyCycle(53.4); // 设置占空比为53.4%
ENPWMOUT(); // 允许PWM输出
while(1);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -