1、#include “reg52.h“unsigned char count; /0.5ms 次数标识sbit pwm =P27 ; /PWM 信号输出sbit jia =P24; /角度增加按键检测 IO 口sbit jan =P25; /角度减少按键检测 IO 口unsigned char jd=5; /角度标识void delay(unsigned char i)/延时unsigned char j,k;for(j=i;j0;j-)for(k=125;k0;k-);void Time0_Init() /定时器初始化TMOD = 0x01; /定时器 0 工作在方式 1 IE = 0x82;
2、TH0 = 0xfe;TL0 = 0x33; /11.0592MZ 晶振,0.5msTR0=1; /定时器开始void Time0_Int() interrupt 1 /中断程序TH0 = 0xfe; /重新赋值TL0 = 0x33;if(count jd) /判断 0.5ms 次数是否小于角度标识pwm=1; /确实小于,PWM 输出高电平elsepwm=0; /大于则输出低电平count=(count+1); /0.5ms 次数加 1count=count%40; /次数始终保持为 40 即保持周期为 20msvoid keyscan() /按键扫描 if(jia=0) /角度增加按键是否按下delay(10); /按下延时,消抖if(jia=0) /确实按下jd+; /角度标识加 1count=0; /按键按下 则 20ms 周期从新开始if(jd=6)jd=5; /已经是 180 度,则保持while(jia=0); /等待按键放开if(jan=0) /角度减小按键是否按下delay(10);if(jan=0)jd-; /角度标识减 1count=0;if(jd=0)jd=1; /已经是 0 度,则保持while(jan=0);void main()count=0; Time0_Init(); while(1)keyscan(); /按键扫描