单片机之矩阵键盘的驱动程序

#include 

#define KEYPORT P1
#include "./delay/delay.h"

sbit seg_select = P2^0;      //段选
sbit bit_select = P2^1;      //位选
#define SEGPORT  P0


unsigned char segdata[10] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
unsigned char bitdata[8] = {0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
unsigned char TempData[2];

void display(void)
{
		
	  static unsigned char i = 0;
	  SEGPORT = 0x0;              //消除重影
	  seg_select = 1;
	  seg_select = 0;
	  
	  SEGPORT = 0xff;
	  bit_select = 1;
	  bit_select = 0;
	
	  SEGPORT = TempData[i];
	  seg_select = 1;
	  seg_select = 0;
	  
	  SEGPORT = bitdata[i];
	  bit_select = 1;
	  bit_select = 0;
	  
    i++;
    if(2 == i)
    {
				i = 0;
		}			
	
}

void timer0_init(void)                       //中断函数
{
		EA = 1;                               //打开总中断
	  TMOD |= 0x01;                        //设置定时器工作方式
	  TH0 = (65536 - 2000) / 256;
	  TL0 = (65536 - 2000) % 256;
	  ET0 = 1;                           //打开定时器中断允许
	  TR0 = 1;                           
}

void timer0_isr(void) interrupt 1    //中断服务程序
{
		TH0 = (65536 - 2000) / 256;
	  TL0 = (65536 - 2000) % 256;
	  display();
	  
}


unsigned char key_scan(void)
{
		unsigned char keyvalue;
	  KEYPORT = 0xf0;
	
	  if(0xf0 != KEYPORT)                                // 有按键按下  
		{
				delay_ms(10);
			  if(0xf0 != KEYPORT)                          //确实有按键按下
				{
					  //KEYPORT &= 0xfo;
						KEYPORT = 0xfe;
					
					  if(0xfe != KEYPORT)
						{
								keyvalue = KEYPORT;
							  while(0xfe != KEYPORT);           //有按键抬起
								delay_ms(10);
								while(0xfe != KEYPORT);          //确实有按键抬起
								return keyvalue;
						}
						KEYPORT = 0xfd;
						if(0xfd != KEYPORT)
						{

						}
						KEYPORT = 0xfb;
						if(0xfb != KEYPORT)
						{

						}
						KEYPORT = 0xf7;
						if(0xf7 != KEYPORT)
						{

						}
				}
		}
		return 0xff;
}

unsigned key_prc()
{
		unsigned char keynum;
	  keynum = key_scan();
	
	  switch(keynum)
		{
				case 0x7e: return 0; break;
			  case 0xbe: return 1; break;
			  case 0xde: return 2; break;
			  case 0xee: return 3; break;
			  default: return 0xff; break;
		}
}

void main()
{
		unsigned char key;
		timer0_init();
	  while(1)
		{
				key = key_prc();
			  if(0xff != key)
				{
						
					  TempData[0] = segdata[key / 16];
					  TempData[1] = segdata[key % 16];
				}
		}
}

/*********delay.c*******/
void delay_us(unsigned char t)
{
		while(--t);
}

void delay_ms(unsigned char t)
{
		while(t--)
		{
			delay_us(245);
			delay_us(245);
		
		}
}

void delay_s(unsigned char t)
{
    while(t--)
		{
        delay_ms(200);
				delay_ms(200);
			  delay_ms(200);
				delay_ms(200);
			  delay_ms(200);
		}
}

/*******delay.h******/
#ifndef _DELAY_H_
#define _DELAY_H_

extern void delay_us(unsigned char t);
extern void delay_ms(unsigned char t);
extern void delay_s(unsigned char t);

#endif

你可能感兴趣的:(单片机)