#include "DataType.h"
#include "C8051F020.h"
//-----------------------------------------------------------------
//----按键接P1端口  PA1接P4^0…PA4接P4^3  PB1接P4^4…PB4接P4^7-----
#define KeyPort P4
#define PA1    0
#define PA2    1
#define PA3    2
#define PA4    3
#define PB1    4
#define PB2    5
#define PB3    6
#define PB4    7
//-----------------------------------------------------------------
void KeyPort_Init ()
{
    P74OUT |= BIT0;  //P4.0-P4.3设置为推挽输出
	P74OUT &= ~BIT1; //P4.4-P4.7设置成漏极开路输出
	P4 |= BIT4 + BIT5 + BIT6 + BIT7; //置1漏极开路引脚的数据寄存器，使其为数字输入模式
}
/******************************************************************
* 函数名称：KeyScan
* 函数功能：按键扫描，返回0表示无键按下，1-16是正常返回
*******************************************************************/
INT8U KeyScan ()
{
    INT32U i;
    KeyPort = 0xf0;
    if(0xf0 == (KeyPort & 0xf0)) // 没有按键，返回0
    {
        return 0;
    }
 
    for(i = 0; i < 6000; i ++);  // 有键按下，延时先 可修改
  
    KeyPort = 0xfE; // 扫描KEY1 - KEY4
    if(0xf0 != (KeyPort & 0xf0))
    {
        switch((KeyPort & 0xf0))
        {
        case 0xE0:
            return 1;
        case 0xD0:
            return 2;
        case 0xB0:
            return 3;
		case 0x70:
			return 4;            
        default:
            return 0; 
        }
    }

	KeyPort = 0xfD;
	if(0xf0 != (KeyPort & 0xf0))
    {
        switch((KeyPort & 0xf0))
        {
        case 0xE0:
            return 5;
        case 0xD0:
            return 6;
        case 0xB0:
            return 7;
		case 0x70:
			return 8;            
        default:
            return 0; 
        }
    }

    KeyPort = 0xfB;
    if(0xf0 != (KeyPort & 0xf0))
    {
        switch((KeyPort & 0xf0))
        {
        case 0xE0:
            return 9;
        case 0xD0:
            return 10;
        case 0xB0:
            return 11;
		case 0x70:
			return 12;            
        default:
            return 0; 
        }
    }

	KeyPort = 0xf7;
	if(0xf0 != (KeyPort & 0xf0))
    {
        switch((KeyPort & 0xf0))
        {
        case 0xE0:
            return 13;
        case 0xD0:
            return 14;
        case 0xB0:
            return 15;
		case 0x70:
			return 16;            
        default:
            return 0;
        }
    }

    return 0;
}