51单片机矩阵键盘扫描程序
keyscan.h
#ifndef _KEYSCAN_H_
#define _KEYSCAN_H_
#include<reg51.h>
#ifndef uchar
#define uchar unsigned char
#endif
#ifndef uint
#define uint unsigned int
#endif
#define KEYPINS P1//定义矩阵键盘的端口
extern uchar keyPressFlag;
uchar keyScan();
void initialKeyScan();
#endif
keyscan.c
#include<keyscan.h>
#include<intrins.h>
#include<function.h>
uchar keyPressFlag;
void initialKeyScan()
{
keyPressFlag = 0;
}
uchar keyScan()
{
uchar k, k_temp;
KEYPINS = 0x0f;
k = KEYPINS;
if(k != 0x0f){
delayms(80);
k_temp = KEYPINS;
if(k == k_temp)
{
keyPressFlag = 1;
k = 0xef;
do
{
KEYPINS = k;
switch(KEYPINS)
{
case 0xee:{return 0x00; break;}
case 0xed:{return 0x04; break;}
case 0xeb:{return 0x08; break;}
case 0xe7:{return 0x0c; break;}
case 0xde:{return 0x01; break;}
case 0xdd:{return 0x05; break;}
case 0xdb:{return 0x09; break;}
case 0xd7:{return 0x0d; break;}
case 0xbe:{return 0x02; break;}
case 0xbd:{return 0x06; break;}
case 0xbb:{return 0x0a; break;}
case 0xb7:{return 0x0e; break;}
case 0x7e:{return 0x03; break;}
case 0x7d:{return 0x07; break;}
case 0x7b:{return 0x0b; break;}
case 0x77:{return 0x0f; break;}
}
k = _crol_(k, 1);
}while(k != 0xfe);
}
}
return 0x10;
}
里面用到了function.h
#ifndef _FUNCTION_H_
#define _FUNCTION_H_
#ifndef uchar
#define uchar unsigned char
#endif
#ifndef uint
#define uint unsigned int
#endif
void delayms(uint c);
#endif
funtion.c
#include<function.h>
void delayms(uint c) //误差 0us
{
uchar a,b;
for (; c>0; c--)
{
for (b=199;b>0;b--)
{
for(a=1;a>0;a--);
}
}
}