由定时器产生PWM信号,可手动按键调节PWM的占空比,按键由外部中断实现
#include <reg51.h>
#include <intrins.h>
#define CYCLE 6000 //周期6000 * 1us = 6ms
#define SCALE (CYCLE / 100) //比例 1%
#define ONE 0x10
#define TWO 0x01
#define THREE 0x40
#define FOUR 0x04
typedef unsigned char uchar;
typedef unsigned int uint;
sbit pwm_out = P2^6; //PWM信号输出
uchar key_value = 0; //按键值
uchar const cycle = 100;
uchar scale = 50;
uchar num = 0;
/*************************************************************
*ms延时函数
*************************************************************/
void delay_ms(uchar n)
{
uchar j = 0;
for(; n>0; n--)
for(; j<125; j++);
}
/*************************************************************
*定时器初始化
*************************************************************/
void Init_Timer()
{
TMOD = 0x01;
TH0 = (65536 - SCALE)/256; //定时器0初值
TL0 = (65536 - SCALE)%256;
}
void main()
{
Init_Timer();
ET0 = 1; //开定时器中断
// IE0 = 1;
IT0 = 0;
EX0 = 1;
EA = 1; //开总中断
pwm_out = 1;
TR0 = 1; //定时器0开始计数
while(1)
{
switch(~key_value & 0x55)
{
case ONE :
scale = 25;
break;
case TWO :
scale = 50;
break;
case THREE :
scale = 75;
break;
case FOUR :
scale = 99;
break;
default :
break;
}
key_value = 0;
}
}
/*************************************************************
*外部中断0(按键)
*************************************************************/
void Int0_isr() interrupt 0
{
key_value = P1;
delay_ms(1);
if(key_value != P1)
key_value = 0;
}
/*************************************************************
*定时器中断0(波形发生)
*************************************************************/
void Timer0_isr() interrupt 1
{
TH0 = (65536 - SCALE)/256;
TL0 = (65536 - SCALE)%256;
num++;
if(num == scale)
pwm_out = 0;
if(num == cycle)
{
num = 0;
pwm_out = 1;
}
}