Raspberry Pi with a keypad matrix




Today we will see how to interfacing the Raspberry Pi with a matrix keypad using Rpi-hw library.

The library provides the class keypad::matrix, defined in “rpi-hw/keypad/matrix.hpp”, with which it is possible to manage keypads of any size.

Raspberry Pi with a keypad matrixIts constructor method takes two ordered lists containing the GPIO pins used by the device:

  1. keypad::matrix(
  2. { COL0, COL1, COL2, }, // Column pins
  3. { ROW0, ROW1, ROW2, } // Rows pins
  4. )

Let’s take an example. The following image shows how to connect the Raspberry Pi with a standard 12-key keypad:

We used the following GPIO pins: 21, 10, and 4 for columns; 22, 14, 15, and 17 for rows. This is the internal circuit diagram of the keypad (where pin names refer to the keypad connector):

The instance of keypad::matrix will check periodically which buttons are pressed, looking for connection between rows and columns. The control algorithm can be summarized as follows:

  1. Set all GPIOs of rows as input.
  2. Set all GPIOs of columns as output (low).
  3. Set a column pin to high.
  4. If one of rows reads a high value, then the button between those column and row is pressed.
  5. Set the previous column to low.
  6. Repeat from line #3 with another column, until there are no more.

Raspberry Pi with a keypad matrix Circuit

And finally, here is a sample code that shows you how to read the state of some buttons in the 12-key keypad:

  1. #include <iostream>
  2. // Include Rpi-hw headers
  3. #include <rpi-hw.hpp>
  4. #include <rpi-hw/time.hpp>
  5. #include <rpi-hw/keypad/matrix.hpp>
  6.  // Use Rpi-hw namespace
  7. using namespace rpihw;
  8.  int
  9. main( int argc, char *args[] ) {
  10.   // Matrix keypad controller
  11. keypad::matrix dev( { 21, 10, 4 }, { 22, 14, 15, 17 } );
  12.   // Main loop
  13. for ( ;; ) {
  14.   // Check some keys state
  15. if ( dev.pressed(0) )
  16. std::cout << “You have pressed button 0!\n”;
  17.   if ( dev.released(2) )
  18. std::cout << “You have released button 2!\n”;
  19.   if ( dev.pressed(1) && dev.pressed(4) )
  20. std::cout << “You have pressed buttons 1 and 4!\n”;
  21.   // Wait some time
  22. time::msleep( 100 );
  23. } return 0;}

To compile it (or any other programs using the library) use the command:

 

For more detail: Raspberry Pi with a keypad matrix


© 2015 Powered By Engineering Projects Team, Raspberry Pi Projects

Scroll to top