【Proteus仿真】51单片机矩阵按键扫描+外部中断使用
📝实验代码
#include <mcs51reg.h>
#include <stdio.h>
#define FOSC 11059200UL
#define BAUD 9600
#define COL1 (0xEF)
#define COL2 (0xDF)
#define COL3 (0xBF)
#define COL4 (0x7F)
unsigned char key_val[] = {
COL1, COL2, COL3, COL4
};
unsigned char key_data[] = {
0xEE, 0xED, 0xEB, 0xE7,
0xDE, 0xDD, 0xDB, 0xD7,
0xBE, 0xBD, 0xBB, 0xB7,
0x7E, 0x7D, 0x7B, 0x77,
};
unsigned char key_row = 0;
unsigned char key_col = 0;
void delayms(unsigned int ms)
{
unsigned int x;
unsigned int y;
for (y=ms; y>0; y--)
{
for (x=227; x>0; x--)
;
}
}
void uart_init()
{
SCON = 0x50;
TMOD = 0x20;
TH1 = (unsigned char)(((65536 - (FOSC/32/BAUD) )>>8) - 2) ;
TL1 = (unsigned char)(65536- (FOSC/32/BAUD) - 2) ;
TR1 = 1;
}
void SendData(char data1)
{
SBUF = data1;
while (!TI) ;
TI = 0;
}
void SendString(unsigned char *buffer)
{
unsigned char *p = buffer;
while (*p)
{
SendData(*p);
p++;
}
}
int putchar(int data1)
{
SendData(data1);
return data1;
}
void int0_init()
{
IT0 = 1;
EX0 = 1;
EA = 1;
}
void key_scan()
{
unsigned char i = 0;
for (i=0; i<4; i++)
{
key_col = key_val[i];
P1 = key_col;
delayms(20);
}
}
void key_value(unsigned char value)
{
unsigned char i = 0;
for (i=0; i<16; i++)
{
if (value == key_data[i])
{
printf("Keyvalue:%d \r\n",i + 1);
}
}
}
void int0_isr(void) __interrupt 0 __using 1
{
EX0 = 0;
delayms(20);
key_row = P1;
key_value(key_row);
EX0 = 1;
}
void main(void)
{
unsigned char i = 0;
int0_init();
uart_init();
while (1)
{
key_scan();
}
}
📚仿真资源
链接: https:
提取码: uhhx