使用STC89C52RC输出PWM调节LED亮度
时间: 2024-02-21 11:37:51 浏览: 188
以下是STC89C52RC控制PWM调节LED亮度的代码:
#include <reg52.h>
#define FOSC 11059200L //晶振频率
#define T1MS (FOSC/12/1000) //1ms定时器值
sbit LED = P1^0; //LED接口
void Timer0Init()
{
TMOD |= 0x01; //选择为定时器0模式,工作方式1,仅用TR0打开启动。
TH0 = 0xFC; //给定时器赋初值,定时1ms
TL0 = 0x67;
ET0 = 1; //打开定时器0中断允许
EA = 1; //打开总中断允许
TR0 = 1; //打开定时器
}
void main()
{
Timer0Init();
while(1)
{
LED = ~LED; //LED翻转
delay_ms(500); //延时500ms
}
}
void Timer0() interrupt 1
{
static unsigned char cnt = 0;
static unsigned char pwm = 0;
TH0 = 0xFC; //给定时器赋初值,定时1ms
TL0 = 0x67;
cnt++; //计数器自增
if(cnt == 100) //计数值为100时重置为0
{
cnt = 0;
}
if(cnt < pwm) //当计数值小于占空比pwm时,LED亮
{
LED = 0;
}
else //否则LED灭
{
LED = 1;
}
}
void delay_ms(unsigned int ms)
{
unsigned int i,j;
for(i=0;i<ms;i++)
{
for(j=0;j<T1MS;j++);
}
}
阅读全文