//脉冲周期为100HZ(10ms)
//占空比表示:高电平所占周期/总周期
#include<reg52.h>
sbit L1 = P0^0;
sbit S7 = P3^0; //模式调节
unsigned char count = 0; //计数
unsigned char PWM = 0; //脉冲宽度
unsigned char state = 0; //PWM标志位
unsigned char code SEG_code[18] =
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,
0xbf,0x7f}; //定义共阳数码管段码内容:0~F,—,.
void Init_timer0() //定时器0初始化
{
TMOD = 0x01;
TH0 = (65535 - 100) / 256; //定时100us
TL0 = (65535 - 100) % 256;
EA = 1; //打开总中断
ET0 = 1; //打开定时器0的中断
TR0 = 0; //关闭定时器0
}
void Service_timer0() interrupt 1 //中断服务函数
{
TH0 = (65535 - 100) / 256;
TL0 = (65535 - 100) % 256;
count++;
if(count == PWM) //在占空比前点亮LED
{
L1 = 1;
}
if(count == 100) //一个脉冲周期结束
{
L1 = 0;
count = 0;
}
}
void Delay_tube(unsigned int t) //数码管延时
{
while(--t);
}
void Delay_keys() //延时去抖动
{
unsigned char i = 108,j = 145;
while(--i)
{
while(--j);
}
}
void Select_HC138(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 Show_tube(unsigned char position,unsigned char value)
{
Select_HC138(6);
P0 = 0x01 << position;
Select_HC138(7);
P0 = value;
}
void Display(unsigned char num)
{
Show_tube(0,SEG_code[16]);
Delay_tube(500);
Show_tube(1,SEG_code[16]);
Delay_tube(500);
Show_tube(2,SEG_code[num]);
Delay_tube(500);
Show_tube(3,SEG_code[16]);
Delay_tube(500);
Show_tube(4,SEG_code[16]);
Delay_tube(500);
}
void Display_tube()
{
if(state == 0) //LED关闭:显示F
{
Display(15);
}
else if(state == 1) //模式1:显示1
{
Display(1);
}
else if(state == 2) //模式2:显示2
{
Display(2);
}
else if(state == 3) //模式3:显示3
{
Display(3);
}
}
void Press_keys()
{
Select_HC138(4);
if(S7 == 0)
{
Delay_keys();
if(S7 == 0)
{
switch(state)
{
case 0: //模式1:10%亮度
PWM = 10;
state = 1;
TR0 = 1; //启动定时器0
//L1 = 0;
break;
case 1: //模式2:50%亮度
PWM = 50;
state = 2;
break;
case 2: //模式3:90%亮度
PWM = 90;
state = 3;
break;
case 3: //关闭状态
TR0 = 0;
L1 = 1;
state = 0;
break;
}
// while(S7 == 0)
// {
// Display_tube();
// }
}
while(S7 == 0);
}
}
void main()
{
Init_timer0(); //定时器0初始化
Select_HC138(5);
P0 = 0x00; //关闭蜂鸣器和继电器
Select_HC138(4);
P0 = 0xff;
while(1)
{
//Display_tube();
Press_keys();
}
}
蓝桥杯单片机CT107D_10_PWM调节LED亮度
最新推荐文章于 2022-10-15 15:20:07 发布