前言
我们老师说这个题目如果写出来基本就有省三等奖的水平了【狗头】一、题目要求
上电LED、数码管、蜂鸣器、继电器全关闭,按下S7按键任意四位数码管显示1234,按下S6按键任意四位数码管显示5678且LED5点亮,
按下S5按键任意四位数码管显示CPUF且打开继电器,按下S4按键数码管、LED、继电器关闭,打开蜂鸣器。
二、原理图
数码管:
继电器和蜂鸣器:
按键:
三、代码
//@mzw
#include <reg52.h>
#include <intrins.h>
sfr P4 = 0xc0; //reg52.h头文件中未包含P4口
sbit hc138_A=P2^5;
sbit hc138_B=P2^6;
sbit hc138_C=P2^7;
sbit S7 = P3^0;
sbit S6 = P3^1;
sbit S5 = P3^2;
sbit S4 = P3^3;
sbit RELAY = P0^4; //继电器和LED5控制引脚
sbit BUZZ = P0^6; //蜂鸣器控制引脚
sbit LED5 = P0^4; //LED5控制引脚
unsigned char key_value = 0;
unsigned char shuzi[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; //0-9
unsigned char shuzi1[10]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};//0-9//含小数点
unsigned char xianshi[5]={0xff,0xff,0xff,0xff,0xff};
/*****配置138译码器*****/
void HC138(unsigned int n)
{
switch(n)
{
case 4:
hc138_A=0 ; hc138_B=0 ; hc138_C=1; break;
case 5:
hc138_A=1 ; hc138_B=0 ; hc138_C=1; break;
case 6:
hc138_A=0 ; hc138_B=1 ; hc138_C=1; break;
case 7:
hc138_A=1 ; hc138_B=1 ; hc138_C=1; break;
}
}
/*****延时函数*****/
void delay(unsigned int k)
{
while(k--);
}
/*****数码管显示函数*****/
void Display()
{
char x = 0x01;
int i = 0;
for(i = 1;i<=8 ;i++)
{
HC138(6);
P0 = x;
x = _crol_(x,1);
HC138(7);
P0 = 0xff;delay(50); //数码管消隐放到这个地方好一点
switch (i)
{
case 1 :P0 = xianshi[i]; break;
case 2 :P0 = xianshi[i]; break;
case 3 :P0 = xianshi[i]; break;
case 4 :P0 = xianshi[i]; break;
case 5 :P0 = 0xff; break;
case 6 :P0 = 0xff; break;
case 7 :P0 = 0xff; break;
case 8 :P0 = 0xff; break;
}
delay(500);P0 = 0xff;
}
}
/*****按键扫描函数*****/
void key_scan()
{
if((S4 == 0) || (S5 == 0) || (S6 == 0) || (S7 == 0)) //其中一个按键被按下则为1
{
delay(100); //延时消抖
if(S4 == 0) key_value = 4;
if(S5 == 0) key_value = 5;
if(S6 == 0) key_value = 6;
if(S7 == 0) key_value = 7;
while((S4 == 0) || (S5 == 0) || (S6 == 0) || (S7 == 0))//等待按键松开
{
Display();
}
}
}
/*****按键实现函数*****/
void Key_real()
{
if(key_value == 7) //按下S7按键任意四位数码管显示1234,
{
HC138(5);P0 = 0x00;BUZZ = 0;RELAY = 0;
HC138(4);P0 = 0xff;LED5 = 1;
xianshi[1]=shuzi[1];
xianshi[2]=shuzi[2];
xianshi[3]=shuzi[3];
xianshi[4]=shuzi[4];
}
if(key_value == 6) //按下S6按键任意四位数码管显示5678且LED5点亮,
{
HC138(5);P0 = 0x00;BUZZ = 0;RELAY = 0;
HC138(4);P0 = 0xff;LED5 = 0;
xianshi[1]=shuzi[5];
xianshi[2]=shuzi[6];
xianshi[3]=shuzi[7];
xianshi[4]=shuzi[8];
}
if(key_value == 5) //按下S5按键任意四位数码管显示CPUF且打开继电器,
{
HC138(5);P0 = 0x00;BUZZ = 0;RELAY = 1;
HC138(4);P0 = 0xff;LED5 = 1;
xianshi[1]=0xc6; //C
xianshi[2]=0x8c; //P
xianshi[3]=0xc1; //U
xianshi[4]=0x8e; //F
}
if(key_value == 4) //按下S4按键数码管、LED、继电器关闭,打开蜂鸣器。
{
HC138(5);P0 = 0x00;BUZZ = 1;RELAY = 0;
HC138(4);P0 = 0xff;LED5 = 1;
xianshi[1]=0xff;
xianshi[2]=0xff;
xianshi[3]=0xff;
xianshi[4]=0xff;
}
}
void main()
{
HC138(5);
P0=0x00; //蜂鸣器和继电器初始化、、全关
HC138(4);
P0= 0xff; //LED小灯初始化、、全关
while(1)
{
key_scan(); //按键扫描
Key_real(); //按键实现函数
Display(); //数码管显示
}
}