蓝桥杯单片机——矩阵键盘(6)

一、原理图分析

首先将J5的跳线帽连接到1、2引脚,使得S4~S19按键组成4*4的矩阵键盘。当按键没有按下时,所有的输入端都是高电平,只要有低电平出现,则说明有键按下。扫描原理如下:

二、编写程序

实现功能:在数码管的第一位显示相应的数字:从左至右,从上到下,依次显示0~F。

注:

①若使用 reg52.h 开头的程序

#include <reg52.h>

sfr P4 = 0xC0;//在reg52.h 中没有定义 P4 寄存器,所以需自己定义

②若使用 stc15f2k60s2.h 开头的程序

#include “stc15f2k60s2.h”// 此文件里已经定义 P4 寄存器,所以不需要重复定义

#include<reg52.h>
unsigned char code duanma[18]=
{	0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0xbf,0x7f};

sfr  P4=0xC0;//定义P4口,从头文件reg51.h里定义相应地址

sbit R1=P3^0;
sbit R2=P3^1;
sbit R3=P3^2;
sbit R4=P3^3;

sbit C4=P3^4;
sbit C3=P3^5;
sbit C2=P4^2;
sbit C1=P4^4;

void SMG_show(unsigned char value)//数码管显示函数
 {
 	 P2=0xC0;P0=0x01;
	 P2=0xE0;P0=value;
 
 }
void keyshow()//按键扫描函数
 {
 	R1=0;//逐行扫描
	R2=R3=R4=1;
	C1=C2=C3=C4=1;
	if(C1==0)//逐列扫描
	{
		 while(C1==0);
		 SMG_show(duanma[0]);
	}
  	else if(C2==0)
	{
		 while(C2==0);
		 SMG_show(duanma[1]);
	}
 	else if(C3==0)
	{
		 while(C3==0);
		 SMG_show(duanma[2]);
	}
 	else if(C4==0)
	{
		 while(C4==0);
		 SMG_show(duanma[3]);
	}
	R2=0;
	R1=R3=R4=1;
	C1=C2=C3=C4=1;
	if(C1==0)
	{
		 while(C1==0);
		 SMG_show(duanma[4]);
	}
  	else if(C2==0)
	{
		 while(C2==0);
		 SMG_show(duanma[5]);
	}
 	else if(C3==0)
	{
		 while(C3==0);
		 SMG_show(duanma[6]);
	}
 	else if(C4==0)
	{
		 while(C4==0);
		 SMG_show(duanma[7]);
	}
	R3=0;
	R1=R2=R4=1;
	C1=C2=C3=C4=1;
	if(C1==0)
	{
		 while(C1==0);
		 SMG_show(duanma[8]);
	}
  	else if(C2==0)
	{
		 while(C2==0);
		 SMG_show(duanma[9]);
	}
 	else if(C3==0)
	{
		 while(C3==0);
		 SMG_show(duanma[10]);
	}
 	else if(C4==0)
	{
		 while(C4==0);
		 SMG_show(duanma[11]);
	}
	R4=0;
	R1=R2=R3=1;
	C1=C2=C3=C4=1;
	if(C1==0)
	{
		 while(C1==0);
		 SMG_show(duanma[12]);
	}
  	else if(C2==0)
	{
		 while(C2==0);
		 SMG_show(duanma[13]);
	}
 	else if(C3==0)
	{
		 while(C3==0);
		 SMG_show(duanma[14]);
	}
 	else if(C4==0)
	{
		 while(C4==0);
		 SMG_show(duanma[15]);
	}
 }
  
void main()
 {
  P2=0xA0;P0=0x00;P2=0x80;P0=0xFF;//关闭外设
  while(1)
  {
 	 keyshow();
  }
 }

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值