A keypad scanning program is common for most of micro-controller programming students. It usually done by the Assembly language programming in a micro-processor class in university. However using C compiler to program the keypad scanning process is very easy, and it's almost readable for most C programmers.
Simulating Program |
Using a single 8-bit I/O port can make a 4x4 (16 keys) matrix keypad. It's divided into two nibbles, one nibble for output and another nibble for input data.
Arduino 4x4 Matrix Keypad Module |
In this example, I use a PIC16F887 micro-controller to scan a 4x4 matrix keypad. Input key will show on a 16x2 character LCD.
/* * File: main.c * Author: Admin * * Created on January 16, 2024, 7:46 PM */ #include <xc.h> #include "config.h" #include "LCD4Bits.h" #define _XTAL_FREQ 8000000UL uint8_t key_16[][4]={'7','8','9','F', '4','5','6','E', '1','2','3','D', 'A','0','B','C'}; uint8_t scanKey(void){ char data=0,temp; for(uint8_t i=0;i<4;i++){ PORTB=1<<i; data=PORTB&0xF0; if(data&(1<<4)) {temp=key_16[i][0]; break;} else if(data&(1<<5)){temp=key_16[i][1]; break;} else if(data&(1<<6)){temp=key_16[i][2]; break;} else if(data&(1<<7)){temp=key_16[i][3]; break;} else temp=0; __delay_ms(10); } return temp; } void main(void) { OSCCONbits.IRCF=7; uint8_t temp,count=0,row=0; PORTB=0; TRISB=0xF0; ANSELH=0; lcdInit(); while(1){ temp=scanKey(); if(temp!=0){ lcdData(temp); count++; __delay_ms(250); } if(count>16){count=0; lcdCommand(0xC0); row+=1;} if(row>=2) { count=0; lcdXY(1,1); lcdCommand(0x01); __delay_ms(10); row=0; } } return; }
After a 16 key-press count, a new line will start. After two lines, the display will clear, and it will return home.
Click here to download this example from GitHub. See also,
No comments:
Post a Comment