AN3407 Matrix Keypad With ATTINY
AN3407 Matrix Keypad With ATTINY
Features
Introduction
This application note shows how a general keypad application can be implemented with tinyAVR® and megaAVR®
devices. A conceptual overview of the operation of a matrix keypad and two demo applications are presented. One
demo shows a simple implementation of a keypad, while the second demo uses more advanced features to make the
application more efficient and use less power.
The examples in this application note may easily be changed to interface a smaller or larger matrix keypad, and are
easy to implement into another application. The application may be used in all implementations using a matrix
keypad, such as access control keypads, keyboards, or remote controls.
The code examples are available through Atmel START:
• Using Matrix Keypad with AVR Devices - Basic
– https://start.atmel.com/#example/Atmel%3AApplication_AVR_Examples%3A1.0.0%3A%3AApplication
%3AUsing_Matrix_Keypad_with_AVR_Devices_-_Basic%3A
• Using Matrix Keypad with AVR Devices - Advanced
– https://start.atmel.com/#example/Atmel%3AApplication_AVR_Examples%3A1.0.0%3A%3AApplication
%3AUsing_Matrix_Keypad_with_AVR_Devices_-_Advanced%3A
The code examples are also available through GitHub:
Table of Contents
Features......................................................................................................................................................... 1
Introduction.....................................................................................................................................................1
1. Block Diagram.........................................................................................................................................3
2. Theory of Operation................................................................................................................................ 4
3. Demo Operation......................................................................................................................................7
3.1. Hardware Prerequisites................................................................................................................7
3.2. Software Prerequisites................................................................................................................. 7
3.3. Running the Example................................................................................................................... 7
5. Power Consumption..............................................................................................................................16
5.1. Basic Operation..........................................................................................................................16
5.2. Advanced Operation...................................................................................................................16
5.3. Plotting Current Data..................................................................................................................17
8. Revision History.................................................................................................................................... 22
Customer Support........................................................................................................................................ 23
Legal Notice................................................................................................................................................. 23
Trademarks.................................................................................................................................................. 24
1. Block Diagram
The block diagram below shows an overview of the advanced application example using a 4x4 keypad with the
ATtiny1627 Curiosity Nano development board. It shows how the application interacts with the peripherals and CPU
of the tinyAVR® 2 device. The keypad and LEDs may be connected to any of the General Purpose Input/Output
(GPIO) pins, but in this example, they are connected physically in a row on the ATtiny1627 Curiosity Nano to simplify
connection.
Figure 1-1. Block Diagram
®
AVR Microcontroller
PB3
RED LED VCC
GREEN LED PB2 Pin Change
Interrupt
CPU
Configure
1 2 3 A PA1 PORT
PIT interrupt
Configure
and Start
PA2
PB1
4 5 6 B PB0
RTC
PC2
7 8 9 C PC1
PC0
PC3
* 0 # D
2. Theory of Operation
Matrix keypads consist of a grid of buttons with corresponding wires that may be read and interpreted by a
microcontroller. As the figure below shows, the number of pins needed by the microcontroller is determined by the
number of rows and columns in the button grid, where one wire is needed per row and per column. When a button is
pressed, a connection between the corresponding row and column is created. This connection enables the keypad to
be interpreted by the microcontroller.
Figure 2-1. Matrix Keypad Schematics
COLUMN 0
ROW 0
4 5 6 B
ROW 1
R0
R1
R2
7 8 9 C R3
ROW 2 C3
C2
C1
C0
* 0 # D
ROW 3
There are multiple ways of scanning a matrix keypad. The simple method used in the example applications is
scanning one full axis (that is, the row or the column) at a time. This is done by setting up one of the axes to output a
known voltage level and reading the voltage level of the wires of the other axis to find out which wire was pulled to
that voltage. Figure 2-2 shows where the columns output 0V and the rows are connected to 3.3V through a pull-up
resistor. ROW 0 is shown to be pulled down to 0V because of a connection to the columns, so the pressed button
may therefore be assumed to be in ROW 0.
4 5 6 B
ROW 1
R0
R1
R2
7 8 9 C R3
ROW 2 C3
C2
C1
C0
* 0 # D
ROW 3
After the first axis has been scanned, the setup must be flipped to read the other axis. This is shown in Figure 2-3
where COLUMN 1 is shown to be pulled down to 0V because of a connection to the rows, so the pressed button may
therefore be assumed to be in COLUMN 1.
Figure 2-3. Column Scan
COLUMN COLUMN COLUMN COLUMN
0 1 2 3 3.3V
1 2 3 A
ROW 0
0V
4 5 6 B
ROW 1
R0
R1
R2
7 8 9 C R3
ROW 2 C3
C2
C1
C0
* 0 # D
ROW 3
When both axes have been scanned, the coordinates of the pressed button in the grid are known, and the button
press may be recorded and acted upon. In this example, since ROW 0 and COLUMN 1 are known to include the
pressed button, it is understood that button 2 is pressed.
Although this method is simple, the problem with it is that it can only handle one simultaneous button press at a time.
Figure 2-4 shows which wires are pulled low when each of the axes are pulled low. As shown in the figure, ROW 1
and 2 and COLUMN 1 and 2 are pressed, leading to four buttons being recorded while only two buttons are really
pressed. This effect is called ghosting.
3.3V
Pressed
button
Columns pulled low 0V Rows pulled low
4 5 6 B 4 5 6 B
ROW 1 ROW 1
R0 R0
R1 R1
R2 R2
7 8 9 C R3 7 8 9 C R3
ROW 2 C3 ROW 2 C3
C2 C2
C1 C1
C0 C0
* 0 # D * 0 # D
ROW 3 ROW 3
Another method is to pull the axis low one wire at a time, reading all the pins on the other axis for each time to find
the intersections. This is shown in the figure below, where ROW 0 is driven low, and COLUMN 1 and COLUMN 2 are
pulled low by buttons 2 and 3 being pressed. The advantage of this method is the ability to read two button presses
at a time, while the disadvantage is that it may add complexity to the application.
Figure 2-5. Single Axis Scan
COLUMN COLUMN COLUMN COLUMN
0 1 2 3 3.3V
1 2 3 A
ROW 0
0V
4 5 6 B
ROW 1
R0
R1
R2
7 8 9 C R3
ROW 2 C3
C2
C1
C0
* 0 # D
ROW 3
3. Demo Operation
In these demo applications, a keypad is connected to the ATtiny1627 Curiosity Nano development board to show
how an access code can be read and checked for validity. The pin code is written by pressing the alphanumerical
buttons on the keypad, reset by pressing star (*), and check for validity by pressing pound (#). The green LED flashes
when the pin is valid and the red LED flashes if the code is incorrect. The red LED also flashes if the preset maximum
number of characters (20) is reached.
Two demos are presented where one, the basic keypad example, implements the above functionality in the simplest
way possible. It is presented to create an understanding of how the keypad works and how one may interface with it.
The other demo, the advanced keypad example, implements more advanced features of the tinyAVR® device to
improve the efficiency of the application in various ways.
System Initiation
fCPU: 3.33 MHz, GPIO init
YES
10 ms Delay
YES
scan_keys()
check_passcode()
YES
As shown in the figure, the device polls the column pins to see whether any of them have been pulled down because
of a connection to the row. If a connection is detected, the device busy-waits for 10 ms before checking the column
pins again. If one of the column pins are still pulled to the row voltage, the key press is considered valid. This
sequence is a simple implementation of a button debouncing technique.
When a valid key press has been detected, the functions scan_keys() and check_passcode() are run. The two
functions are discussed in the following sections.
When the key press has been properly handled by the two functions, the device polls for the button to be released.
This is done to prevent one press to be registered multiple times. When the button is released, the device returns to
polling for a new key press.
scan_keys()
NO NO NO
COLUMN 0? COLUMN 1? COLUMN 2? COLUMN 3?
Pin Invert
Rows Input, columns output
NO NO NO
ROW 0? ROW 1? ROW 2? ROW 3?
Pin Reset
Columns Input, rows output
return
The key_pressed variable is incremented by a value depending on which row is detected to contain the pushed
button. If, for example, button B is pressed, COLUMN 3 would be recorded first, with a value of 3 being stored into
the key_pressed variable. Then ROW 1 would be recorded, which would add 4 to the variable, giving the variable a
total of 7. Counting the buttons of the keypad left to right and top to bottom, button B (with a zero-indexed numbering
scheme) is button number 7.
After recording the button press, the pins are reset to the initial state with columns as inputs and rows as outputs.
check_passcode()
YES
Button pressed == *
NO
YES YES
Button pressed == # input_pass == passcode Green LED flashed
NO NO
Red LED flashed
NO
Add character to
input_pass
If the pound key is pressed and the input code matches the passcode, the green LED is flashed before the input code
is reset. If, on the other hand, the input code does not match, the red LED is flashed instead. If the star key is
pressed, the passcode is simply reset.
The application implements a fixed length input code of 20 characters. If the length is exceeded, it flashes the red
status LED twice and resets the input code.
4.2.1 Sleep
The most important low-power feature that is implemented in the advanced keypad application is putting the MCU to
sleep. tinyAVR and megaAVR devices have three available sleep modes. The sleep modes each turn off the clock for
different parts of the microcontroller to save power.
When designing an application that uses a sleep mode, one must consider which peripherals and clocks that need to
be awake while the CPU sleeps. If, for example, the Real-Time Counter (RTC) should keep track of time while the
CPU sleeps, one must select a sleep mode accordingly. Also, the sleep mode must be selected based on how the
CPU should wake from sleep. Some interrupt types are unable to wake the device in certain sleep modes.
Information regarding peripheral clocks and interrupts in different sleep modes can be found in the Sleep Controller
section in the device data sheet.
In the advanced keypad application, no peripheral is needed to be kept running between button presses. Therefore,
Power-Down Sleep mode is suitable. Looking at wake-up sources for this sleep mode, one can see that a pin change
interrupt will be able to wake the CPU. This is also suitable for the application since a pin change (that is, a button
press), is what the application is waiting for. It is important to note that some pin change interrupt types rely on a
clock signal to trigger. Since the relevant clock is turned off in Power-Down Sleep mode, an asynchronous
(independent of a clock signal) trigger must be chosen for the pin change interrupt. In the application, the
BOTHEDGES trigger (as described in Section 4.2.2 Interrupt Operation) is chosen.
Power-Down Sleep mode initialization is shown in the following code snippet:
The ATtiny1627 microcontroller used in this application example features a Real-Time Counter (RTC) which can keep
track of delays independent of the CPU. It can run on the internal 32.768 kHz RC oscillator, which means it will run in
any sleep mode. The RTC features a Periodic Interrupt Timer (PIT) which can interrupt the CPU from any sleep mode
after a set number of RTC clock cycles.
PIT initialization is shown in the code snippet below:
/* Set interrupt to fire every 32 RTC clock cycles and enable PIT */
RTC.PITCTRLA = RTC_PERIOD_CYC32_gc | RTC_PITEN_bm;
/* Enable PIT interrupts */
RTC.PITINTCTRL = RTC_PI_bm;
System Initiation
fCPU: 3.33 MHz, START init
Power-Down Sleep
btn_debounce()
PRESS_VALID == 1 NO
YES
scan_keys()
check_passcode()
YES
After wake up from sleep, the button press is debounced. This is performed by running a loop ten times, in which the
button is checked to be pressed as shown in the chart below. If the button is found to be pressed all ten times, the
button press is considered valid. If the button is not read as pressed while iterating through the loop, the validation
flag is cleared and the CPU exits the loop.
btn_debounce
Reset PRESS_VALID
flag in GPIOR0
for-loop i ≥ 10
lp_delay_ms(2) return
i = 0; i < 10; i++
i < 10
NO
Clear PRESS_VALID
flag in GPIOR0
break
The debounce function uses a 2-ms delay between the iterations of the loop. This delay is implemented using a timer
delay as shown in the figure below. The Periodic Interrupt Timer (PIT) is programmed to trigger an interrupt once
every millisecond. When the interrupt is triggered, a counter is incremented, and when this counter reaches the
desired number of microseconds, the CPU returns from the function.
lp_delay_ms(delay)
pit_cnt = 0
pit_cnt += 1
YES
return
The scan_keys() and check_passcode() functions are identical to those of the basic keypad example, except
that they use the low-power timer delay function when timing the LED indicators.
5. Power Consumption
In addition to using much power, unused pins are not handled correctly by enabling the internal pull up, which may be
seen in the instability of the power consumption. When touching the other pins of the device while measuring current,
one can clearly see that the results are affected.
When buttons are repeatedly pressed and scanned by the device as seen in the second figure, power consumption is
significantly higher than when the CPU is sleeping, but is still very low at ~30 µA on average and ~80 µA when
holding down a button.
Figure 5-4. Power Analysis, Advanced Operation With Key Press
DGI
TX<- host
CLK
USB
POWER DEBUGGER
PS LED
VBUS
NC
VOFF
ID
CDCRX
DBG3
DEBUGGER
CDCTX
DBG0
host USB
DBG1
GND
ATtiny1627
DBG2
VTG
CURIOSITY NANO
PA1
PB6
PA2
PB5
PB1
PB4
ATtiny1627
A A
PA3
PB0
PA4
PC2
PA5
PC1
PA6
PC0
PA7
PC3
GND
GND
GND
LED0
PB2
PC5
PB3
PC4
SW0
Download the code as a .zip file from the example page on GitHub by clicking the Clone or download button.
8. Revision History
Revision Date Description
A 06/2020 Initial document release
Customer Support
Users of Microchip products can receive assistance through several channels:
• Distributor or Representative
• Local Sales Office
• Embedded Solutions Engineer (ESE)
• Technical Support
Customers should contact their distributor, representative or ESE for support. Local sales offices are also available to
help customers. A listing of sales offices and locations is included in this document.
Technical support is available through the website at: www.microchip.com/support
Legal Notice
Information contained in this publication regarding device applications and the like is provided only for your
convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with
Trademarks
The Microchip name and logo, the Microchip logo, Adaptec, AnyRate, AVR, AVR logo, AVR Freaks, BesTime,
BitCloud, chipKIT, chipKIT logo, CryptoMemory, CryptoRF, dsPIC, FlashFlex, flexPWR, HELDO, IGLOO, JukeBlox,
KeeLoq, Kleer, LANCheck, LinkMD, maXStylus, maXTouch, MediaLB, megaAVR, Microsemi, Microsemi logo, MOST,
MOST logo, MPLAB, OptoLyzer, PackeTime, PIC, picoPower, PICSTART, PIC32 logo, PolarFire, Prochip Designer,
QTouch, SAM-BA, SenGenuity, SpyNIC, SST, SST Logo, SuperFlash, Symmetricom, SyncServer, Tachyon,
TempTrackr, TimeSource, tinyAVR, UNI/O, Vectron, and XMEGA are registered trademarks of Microchip Technology
Incorporated in the U.S.A. and other countries.
APT, ClockWorks, The Embedded Control Solutions Company, EtherSynch, FlashTec, Hyper Speed Control,
HyperLight Load, IntelliMOS, Libero, motorBench, mTouch, Powermite 3, Precision Edge, ProASIC, ProASIC Plus,
ProASIC Plus logo, Quiet-Wire, SmartFusion, SyncWorld, Temux, TimeCesium, TimeHub, TimePictra, TimeProvider,
Vite, WinPath, and ZL are registered trademarks of Microchip Technology Incorporated in the U.S.A.
Adjacent Key Suppression, AKS, Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BlueSky, BodyCom,
CodeGuard, CryptoAuthentication, CryptoAutomotive, CryptoCompanion, CryptoController, dsPICDEM,
dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming, ICSP,
INICnet, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, memBrain, Mindi, MiWi, MPASM, MPF,
MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM,
PICDEM.net, PICkit, PICtail, PowerSmart, PureSilicon, QMatrix, REAL ICE, Ripple Blocker, SAM-ICE, Serial Quad
I/O, SMART-I.S., SQI, SuperSwitcher, SuperSwitcher II, Total Endurance, TSHARC, USBCheck, VariSense,
ViewSpan, WiperLock, Wireless DNA, and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A.
and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
The Adaptec logo, Frequency on Demand, Silicon Storage Technology, and Symmcom are registered trademarks of
Microchip Technology Inc. in other countries.
GestIC is a registered trademark of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip
Technology Inc., in other countries.
All other trademarks mentioned herein are property of their respective companies.
© 2020, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.
ISBN: 978-1-5224-6262-0