急求用51单片机(stc89c52)利用pwm控制led灯光亮度变化的c程序,电路图如下:

2024-11-29 07:52:15
推荐回答(1个)
回答1:

#include
#define uint unsigned int
#define uchar unsigned char
uchar count ,z;
sbit key_1 = P3^7;
sbit key_2 = P3^6;
sbit PWM = P2^0;
void key_control();
void init ();
void create_PWM(uchar);
void delay(uint);
void main ()
{
init ();
while(1);
{
key_control();
create_PWM(count);
}
}
void delay(uint z)
{
uint x,y;
for(x = z;x>0;x--)
for(y = 110;y>0;y--);
}

void init()
{
TMOD = 0x10;
TH1 = (65536-4608)/256;//50sm
TL1 = (65536-4608)%256;
TR1 = 1;
}
void create_PWM(uchar count)
{
static i;
if(TF1 == 1)
{
TF1 = 0;
TH1 = (65536-4608)/256;//50sm
TL1 = (65536-4608)%256;
i++;
if(i == 100) i=0;
if(i <= count) PWM = 1;
else PWM = 0;
}
}
void key_control()
{

if(key_1 ==0)
{
delay(10);
if(key_1 == 0)
{
count+= 5;
if(count >= 100)count = 0;
}
}
if(key_2 ==0)
{
delay(10);
if(key_2 ==0)
{
count-= 5;
if(count <= 0)count =100;
}
}
}