回答
里有个PWM控制LED给你参考下使用两个定时器Timer0和Timer1中断实现PWM控制LED明暗效果。其中Timer0工作在方式1用于脉冲宽定时,Timer1工作于方式2用于占空比的定时。在这个程序里,脉冲宽是个固定的值,通过递增、递减改变占空比,从而实现LED明暗效果。如果将LED换作蜂鸣器,通过改变脉冲宽可改变音调。/**************************************///文件名:main.c//作 者:jammy-lee//日 期:2009-3-18//功 能:使用两个定时器模拟PWM/**************************************///头文件#include//宏定义typedef unsigned char uint8;typedef unsigned int uint16;typedef long unsigned int uint32;uint16 time0;uint16 PULSE_WIDTH = 0x300; //脉冲宽uint8 DUTY_CYCLE = PULSE_WIDTH*1/5;//占空比//延时子程序void delayuint8 ms{uint8 i;whilems--{fori=0;i<120;i++;}}//定时器0,控制低电平void Timer0 interrupt 1{TR1 = 0; //关闭定时器1time0 = 0xFFFF - PULSE_WIDTH; //定时器0初始值TL0 = uint8time0;TH0 = time0 >> 8;TH1 = DUTY_CYCLE;TR1 = 1;P0 = 0x00; //打开定时器1}//定时器1.控制高电平void Timer1 interrupt 3{TR1 = 0; //关闭定时器1P0 = 0xFF;}//主函数int mainvoid{TMOD = 0x21; //定时器1:工作方式1,定时器0:工作方式2time0 = 0xFFFF - PULSE_WIDTH; //定时器0初始值TL0 = uint8time0;TH0 = time0 >> 8;TL1 = DUTY_CYCLE;TH1 = DUTY_CYCLE;EA = 1; //允许全局中断ET0 = 1; //允许定时器0中断ET1 = 1; //允许定时器1中断TR0 = 1;//主循环while1{do{ifDUTY_CYCLE != PULSE_WIDTH*1/4{DUTY_CYCLE++;delay5;}else break;}while1;do{ifDUTY_CYCLE != 0x01{DUTY_CYCLE--;delay5;}else break;}while1;}}