Raspberry Pi: Membrane (Matrix) Keypad as GPIO Input
Membrane matrix keypad using GPIO as Raspberry Pi input has been my goal since WiringPi deployed in the first place. To begin with, GPIO hacking was initially started with some important basics (see previous post). Without external system (other interfacing chip), the 3×4 membrane keypad reserved all seven GPIO pins plus one pin used for LED indicating successful reading of pressed key.
My idea of having the keypad is to make alternative input available under no keyboard presence nor shell access. List of things I can think of for instances, pressed key “0″ will make the Raspberry Pi (RPi) dial GPRS to a specific ISP and act as router to the USB WiFi stick, pressed key “7″ will convert it to a router that will bridge the ethernet to WiFi, etc. In short, those key readings will invoke subsequent scripts to run inside RPi.
The physical connection schematic drawings and code are gitified (visit v1.2 of the project on gitHub). A nice animated image on how the buttons connect pins forming a matrix can be found in hackyourmind.org.
Some remarks over what the code does:
- It only read one pressed key at a time.
- It uses no interrupt. To read input it must wait and scan (this waiting experience is by far negligible to human sense).
- Debouncing doesn’t seem necessary as WiringPi already provided this by software (I suppose this timing method on their gitHub deals with debounce).
How it works? RPi forum thread gives a general idea that applies in my case:
- Divide the 3×4 matrix as columns and rows. 4 GPIO pins as rows are pulled-up with 10k resistors and initialized as input.
- Other 3 GPIO pins as columns are initialized as output low.
- First loop will scan for one pressed key being read as one of the rows pulled-low
- After the loop breaks, all columns are set as input, then the row pin found in the loop is set as output-high
- Second loop will scan for column being pulled-high by that row pin. Between both loops, it is assumed that the key press is still in effect. In reality, normal human act of pressing this key elapses long enough for the software to run the scans in two loops.
- Bingo! The code reads row-column combination of the pressed key.
Example of the code’s output by calling from shell:
$ while true; do /usr/local/bin/matrixQPi.py -i; done 3 6 9 8 # *
(In the above example
^C will throw Python
KeyboardInterrupt messages before breaking the