51单片机八路抢答器
由于51单片机小板,按键比较少,还有一些功能上的缺陷,所以说无法完成八路抢答器,所以我们用proteus仿真,代码与实验结果如下:
/********************************
Function: 八路抢答器
Date: Sep 20,2017
By:Third Group Bolanche L
**************************/
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
sbit Start=P3^7;
sbit Indecator=P3^6; //指示灯
sbit Interrupt=P3^3; //中断1
sbit KEY1=P2^0; //第一位LED
sbit KEY2=P2^1;
sbit KEY3=P2^2;
sbit KEY4=P2^3;
sbit KEY5=P2^4;
sbit KEY6=P2^5;
sbit KEY7=P2^6;
sbit KEY8=P2^7;
uchar n; //声明全局无符号字符变量n
//延时毫秒
void delayms(uint c)
{
uchar a,b;
for(;c>0;c--)
for(a=142;a>0;a--)
for(b=2;b>0;b--);
}
//数码管显示
void SMG_dis(uchar m)
{
P0=table[m] ;
//delayms(20);
}
//LED亮
void LED_DIS(uchar i)
{
P1 |=(1<<(i-1)); //将第i个LED点亮
}
//按键扫描,返回值为被按下的那个按键,每按下一个按键触发一次中断
char KEY_Scan(void)
{
if(KEY1==0)
{
delayms(20); //消抖
if(KEY1==0)
{
Interrupt=1; //中断1口赋高电平
delayms(20);
Interrupt=0;
n=1;
}
}
if(KEY2==0)
{
delayms(20);
if(KEY2==0)
{
Interrupt=1;
delayms(20);
Interrupt=0;
n=2;
}
}
if(KEY3==0)
{
delayms(20);
if(KEY3==0)
{
Interrupt=1;
delayms(20);
Interrupt=0;
n=3;
}
}
if(KEY4==0)
{
delayms(20);
if(KEY4==0)
{
Interrupt=1;
delayms(20);
Interrupt=0;
n = 4;
}
}
if(KEY5==0)
{
delayms(20);
if(KEY5==0)
{
Interrupt=1;
delayms(20);
Interrupt=0;
n = 5;
}
}
if(KEY6==0)
{
delayms(20);
if(KEY6==0)
{
Interrupt=1;
delayms(20);
Interrupt=0;
n = 6;
}
}
if(KEY7==0)
{
delayms(20);
if(KEY7==0)
{
Interrupt=1;
delayms(20);
Interrupt=0;
n = 7;
}
}
if(KEY8==0)
{
delayms(20);
if(KEY8==0)
{
Interrupt=1;
delayms(20);
Interrupt=0;
n = 8;
}
}
return n;
}
void INT_1() interrupt 2
{
EX1=0;
delayms(20); //消抖
EX1=1;
LED_DIS(n);
SMG_dis(n);
Indecator=0;
delayms(20);
P1=0x00; //关闭抢答人指示灯
}
void main()
{
EX1=1; //开启外部中断1
IT1=1; //开启下降沿触发
EA=1; //开启总中断
P1=0x00; // 点亮第一位小灯
P0=0x00; // 关闭数码管
Indecator=0; //关闭指示灯
Interrupt=1;
while(1)
{
if(Start==0)
{
delayms(20);
if(Start==0)
Indecator=1; //主持人按下开始按键,指示灯亮
}
n=KEY_Scan();//扫描哪一个按键被按下,并触发中断
}