蓝桥杯——用三行代码写独立键盘

一、原理部分

三行代码

uchar cont,trg;    //triger触发 continue连续
void KeyScan()
{
	    uchar ReadData =  PINB^0xff;
		trg = ReadData&(ReadData^cont);
		cont = ReadData;
}

原理在我之前的一篇文章中有讲到,这里不再赘述三行代码搞定独立按键

二、代码部分

实验平台:CT107D
实验芯片:stc15f2k60s2
实验现象:按下S7数码管显示数字加1,长按1s以上加10,大于99清零。
代码如下

#include

#define uchar unsigned char
#define uint unsigned int

sbit buzz = P0^6;

uchar code duan[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,0x00};//定义段码数组
uchar disbuff[8];//定义显示数字数字

uchar cont,trg;
uchar index,num = 0; 
uchar count = 0;

void closebuzz()
{
	P2 = 0xa0;
	buzz = 0;
	P2 = 0x00;
}

void keyscan()//按键扫描
{
	    uchar ReadData =  P3^0xff;
		trg = ReadData&(ReadData^cont);
		cont = ReadData;
}

void keyfun()//按键功能
{
	if(trg == 0x01)
	{
		num++;

		if(num >= 99)
		num = 0;
	}

	if(cont == 0x01)
	{
		if(++count == 50)	 //1s长按键触发
		{
			count = 0;
			num+=10;

			if(num >= 99)
			num = 0;
		}
	}
}

void shownum()//显示数字函数
{
	disbuff[0]=num/10;
	disbuff[1]=num%10;
	disbuff[2]=10;
	disbuff[3]=10;
	disbuff[4]=10;
	disbuff[5]=10;
	disbuff[6]=10;
	disbuff[7]=10;
}

void display()//数码管扫描函数
{
	P2 = 0xe0;
	P0 = 0xff;
	P2 = 0x00;

	P2 = 0xc0;
	P0 = 1<<index;
	P2 = 0x00;

	P2 = 0xe0;
	P0 = ~duan[disbuff[index]];
	P2 = 0x00;

	index++;
	index &= 0x07;

}

void Timer0Init(void)		//2毫秒@12.000MHz
{
	AUXR |= 0x80;		//定时器时钟1T模式
	TMOD &= 0xF0;		//设置定时器模式
	TL0 = 0x40;		//设置定时初值
	TH0 = 0xA2;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	TR0 = 1;		//定时器0开始计时
	ET0 = 1;
	EA = 1;
}

void time1() interrupt 1 //中断服务函数
{
	static uchar key_count = 0;
	if(++key_count == 10)//20ms扫描一次按键
	{
		key_count = 0;
		keyscan();
		keyfun();
	}
	display();		
}

void main()
{
	Timer0Init(); //初始化定时器
	closebuzz();
	while(1)
	{
		shownum();
	}
}


你可能感兴趣的:(蓝桥杯,单片机)