Sei sulla pagina 1di 14

Zx Lee

Personal Blog on Electronics and Programming

4×4 Matrix Keypad

Tired of using normal push bu ons as input to your system? You should consider including a matrix keypad. Matrix keypad is widely use in our
daily life. Often, matrix keypad is available in 3×4 or 4×4. For your information, matrix keypad is a good substitution to normal push bu on.
Matrix keypad offers more input to the microcontroller with lesser I/O pins required as compared to bu ons. Consider your system needs 16
inputs, you requires only 8 I/O pins with keypad instead of 16 I/O pins. So you can actually use the extra 8 pins for other functions.

Membrane type 4×4 Matrix


Keypad

4×4 Matrix Keypad

Still unclear? Let us look at how a 4×4 matrix keypad works.


Mapping of bu ons with rows and
columns

A 4×4 matrix keypads consists of 4 rows and 4 columns. This is roughly how the keypads looks like:

There is a switch connecting each row and column. So the combinations of rows and columns makes up the 16 inputs.

So, try to imagine this. Initially all the switch are open (not connected). When you pressed either one bu ons, the switch is now closed
(connected). As you can see, now there is a connection between the row and column.

Okay, now we know how a matrix keypad works, but how do we relate it with our microcontroller? So we connect the first 4 pins to the column
as INPUT. The other 4 pins is connected to the row as OUTPUT. The input meant that is the input to the microcontroller while output is the
output from the microcontroller. Note that the input to the microcontroller has to connect to pull high resistor, or you can use the internal pull up
from Arduino itself.

Here comes the magic, the microcontroller send LOW to each row one at a time and check whether there is a LOW signal detected on the
column. If there is no bu on pressed, the microcontroller will scan for the next row and read for LOW signal. Since the column is pull HIGH
internally, so no bu on pressed would return 1 to the microcontroller. When you pressed one of the bu on, now the row and column are
connected. The 0 from row would make the column return a 0 to microcontroller.

With the row and column, you can know which bu on you are pressing. Amazing.

Since the connections of a keypad is quite easy, I have actually made myself a DIY keypad with DIY PCB method instead of purchasing one.
Now let us look on how to interface with the hardware before moving on the the software part. For a 4×4 matrix keypad, usually it has 8 pins on
it. How do we know which pins are associate to which rows and columns? A digital multimeter (DMM) would ease your job.

Turn your DMM to connectivity mode. Now put one of your meter probe to the first pin and the other one to the fifth pin. Try to press the bu on
and see which bu on would gives you the “beep” sound. Next, try to probe to the sixth pin and press other bu on. Keep trying and you would
understand the connection behind the keypad.

Finally we have reached to the software part. To use a keypad with Arduino, its pre y simple with the help of Keypad.h library. You can
download the library at here.

Note that when you are using this library, you don’t need to connect any external resistor as it has been internally pull high in Arduino.

Hardware connection with Arduino:

Example code:

1 #include <Keypad.h>
2
3 char keys[4][4]={
4 {'1','2','3','A'},
5 {'4','5','6','B'},
6 {'7','8','9','C'},
7 {'*','0','#','D'}};
8
9 byte rowPin[4]={5,6,7,8};
10 byte colPin[4]={9,10,11,12};
11
12 Keypad keypad=Keypad(makeKeymap(keys),rowPin,colPin,4,4);
13
14 void setup()
15 {
16 Serial.begin(9600);
17 }
18
19 void loop()
20 {
21 char pressed=keypad.getKey();
22 if(pressed)
23 {
24 Serial.println(pressed);
25 }
26 }

Code explanation:

char keys[no_of_row][no_of_col]
– Define the keymap

byte rowPin[no_of_row]={pins}

– connect keypad row pins to the defined pins in {}

byte colPin[no_of_col]={pins}

– connect keypad column pins to the defined pins in {}

Keypad keypad=Keypad(makeKeymap(keys),rowPin,colPin,no_of_row,no_of_col)

– create the keypad

keypad.getKey()

– check for the bu on pressed and return as define in keymap

Video demonstration:

4x4 Matrix Keypad

Reference:

PCB Heaven, How Key Matrices Works

Advertisements

REPORT THIS AD

REPORT THIS AD

zxlee
July 24, 2013
Arduino, Tutorial

Arduino, Do it yourself, Input/output, Keypad, Microcontroller, Printed circuit board, Push-bu on

5 thoughts on “4×4 Matrix Keypad”

1. Vick
July 24, 2013 at 12:21 pm

Good job ! Gonan learn this ! Thanks for the guide

