AVR4x4矩阵键盘驱动

单片机
2018-10-24 18:00
关键字: 4x4 AVR 矩阵键盘 驱动
收藏

#include

#include

#include "key.h"

#include "1602.h"

#include "delay.h"


unsigned char display[3]={0,0,0};//显示数据

void main(void)


{ unsigned char Key;

LCD_init();

delay_nms(50);

while(1)

{

Key = keyboard_Scan(); // 键盘扫描

display[1]=Key/100%10+0x30;

display[2]=Key/10%10+0x30;

display[3]=Key%10+0x30;

LCD_write_char(5,0,display[1]);

LCD_write_char(6,0,display[2]);

LCD_write_char(7,0,display[3]);

delay_nms(50);

//switch(Key)

// {

// case 0:

// break;


// default:

// break;

//}

}

}


//key.h


#ifndef _4X4_H_

#define _4X4_H_


#define No_key 255


#define key_port PORTB

#define key_port_ddr DDRB

#define key_port_pin PINB



unsigned char keyboard_Scan(void);


#endif


//key.c


#include

#include

#include "key.h"


const unsigned char key_table[16] =

{

1, 2, 3,12,

4, 5, 6,13,

7, 8, 9,14,

10,0,11,15,

};



//4x4矩阵键盘扫描函数


unsigned char keyboard_Scan(void)

{

unsigned char temp,key,row,Column;


key_port_ddr = 0b00001111;// 高四位输入行线/低四位输出列线

key_port = 0b11110000;// 高四位打开上拉电阻/低四位输出低电平

delay_nus(5);// 延时5us

if((key_port_pin & 0xF0)!= 0xF0) // 作初检查有否键按下,没有,就返回

{ // 如果行线不全为1,可能有键按下

delay_nms(5);// 延时去抖动


//设置列线初始值3~0=1110

for(Column=0,key_port=0b11111110;Column<4;Column++)

{

for(row=0,temp=0b11101111;row<4;row++)// 设置行线初始值7~4=1110

{

while((key_port_pin & 0xF0)==(temp & 0xF0))// 输入行线,查看这行有否键按下

{

key=4*row+Column;// 键编码=4*行输入值+列扫描值

key=key_table[key];// 键盘编码转换键值

return (key);

}

temp<<=1;// 行线左移1位

}

key_port=((key_port<<1)|0x01);// 列线扫描值左移1位,扫描下一行

}

}

return (No_key);

}


相关推荐