#include<reg51.h>
#define adc_port P1
sbit pwm_pin=P3^4;
sbit rd=P3^0;
sbit wr=P3^1;
sbit intr=P3^2;
unsigned char pwm_width;
unsigned int adc_value;
int pwm_setup();
unsigned int adc_init();
void delay(unsigned int);
void main()
{
while(1)
{
adc_init();
pwm_setup();
}
}
unsigned int adc_init() /*ADC initialization and read values from 0-255*/
{
adc_port=0xFF;
intr=1;
rd=0;
wr=0;
delay(2);
wr=1;
while(intr==1)
{
rd=0;
adc_value=adc_port;
rd=1;
}
return(adc_value);
}
/*pwm setup with duty cycle controlled by adc_value (range 0-255)*/
int pwm_setup()
{
TMOD=0x01;
pwm_width=adc_value;
EA=1;
ET0=1;
TR0=1;
return(pwm_width);
}
void delay(unsigned int count) /*Delay function*/
{
int i,j;
for(i=0;i<=count;i++)
for(j=0;j<=1275;j++);
}
void timer0() interrupt 1 /*Tomer0 ISR*/
{
TR0=0;
if(pwm_pin==1)
{
pwm_pin=0;
TH0=pwm_width;
TF0=0;
return;
}
else
{
pwm_pin=1;
TH0=255-pwm_width;
TF0=0;
return;
}
}