51单片机——按键操作

2022-12-14  

在51单片机开发板上,对按键设置进行操作,其中包括按键的按下,显示对应位置,以及按键密码锁


1.按下按键显示对应位置

main.c

#include

#include "Delay.h"

#include "LCD1602.h"

#include "MatrixKey.h"

unsigned char KeyNum;


void main()

{

LCD_Init();

LCD_ShowString(1,1,"helloworld");

while(1)

{

KeyNum=MatrixKey();

if(KeyNum)

{

LCD_ShowNum(2,1,KeyNum,2);

}

}

}

Delay.c

void Delay(unsigned int xms)

{

unsigned char i, j;

while(xms--)

{

i = 2;

j = 239;

do

{

while (--j);

} while (--i);

}

}


Delay.h

#ifndef __DELAY_H__

#define __DELAY_H__


void Delay(unsigned int xms);


#endif

LCD1640.c

#include


//引脚配置:

sbit LCD_RS=P2^6;

sbit LCD_RW=P2^5;

sbit LCD_EN=P2^7;

#define LCD_DataPort P0


//函数定义:

/**

  * @brief  LCD1602延时函数,12MHz调用可延时1ms

  * @param  无

  * @retval 无

  */

void LCD_Delay()

{

unsigned char i, j;


i = 2;

j = 239;

do

{

while (--j);

} while (--i);

}


/**

  * @brief  LCD1602写命令

  * @param  Command 要写入的命令

  * @retval 无

  */

void LCD_WriteCommand(unsigned char Command)

{

LCD_RS=0;

LCD_RW=0;

LCD_DataPort=Command;

LCD_EN=1;

LCD_Delay();

LCD_EN=0;

LCD_Delay();

}


/**

  * @brief  LCD1602写数据

  * @param  Data 要写入的数据

  * @retval 无

  */

void LCD_WriteData(unsigned char Data)

{

LCD_RS=1;

LCD_RW=0;

LCD_DataPort=Data;

LCD_EN=1;

LCD_Delay();

LCD_EN=0;

LCD_Delay();

}


/**

  * @brief  LCD1602设置光标位置

  * @param  Line 行位置,范围:1~2

  * @param  Column 列位置,范围:1~16

  * @retval 无

  */

void LCD_SetCursor(unsigned char Line,unsigned char Column)

{

if(Line==1)

{

LCD_WriteCommand(0x80|(Column-1));

}

else if(Line==2)

{

LCD_WriteCommand(0x80|(Column-1+0x40));

}

}


/**

  * @brief  LCD1602初始化函数

  * @param  无

  * @retval 无

  */

void LCD_Init()

{

LCD_WriteCommand(0x38);//八位数据接口,两行显示,5*7点阵

LCD_WriteCommand(0x0c);//显示开,光标关,闪烁关

LCD_WriteCommand(0x06);//数据读写操作后,光标自动加一,画面不动

LCD_WriteCommand(0x01);//光标复位,清屏

}


/**

  * @brief  在LCD1602指定位置上显示一个字符

  * @param  Line 行位置,范围:1~2

  * @param  Column 列位置,范围:1~16

  * @param  Char 要显示的字符

  * @retval 无

  */

void LCD_ShowChar(unsigned char Line,unsigned char Column,char Char)

{

LCD_SetCursor(Line,Column);

LCD_WriteData(Char);

}


/**

  * @brief  在LCD1602指定位置开始显示所给字符串

  * @param  Line 起始行位置,范围:1~2

  * @param  Column 起始列位置,范围:1~16

  * @param  String 要显示的字符串

  * @retval 无

  */

void LCD_ShowString(unsigned char Line,unsigned char Column,char *String)

{

unsigned char i;

LCD_SetCursor(Line,Column);

for(i=0;String[i]!='

文章来源于:电子工程世界    原文链接
本站所有转载文章系出于传递更多信息之目的,且明确注明来源,不希望被转载的媒体或个人可与我们联系,我们将立即进行删除处理。