【蓝桥杯单片机进阶强化-04】PWM信号控制呼吸流水灯
内容来自小蜜蜂老师 小蜜蜂老师博客链接 老师在这个案例中是用MM模式写的 我用IO方式写的 在进行S7按键操作时不知道为什么没有反应 检查了一下和老师写的差不多 望大佬指出错误
#include "reg52.h"
sbit S4 = P3^3;
sbit S7 = P3^0;
unsigned char pwm = 0;
unsigned char pwm_duty = 0;
unsigned char times = 0;
unsigned char key_value = 0;
unsigned char led_start = 0;
unsigned char status = 0;
unsigned char status_go = 0;
unsigned char code SMG_duanma[18]=
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,
0x88,0x80,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};
void Delay(unsigned int t)
{
while(t--);
}
void Init_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 Init_System(void)
{
Init_74HC138(4);
P0 = 0xff;
Init_74HC138(5);
P0 = 0x00;
}
void SMG_DisplayBit(unsigned char pos,unsigned char dat)
{
Init_74HC138(6);
P0 = (0x01 << pos);
Init_74HC138(7);
P0 = dat;
}
void SMG_Close(unsigned char dat)
{
Init_74HC138(6);
P0 = 0xff;
Init_74HC138(7);
P0 = dat;
}
void SMG_Display_Data(unsigned char status,unsigned char duty)
{
SMG_DisplayBit(0,SMG_duanma[status]);
Delay(200);
SMG_DisplayBit(1,0xff);
Delay(200);
SMG_DisplayBit(2,0xff);
Delay(200);
SMG_DisplayBit(3,0xff);
Delay(200);
SMG_DisplayBit(4,0xff);
Delay(200);
SMG_DisplayBit(5,0xff);
Delay(200);
SMG_DisplayBit(6,SMG_duanma[duty/10]);
Delay(200);
SMG_DisplayBit(7,SMG_duanma[duty%10]);
Delay(200);
SMG_DisplayBit(0,0xff);
Delay(200);
SMG_DisplayBit(6,0xff);
Delay(200);
SMG_DisplayBit(7,0xff);
Delay(200);
}
void Init_Timer0(void)
{
TMOD = 0x01;
TH0 = (65535-1000)/256;
TL0 = (65535-1000)%256;
ET0 = 1;
TR0 = 1;
EA = 1;
}
void Led_Control(void)
{
if(times == 5)
{
times = 0;
if(led_start == 0)
{
pwm_duty += 1;
if(pwm_duty == 11)
{
pwm_duty = 10;
led_start = 1;
}
}
else if(led_start == 1)
{
pwm_duty -= 1;
if(pwm_duty == 255)
{
pwm_duty = 0;
led_start = 0;
if(status_go == 1)
{
status ++;
if(status == 8)
{
status = 0;
}
}
else if(status_go == 2)
{
status--;
if(status == 255)
{
status = 7;
}
}
}
}
}
}
void Key_Tackle(void)
{
if(S4 == 0)
{
Delay(20);
if(S4 == 0)
{
while(S4 == 0)
{
key_value = 1;
}
key_value = 0;
status_go++;
if(status_go == 3)
{
status_go = 1;
}
}
}
if(S7 == 0)
{
Delay(20);
if(S7 == 0)
{
while(S7 == 0)
{
key_value = 1;
SMG_Display_Data(status+1,pwm_duty*10);
}
key_value = 0;
}
}
}
void main(void)
{
Init_System();
Init_Timer0();
while(1)
{
Led_Control();
Key_Tackle();
}
}
void Server_Timer0() interrupt 1
{
TH0 = (65535-1000)/256;
TL0 = (65535-1000)%256;
if(status_go == 0)
{
Init_74HC138(4);
P0 = 0xe7;
}
pwm++;
if(pwm < pwm_duty)
{
Init_74HC138(4);
P0 = ~(0x01 << status);
}
else if(pwm <= 10)
{
Init_74HC138(4);
P0 = 0xff;
}
else
{
pwm = 0;
Init_74HC138(4);
P0 = ~(0x01 << status);
if(key_value == 0)
{
times++;
}
}
}
|