Fri Jul 12, 2013 6:59 am
The RasPi has 17 GPIO on the main header, and another 4 on the P5 header on a Rev2 board. Some have alternate functions, but they can all be configured as general purpose I/O.
You can scan 25 switches with 10 GPIO lines. Connect the switched in a matrix with one pin connected to all switches in the same row and the other pin connected to all switched in the same column. Wire each row to one of 5 GPIO outputs through 1k resistors and wire each column to one of 5 GPIO inputs.
Set a row output high then read each column input. If an input is high it means the switch at that row and column in the matrix is pressed. Clear the output then set the next one along high and read the inputs again. In five write/read steps you have read 25 switches.
You can use this scanning method to read up to 110 switches on a Pi with no IO expander.
10+11 = 21 GPIO lines
10 * 11 = 110 matrix points.
For such large numbers of switches dedicated interfaces make more sense in most cases, but it can be done.
Note that each matrix point is a switch link between two lines. You can't use matrix scanning to read lots of logic signals (more hardware would be required).
Since each point is only read when row is set and column sampled very short switch activations could be missed. This isn't a problem with push buttons / keyboards but may be an issues with some devices.
You can do the same with output, but often you will want the output to stay active between matrix scans. You could run 25 LEDs wired in a 5x5 matrix (which could be any physical arrangement), but each LED will be on for only 1/25th of the time, so it won't be as bright as it could be. This isn't a sound design because if, for any reason, all ten GPIO were on at the same time, perhaps because the wrong GPIO program is run by mistake, all the LEDs would be on an that would overload the Pi, possibly damaging the Pi.