zxlee
July 24, 2013 at 1:38 pm

Nice, hope to see a project from you using keypad soon

2. paulsin
June 27, 2015 at 12:10 pm

I have made a simple technique to connect an 4*4 bu on pad to arduino using four digital pins of arduino instead of 8. Read more at :

h p://www.haberocean.com/2015/05/circuit-for-44-bu on-keypad-using-74165-and-74595-part-1/

zxlee
June 27, 2015 at 9:53 pm

Never seen this method before, but it is nice that it is able to reduce the pin counts. Thumbs up to you.

3. Selling
May 23, 2016 at 11:34 pm

I ɦave гead a fеᴡ excedllent stuff ɦere. Definiktely vaⅼue boomarking


for revisiting. ӏ surprise һow mսch a empt you plaϲе to creatе thіs sort of magnificent informative website.

BLOG AT WORDPRESS.COM.

UP ↑

REPORT THIS AD
Basic Circuit Eliminates Numeric Keypad Polling http://electronicdesign.com/print/components/basic-circuit-eliminates-n...

print | close

Electronic Design
Rick Mally, Independent Designs LLC
Mon, 2014-10-20 12:16

Using eight digital inputs, this circuit simplifies decoding of the common membrane 4x4
keypad matrix and eliminates the traditional requirement of scanning rows or columns.
Any X-Y switch matrix, which can be part of some apparatus, can be considered with this
device.

The design uses eight pre-biased transistors—four NPN and four PNP. When depressing
a given switch, two transistors will turn on via the current through their internal biasing
networks, providing a unique signature code that can be recognized and decoded. The
generated code, which will be unique for each key, is readable with a simple 8-bit input
statement. By enabling a pin-change interrupt on all eight inputs, the keyboard decode program can be entirely
interrupt-driven.

The eight lines could also be connected to a shift register, thereby only requiring two to three digital I/O lines
for the microprocessor to shift out and read the result.

In the simplest setup, an 8-bit port is configured as inputs, with internal pull-up resistors on bits 0-3 and
internal pull-down resistors on bits 4-7 (Fig. 1). This is possible with several microprocessors, including
STMicroelectronics’ STM32F100. In fact, this circuit was prototyped with the STM32F100, and wound up
delivering excellent results.

1 of 2 10/20/2014 2:00 PM
Basic Circuit Eliminates Numeric Keypad Polling http://electronicdesign.com/print/components/basic-circuit-eliminates-n...

Related

Button Replacement Enables Complete Matrix Keypad Solution

Function Generator Line Expands to Add Keypads and Displays

One-Pin Keypad Interface Conserves Battery Power

The design in Figure 2 employs external pull-up and pull-down resistors. The best solution implements two
resistor arrays, such as the widely available four-element surface-mount types—they’re compact, inexpensive,
and add only two components to the circuit board. For most pull-up and pull-down applications, 10 kΩ will
suffice.

Of course, several combinations are possible when simultaneously pressing two keys, also leading to the
generation of unique codes. This scenario works as well—any combination in which the two keys don’t share a
common row or column can be decoded.

Rick Mally, sole proprietor of Independent Designs, a small-scale custom electronic design and prototyping
firm for clients with a limited budget was home-schooled and self-educated in the electronics field.

Source URL: http://electronicdesign.com/components/basic-circuit-eliminates-numeric-keypad-polling

2 of 2 10/20/2014 2:00 PM
LEARN.PARALLAX.COM Search

Read
Read aa 4x4
4x4 Matrix
Matrix Keypad
Keypad
A matrix keypad is the kind of keypad you see on microwave ovens, gas pumps, and calculators. A matrix keypad you can connect to a breadboard is also great for
prototypes and inven ons where things like codes, mes, or other values have to be entered.

Parts

