#include /* 两行接 P3.6、P3.7,四列从左到右接 P3.3、P3.2、P3.1、P3.0 */ sbit row1 = P3^7; sbit row2 = P3^6; sbit col1 = P3^3; sbit col2 = P3^2; sbit col3 = P3^1; sbit col4 = P3^0; void delayMs(unsigned int i) { unsigned char t; while (i--) for (t = 0; t < 120; t++); } unsigned char scanKey(void) { unsigned char key = 0; P3 = 255; /* 输入引脚先写 1 */ row1 = 0; /* 扫描第一行 */ if (col1 == 0) key = 1; else if (col2 == 0) key = 2; else if (col3 == 0) key = 3; else if (col4 == 0) key = 4; row1 = 1; row2 = 0; /* 扫描第二行 */ if (key == 0) { if (col1 == 0) key = 5; else if (col2 == 0) key = 6; else if (col3 == 0) key = 7; else if (col4 == 0) key = 8; } row2 = 1; return key; /* 没有按键返回 0 */ } void main(void) { unsigned char key; P2 = 255; /* LED 低电平点亮,初始全灭 */ while (1) { key = scanKey(); if (key != 0) { delayMs(20); /* 按键消抖 */ if (scanKey() == key) P2 = 255U << key; /* 低位补 0,点亮对应数量的灯 */ } } }