1:独立按键控制小灯亮灭(单片机):
#include
sbit key=P3^0; sbit D1=P1^0;
//51单片机函数头文件 //定义按键的IO口 //定义led灯的IO口 void delay(unsigned char y)
{ unsigned char j,k; for(j=y;j>0;j--) for(k=0;k<57;k--); }
void keyscan() { if(key==0) { delay(10); if(key==0) { D1=0; } } }
void main() { while(1) { keyscan(); } }
2:矩阵键盘控制多个小灯(单片机):#include
#define uint unsigned int #define uchar unsigned char sbit D1=P1^0; sbit D2=P1^1; sbit D3=P1^2; sbit D4=P1^3;
void delay(uint z) { uint x,y;
for(x=z;x>0;x--)
for(y=100;y>0;y--);
//延时子函数
//延时10ms,去抖动
//延时函数
}
void main() {
while(1) { uchar temp; P3=0xfe; temp=P3;
temp=temp&0xf0; while(temp!=0xf0) { delay(5); temp=P3;
temp=temp&0xf0; while(temp!=0xf0) {
temp=P3; switch(temp) {
case 0xee:D1=0;break; case 0xde:D2=0;break; } } while(temp!=0xf0) { temp=P3; temp=temp&0xf0; } } P3=0xfd; temp=P3;
temp=temp&0xf0; while(temp!=0xf0) {
delay(5); temp=P3;
temp=temp&0xf0; while(temp!=0xf0) {
temp=P3; switch(temp) { case 0xde:D3=0;break;
//键盘扫描 //延时去抖 //按键松手检测
case 0xdd:D4=0;break; } } while(temp!=0xf0) { temp=P3; temp=temp&0xf0; } } } }
3:矩阵键盘控制数码管显示(单片机):
#include
#define uint unsigned int #define uchar unsigned char sbit wela=P2^0;
uchar code table[]= { //段选的数字决定显示的数字,这里的是数字0~15 0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f,0x77,0x7c, 0x39,0x5e,0x79,0x71,}; void delay(uint z) //延时ms函数 { uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--); }
void display(uchar num) //显示子函数 { P0=table[num]; }
void main() { uchar temp,num; //初始化位选,显示0 P0=0x3f; wela=0; while(1) { P3=0xfe; //按键检测 temp=P3; temp=temp&0xf0; while(temp!=0xf0)