Interfacing the Keyboard with AVR Microcontroller
At a lowest level, keyboards are organized in a matrix of rows and columns. The CPU accesses both rows and columns through ports, therefore with two 8-bit ports an 8 X 8 matrix of keys can be connected with a microcontroller.
When a key is pressed, a column and a row make a contact; otherwise, there is no connection between rows and columns. In x86 PC keyboards, a single microcontroller use for software and hardware interfacing of the keyboard.
The matrix keyboard connection with the port 1 and port 2 of AVR microcontroller is shown below:
Scanning and identifying the key:
Above figure represent a 4 X 4 matrix connected to two ports. The rows are connected to an output port and the columns are connected to an input port. If no key has been pressed, reading the input port will give 1s for all columns since they are connected to high (VCC). If all the rows are grounded and key is pressed, one of the columns have 0 since the key is pressed provides the path to ground. It is the function of microcontroller to scan the keyboard continuously to detect and identify the key pressed.
Grounding rows and reading columns:
For detecting the pressed key, the microcontroller grounds all rows by providing 0 to the input latch, and then it reads columns. If the data read from the columns is D3-D0=1111, no key has been pressed and the process continues until a key pressed is detected by system.
However, if one of the column bits has a zero, this means that a key press has occurred. For example, if D3-D0= 1101, it means that a key in the D1 column has been pressed. After a key press is detected, the microcontroller will pass through the process of identifying the key.
Starting with the top row, the microcontroller grounds it for providing a low to row D0 only; then it reads the columns. If the data read is all 1s, no key in a row is activated and the process is further moved to the next row.
The process of identifying the rows and columns is easy as microcontroller knows at any time which rows and columns are being accessed.
The C program for reading the keypad and sending the result to Port D is given below:
PC0-PC3 connected to columns
PC4-PC7 connected to rows