蓝桥杯CT107D之独立按键

直接上代码

采用状态机消抖,比较基础,相信有一定51基础的都能看懂吧‘’‘’‘’

#include "reg51.h"

//-----------------------------------------------
#define key_input P3
#define key_state_0 0	  //是否按下
#define key_state_1 1 	  //是否是抖动
#define key_state_2 2	  //判断是否弹起
#define key_mask 0x0f	  //屏蔽不需要的IO

#define FOSC 11059200L

#define T1MS (65536-FOSC/1000)      //1T模式
//#define T1MS (65536-FOSC/12/1000) //12T模式

sfr AUXR = 0x8e;                    //Auxiliary register
sbit N_RELAY = P0^4;
sbit N_BUZZ = P0^6;
sbit LED_1 = P0^0;

char KEY;

char read_key(void)
{
	static char key_state = 0;
	char key_press,key_return = 0;
	key_press = key_input & key_mask;
	switch(key_state)
	{
		case key_state_0:
		if(key_press != key_mask)
		key_state = key_state_1;
		break;
		case key_state_1:
		if(key_press = (key_input & key_mask))
		{
			if(key_press == 0x0e) key_return = 1;
			if(key_press == 0x0d) key_return = 2;
			if(key_press == 0x0b) key_return = 3;
			if(key_press == 0x07) key_return = 4;
			key_state = key_state_2;
		}
		else
		key_state = key_state_0;
		break;
		case key_state_2:
		if(key_press == 0x0f)	key_state = key_state_0;
		break;
		default:
		break;
	}
	return 	key_return;
}


/* Timer0 interrupt routine */
void tm0_isr() interrupt 1 
{
	static char count=10;
	if(count-- == 0)
	{
		count = 10;
		KEY = read_key();
	}
}


//T0初始化
void Timer0Init()
{
	AUXR |= 0x80;                   //定时器0为1T模式
//  AUXR &= 0x7f;                   //定时器0为12T模式

    TMOD = 0x00;                    //设置定时器为模式0(16位自动重装载)
    TL0 = T1MS;                     //初始化计时值
    TH0 = T1MS >> 8;
    TR0 = 1;                        //定时器0开始计时
    ET0 = 1;                        //使能定时器0中断
    EA = 1;
}

/* main program */
void main()
{
	P2 = 0xa0; N_BUZZ=0;N_RELAY=0;  P2 = 0x00;
	P2 = 0x80; P0=0xff;  P2 = 0x00;
	Timer0Init();
    while (1)
	{
		switch(KEY)
		{
			case 1:
			P2 = 0xa0;P0=0x00;N_RELAY=1;  P2 = 0x00;
			break;
			case 2:
			P2 = 0xa0;P0=0x00;N_BUZZ=1;	  P2 = 0x00;
			break;
			case 3:
			P2 = 0x80;P0=0xff;LED_1=0;	  P2 = 0x00;
			break;
			case 4:
			P2 = 0xe0;P0=0xc0;	  P2 = 0x00;
			P2 = 0xc0;P0=0xff;	  P2 = 0x00;
			break;
			default:
			break;
		}	
	}
}



你可能感兴趣的:(CT107D)