PWM脉冲调制信号的发生与控制
1、代码思路:
(1)我们可以利用定时器规定周期为10ms(100HZ),通过调节高电平时间来产生想要的PWM波,不同的亮度对应着不同占空比。
(2)首先我们先通过定时器产生四种不同的亮度,然后编写可以转换四种不同状态的按键,走后把他们整合起来
#include <REGX52.H>
sbit L1 = P0^0;
sbit S7 = P3^0;
unsigned char count = 0;
unsigned char pwm_duty = 0;
void Delay(unsigned int t) {
while(t--);
}
void _74HC138(unsigned char n) {
switch(n) {
case 4: P2 = (P2 & 0x1f) | 0x80;
break;
case 5: P2 = (P2 & 0x1f) | 0xa0;
break;
case 6: P2 = (P2 & 0x1f) | 0xc0;
break;
case 7: P2 = (P2 & 0x1f) | 0xe0;
break;
}
}
void sysInit(void) {
_74HC138(5);
P0 = 0x00;
_74HC138(4);
P0 = 0xFF;
}
void Timer0Init(void) {
TMOD = 0x02;
// 100us
TH0 = 256 - 100;
TL0 = 256 - 100;
EA = 1;
ET0 = 1;
// TR0 = 1;
}
unsigned char state = 0;
void Scan_Key(void) {
if(S7 == 0) {
Delay(300);
if(S7 == 0) {
switch(state) {
case 0:
TR0 = 1; // 开启定时器
L1 = 0;
pwm_duty = 10;
state = 1;
break;
case 1:
pwm_duty = 50;
state = 2;
break;
case 2:
pwm_duty = 90;
state = 3;
break;
case 3:
L1 = 1;
state = 0;
TR0 = 0;
break;
}
while(S7 == 0);
}
}
}
void Timer0Rountine () interrupt 1 {
count++;
// 20 20
if(count == pwm_duty) {
// 即对占空比的切换
L1 = 1; // count == pwm_duty 由低电平置为高电平
}else if(count == 100) {
L1 = 0;
count= 0;
}
}
void main(void) {
sysInit();
_74HC138(4);
// 默认关灯
L1 = 1;
Timer0Init();
while(1) {
Scan_Key();
}
}
标签:case,脉宽调制,10,void,P2,duty,break,state,PWM
From: https://www.cnblogs.com/bky111/p/17744755.html