(1) 4x4 Matrix Membrane Keypad (h ps://www.parallax.com/product/27899)


(4) Resistors - 1 kΩ (brown-black-red)
(4) Jumper Wires

Circuit

Note: Be careful when making your 4x4 Keypad connec ons. The FLiP and ABWX diagrams below use the same
pins, but the orienta on of your circuit and keypad differs depending on which board you use.
Test Code
The test program updates the Terminal showing whichever single key is pressed, every 1.5 s. If you're not pressing a key when it checks, the program will display
-1. So, for best results, press and hold the key you want to try. Keep in mind, this is just test code. The Try This and Your Turn examples will demonstrate how to
make it responsive as you type in numbers, how to do simple mathema c func ons, and more.

Before running the program, let's add the matrix keypad examples and library to your Learn folder.

Download Matrix Keypad Library and Examples 1_1_6.zipside (/sites/default/files/content/propeller-c-tutorials/simple-


devices/MatrixKeypad/Matrix%20Keypad%20Library%20and%20Examples%201_1_6.zipside)

In SimpleIDE, click Tools and select Update Workspace.

Click Browse, and then find/select Matrix Keypad Library and Examples 1_1_6.zipside.

Click Open and wait for SimpleIDE to update the workspace.

Now, you're ready to try the first example program

Click SimpleIDE's Open Project bu on, and open Keypad 4x4 Read Keys.side from ...Documents/SimpleIDE/Learn/Examples/Devices/Interface/.

Make sure your board has power, and the COM port is correctly set.

Use SimpleIDE's Run with Terminal bu on.

When the SimpleIDE terminal appears and starts displaying "Key = -1", try pressing and holding various bu ons and verify that the program detects and
displays the bu on you press.

How it Works
This 4x4 matrix keypad has 16 built-in pushbu on contacts connected to row and column lines. A microcontroller can scan these lines for a bu on-pressed state.
In the keypad library, the Propeller sets all the column lines to input, and all the row lines to input. Then, it picks a row and sets it high. A er that, it checks the
column lines one at a me. If the column connec on stays low, the bu on on the row has not been pressed. If it goes high, the microcontroller knows which row
(the one it set high), and which column, (the one that was detected high when checked). See the schema c in the "Circuit" sec on, above, for a visual reference of
the keypad layout.

The keypad library supports pre y much any number of rows and columns. So, the program has to tell it our keypad is has 4 rows and 4 columns, which I/O pins
the lines are connected to, and what value each bu on represents. The rows, cols, and values arrays store that informa on. The rows array will be used to
tell the keypad library that the top row is connected to P7, the second row to P6 and so on. Likewise, the cols array lists the le most column as connected to P3,
the next over connected to P2 and so on. The values array stores the value we want the program to give us for each bu on press. For example, if the top-le
bu on is pressed, we want the number 1, and if the next one over is pressed, we want the number two. If the top right bu on is pressed, we want the ASCII code
for the 'A' character, which is 65.

Inside the main func on, keypad_setup gets the number of rows (4), the number of columns (also 4), the rows array, the cols array, and the values
array. A er that, key = keypad_read() will return -1 if no bu ons are pressed. If a bu on is pressed, it will return the value from the array that
corresponds to that bu on. For example, if you press a bu on on the 3rd row, second column, the keypad_read func on will return the number 8, which will
get stored in the key variable. To display it correctly, an if statement checks for values less than or equal to 9, and displays them with %d, decimal-integer
forma ng flag . The ASCII codes for '*', '#', 'A', 'B', 'C', and 'D' are 35, 42, 65, 66, 67, and 68, all of which are above 9, and get displayed with the print statement
that uses the %c character forma ng flag.

/*
Keypad 4x4 Read Keys.c
Demonstrates how to read individual key presses with the keypad library.
*/

#include "simpletools.h" // Libraries simpletools & keypad


#include "keypad.h"

int rows[4] = {7, 6, 5, 4}; // Row I/O pins (top to bottom)


int cols[4] = {3, 2, 1, 0}; // Column I/O pins (left to right)

int values[16] = { 1, 2, 3, 'A', // Values for each key in the 4x4


4, 5, 6, 'B',
7, 8, 9, 'C',
'*', 0, '#', 'D' };

int key; // Variable stores keypad key

int main() // Main function


{
keypad_setup(4, 4, rows, cols, values); // Setup dimensions, keypad arrays

while(1) // Main loop


{
key = keypad_read(); // Get pressed key (or -1 for none)

if(key <= 9) // Display key value


print("key = %d\r", key); // If <= 9, dispaly as decimal
else
print("key = %c\r", key); // Otherwise, display as character
pause(1500); // Wait 1.5 s before repeat
}
}

Did You Know?


If you want the Propeller to rememeber a value 123 when a er you press the 1, 2, and 3 bu ons, here's how it works:

1. When the 1 is pressed add it to a variable (we'll use the number variable).
2. Wait for the 1 bu on to be released.
3. When 2 is pressed, muliply number by 10, then add 2.
4. Wait for the 2 bu on to be released.
5. When 3 is pressed, muliply number (which holds 12) by 10, and add 3.
6. Wait for the 3 bu on to be released.
7. If the bu on is pressed that signals you're done typing digits, save or display the value.

Try This
This example program allows you to press/release digits to build numbers. For example, if you press and release 1, then 2, then 3, then #, the program will display
"You entered 123". Keep in mind that it's not just rememebering the digits 1, 2, and 3, it's crea ng the number 123 by mul plying what's already in the number
variable by 10, and then adding the most recently pressed digit. Once the Propeller has this value, it could be used as a count-down mer in an oven, or the first
value used in a calculator opera on.

/*
Keypad 4x4 Digits to Numbers.c
Demonstrates how to build numbers with multiple key presses.
*/

#include "simpletools.h" // Libraries simpletools & keypad


#include "keypad.h"

int rows[4] = {7, 6, 5, 4}; // Row I/O pins (top to bottom)


int cols[4] = {3, 2, 1, 0}; // Column I/O pins (left to right)

int values[16] = { 1, 2, 3, 'A', // Values for each key in the 4x4


4, 5, 6, 'B',
7, 8, 9, 'C',
'*', 0, '#', 'D' };

int number = 0; // Stores number result

int main() // Main function


{
keypad_setup(4, 4, rows, cols, values); // Setup dimensions, keypad arrays

print("Type a number, then press #\r"); // User prompt

while(1) // Main loop


{
number = keypad_getNumber(); // Get number entered on keypad

print("\r"); // Next line


print("You entered %d\r", number); // Display result
}
}

Your Turn

The ...Documents/SimpleIDE/Learn/Examples/Devices/Interface/ folder also has a calculator example that uses the A bu on to add two numbers, and
the B bu on to subtract. Try modifying this program for mul ply with C and divide with D.

The ...Documents/SimpleIDE/Learn/Examples/Devices/Interface/ folder also has a countdown mer. Try adding a piezospeaker and make the speaker
beep when you press each number. This is the same kind of auditory feedback microwave ovens use.

Advanced Topic

Try opening the 4x4 Keypad Read Simultaneous Keys example.

Try pressing any two keys, they should both display.

However, when you start pressing 3 keys at a me, a keypad like the 4x4 Matrix Membrane, which is designed for individual key presess will some mes display as
if a key was pressed that was not actually pressed.

Many combina ons work fine, like 1, 5, 9, and D will all display correctly, as will 1, 4, 7, and *. But, try pressing 1, 2, and 7. The program will tell you that detected
1, 2, 7, and 8. This phenomenon is called ghos ng, with the number 8 being the ghost number. Ghos ng happens when you press 2 bu ons on the same row,
and one bu on on the same column. For example, 1 and 2 are on the same row, and 7 is on the same column as 1. The 7 press travels up to 1, across to 2, and
then down the 8 column and is detected there. Some keypads that are designed for mul ple, simultaneous key presses have built-in diodes that can prevent
this.

Another problem with keypads that are designed for indivdual key presses is called masking. Masking just means that if your program is wai ng for a single key
press, and you then press and release a second key a er the first, the second key is not detected. The change is "masked out" by the keypad circuit.
LEARN.PARALLAX.COM Search

RFID
RFID Reader
Reader
RFID stands for Radio Frequency Iden fica on. The Parallax RFID Reader Serial + Tag Sampler includes several unique RFID tags. This tutorial will show you how
connect the RFID Card Reader to the Propeller microcontroller. Then, it will show you how to read a tag’s ID number and use that data in a program.

Circuit
In addi on to 5V and ground, the RFID Card Reader – Serial requires two Propeller I/O pin connec ons. P2 will be set to output, to set the RFID Reader’s Enable
pin. P1 will be set to input, to read the serial data coming from the RFID Reader. A 2.2 k-ohm resistor is used for this connec on since the reader outputs a 5 V
signal and the Propeller chip is a 3.3 V device.

Parts

(1) RFID Card Reader – Serial (#32390) (h p://www.parallax.com/product/32390)


(2) RFID Tags (included with #32390)
(1) 2.2 k-ohm resistor (red-red-red)
(4) Jumper wires

Build the RFID Reader circuit following the wiring diagram and schema c below.

This circuit and test code will work with any Propeller development board that has a prototyping area.

Test Code

Library Alert! This example code and library requires the Learn folder released 5/15/2014 or later. Update your
Learn Library (/propeller-c-set-simpleide/update-your-learn-folder).

Click SimpleIDE’s Open Project bu on.

Open RFID Read.side from ...Documents\SimpleIDE\Learn\Examples\Devices\Sensor\RFID Serial

Click the Run with Terminal bu on.

Hold each RFID tag near the RFID Reader.

Each tag’s ID number should appear in the SimpleIDE Terminal. If no tag is detected within one second, you will see “ med out” un l a tag is detected.
How it Works
First, the program includes the simpletools and rfidser libraries. The rfidser library gives us access to the rfid_open and rfid_get func ons, along with other
conveniences for communica ng with the RFID reader.

#include "simpletools.h" // Include simpletools


#include "rfidser.h" // Include rfidser

Next, the program declares two int values, giving names to the two Propeller I/O pins that are connected to the RFID Reader. Later, these names will be passed
to parameters in a func on call.

int rfidEn = 2; // Reader /ENABLE pin to P2


int rfidSout = 1; // Reader SOUT pin to P1

The next line creates a device iden fier for the RFID reader; we named it rfid. The device iden fier is a nickname for a memory structure being set aside to
store informa on about this par cular RFID reader connec on. If you are using more than one RFID reader in your project, you would give each one its own
iden fier using rfider *nickname.

rfidser *rfid; // Set up device ID

Inside the main rou ne, the rfid_open func on call starts the RFID card reading process in another cog. No ce that the I/O pin names declared above are
passed to the rfid_open func on’s parameters. The func on returns informa on that gets stored in the memory structure we nicknamed rfid. Now, rfid
is ready to use with other func on calls.

int main() // Main function


{
rfid = rfid_open(rfidSout, rfidEn); // Open reader, start reading

The last two lines are inside an infinite while loop. The first line gets the tag ID from the reader (if one is detected) and the second line prints the tag ID in the
SimpleIDE Terminal.

while(1) // Main loop


{
char *str = rfid_get(rfid, 1000); // Wait up to 1 s for card
print("id = %s.\n", str); // Print ID.
}
}

Let’s look closer at those two lines. The func on call rfid_get(rfid, 1000) is listening to the device we named rfid for 1000 ms. This func on returns
the tag’s ID number if one is present, or the phrase “ med out” if no ID number is received within 1000 ms. On the other side of the equal sign, char *str
names a pointer to a place in Propeller memory to start storing the characters returned by the func on call.

The print func on call uses the %s forma er to display str. This forma er will print a character string stored in memory, star ng at the address named str.
The character string will display as a tag ID or the phrase “ med out” on a new line each me through the loop.

Did You Know?


Passive Tags — These tags are passive, meaning they do not have a power source of their own inside. Instead, an embedded antenna circuit inside the tag gathers
a ny bit of power from a magne c field generated by the Reader. Holding the Reader close to the tag powers it just enough to send its ID number back to the
Reader.

Keep it In the Family — The Parallax RFID Card Reader works with the EM4100 family of read-only tags. This reader will not work with tags from other families,
nor can it write data to RFID tags.

Try This
When RFID tags are used in access systems, the usual goal is to find out if a tag’s ID is known to the system, so the appropriate ac on can be taken. The next
example program uses if...then...else to take a different ac ons based on a tag’s ID. First, you will need to write down your tags’ ID numbers.

Label your tags “A” and “B.”

Click SimpleIDE’s Open Project bu on.

Open RFID Read and Compare.side from ...Documents\SimpleIDE\Learn\Examples\Devices\Sensor\RFID Serial.

Click Run with Terminal, and then hold a tag up to the reader. You should see the message “Unknown ID” followed by the tag’s number.
Click the Disable bu on in the SimpleIDE Terminal, then write down the tag’s ID number.

Now, update the lines shown below with the ID numbers from your own tags.

Click Run with Terminal again. The Serial Terminal should now recognize each tag. If it doesn’t, re-check your typing and try again!

Your Turn
Now that the program recognizes both tag IDs and takes separate ac ons for each, you can modify those ac ons to make the applica on more interes ng. The
rfidser library has an rfid_disable func on that will make the RFID reader ignore tags un l you either re-run the program or call the rfid_enable
func on. Let’s modify the program to go into lock-down if Tag B is detected.

A er the second else...if statement, replace the print statement with break;

Below the closing bracket of the while(1) block, add these two lines:

Rfid_disable;
Print(“Banned user detected – system in lockdown.\n”);

Now re-run the program. Try Tag A to make sure the reader is s ll reading. Then try Tag B. Does it stop the whole show?

Disable vs Close, Enable vs Open. rfid_disable does not shut down the Propeller core running the RFID
reading process that was launched with rfid_open. Reading can resume with rfid_enable. If you want
your applica on to stop reading tags and also free up the Propeller core and memory that it is using, shut down
the process en rely with rfid_close. If your project needed to read tags again a er that, your program would
need to call rfid_open to re-start the RFID reading process again in another core.

Potrebbero piacerti anche