Keypad
This driver lets you read the state of any key in a keypad matrix circuit as if it was connected to a single input pin. It supports keypads of any size, and any embedded platform that implements the embedded-hal traits.
Motivation
The simplest way to read keypresses with a microcontroller is to connect each key to one input pin. However, that won't work if you have more keys than available pins. One solution is to use a keypad matrix circuit that lets you read from N*M keys using only N+M pins.
In this example, each row is an input pin with a pullup resistor, and each column is an open-drain output. You read the state of a particular key by driving its column pin low and reading its row pin.
A downside of this approach is that it increases code complexity. Instead of reading a single input pin to check if a key is pressed, you need to actively scan the matrix by driving a column low, reading a row, and setting the column high/floating again.
The purpose of this driver is to use the embedded-hal
traits to hide that
complexity. It does this by giving you a set of virtual KeyInput
pins, each
of which represent one key in your keypad matrix. Because they implement the
InputPin
trait, you can treat each one like a single input pin, without worrying about the matrix-scanning that happens under the hood.
This approach was inspired by the shift-register-driver crate, which uses virtual output pins to simplify the use of a shift register.
Limitations
-
Reading the key state is not reentrant.
-
This is not optimized for scanning through the entire keypad as quickly as possible. That's a tradeoff that comes from treating each key as an independent input.
Example
This example uses mock types that implement the embeddded-hal
traits without using
any real hardware. It will compile and run on your host computer, but it
won't do anything interesting because there are no real buttons to press.
For an example that runs on an actual microcontroller, see keypad-bluepill-example.
extern crate keypad;
extern crate core;
use InputPin;
use ;
// Define the struct that represents your keypad matrix circuit, picking the
// row and column pin numbers.
keypad_struct!
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.