欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

蓝桥杯单片机必备知识-----(5)独立按键

程序员文章站 2022-06-08 20:49:26
...

蓝桥杯单片机必备知识-----(5)独立按键

独立按键

蓝桥杯单片机必备知识-----(5)独立按键
注:在使用独立按键部分时,需将跳线帽放置BIT端

代码逻辑:

1.放在while(1)一直扫描按键是否按下
2.放在中断中 中断一次扫描按键是否按下
注:大型项目会放在中断中进行,一直扫描会占用过多资源,如果参加比赛则可以在while中一直使用循环

按键扫描函数

void read_key()
{
	uchar temp;  
	static unsigned state = 0;		//状态
	temp = P3 & 0x0f; 	//临时存储P3的状态
	switch(state)
	{
		case 0:{if(P3 != 0x0f) state = 1;}break;	//状态0,检测到有按键按下
		case 1:										//再次检测是否有按键按下,消抖
		{
			if(P3 != 0x0f){
			switch(temp)
			{
				case 0x0e:{s7++;state = 2;}break;	//如果S7按键对应的状态改变,则s7++
				case 0x0d:{s6++;state = 2;}break;	//如果S6按键对应的状态改变,则s7++
				case 0x0b:{s5++;state = 2;}break;	//如果S5按键对应的状态改变,则s7++
				case 0x07:{s4++;state = 2;}break;	//如果S4按键对应的状态改变,则s7++
			}
			}
			else state = 0;
		}break;
		case 2:{if(P3 == 0xff) state = 0;}break;	//检测按键是否抬起
	}
}

中断函数

void time0() interrupt 1
{
	static unsigned char intr = 0;
	display();
	if(++intr == 8) 	//按键消抖时间为5~10ms	
	{
		intr = 0;
		read_key();		//进行键扫描
	}
}

主函数内容不再赘述,如有不明白请看1,2中的内容

测试结果:

蓝桥杯单片机必备知识-----(5)独立按键

代码粘贴

#include <stc15f2k60s2.h>

#define uint unsigned int
#define uchar unsigned char

uchar tab[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff};
uchar dspbuf[8] = {10,10,10,10,10,10,10,10};
uchar s4 =0 ,s5 = 0,s6 = 0,s7 = 0;

void read_key();
void display();
void load();
void cls()
{
	//关闭LED
	P2 = (P2 & 0x1f) | 0x80;
	P0 = 0xff;
	P2 = 0x1f;
	//关闭BUZZ
	P2 = (P2 & 0x1f) | 0xa0;
	P0 = 0x00;
	P2 = 0x1f;
}

void main()
{
	cls();
	AUXR = 0x80;
	TMOD = 0x80;
	TL0 = 0xcd;
	TH0 = 0xd4;
	
	TR0 = 1;
	ET0 = 1;
	EA = 1;
	while(1)
	{}
}

void time0() interrupt 1
{
	static unsigned char intr = 0;
	display();
	if(++intr == 8) 	
	{
		intr = 0;
		read_key();
	}
}

void read_key()
{
	uchar temp;
	static unsigned state = 0;
	temp = P3 & 0x0f;
	switch(state)
	{
		case 0:{if(P3 != 0x0f) state = 1;}break;
		case 1:
		{
			if(P3 != 0x0f){
			switch(temp)
			{
				case 0x0e:{s7++;state = 2;}break;
				case 0x0d:{s6++;state = 2;}break;
				case 0x0b:{s5++;state = 2;}break;
				case 0x07:{s4++;state = 2;}break;
			}
			}
			else state = 0;
		}break;
		case 2:{if(P3 == 0xff) state = 0;}break;
	}
}

void load()
{
	
	dspbuf[0] = s4;
	dspbuf[1] = s5;
	dspbuf[2] = s6;
	dspbuf[3] = s7;
	dspbuf[4] = 10;
	dspbuf[5] = 10;
	dspbuf[6] = 10;
	dspbuf[7] = 10;
}

void display()
{
	static unsigned char dspcom = 0;
	load();
	P2 = (P2 & 0x1f) | 0xe0;
	P0 = 0xff;
	P2 = 0x1f;
	
	P2 = (P2 & 0x1f) | 0xc0;
	P0 = 1 << dspcom;
	P2 = 0x1f;
	
	P2 = (P2 & 0x1f) | 0xe0;
	P0 = tab[dspbuf[dspcom]];
	P2 = 0x1f;
	
	if(++dspcom == 8) dspcom = 0;
}
相关标签: 蓝桥杯单片机