For times when you only have 2 free microcontroller pins, the serial I/O expander IC is the way to go. They come in a variety of flavors, with RS232, SPI, and I2C being the most common. The PCA95xx I2C compatible chips are the least expensive. Although, at 0.80$ it is quite a bit more than HC logic. A typical implementation is shown below.
Figure 1 – Example I/O expander mux schematic.
Basically the I/O expander implements the scanning matrix, and the microcontroller gives it commands to set certain pins high, and read back on others. It is relatively straightforward, but since each command must go over a serial bus to execute, it can take a while to scan an entire matrix. Another disadvantage is that it does not allow for external interrupts. And, since it uses I2C, it will consume that peripheral on your microcontroller and give you headaches if your PCB layout isn’t perfect (I2C is to be avoided like the plague). But, if you don’t have an I2C peripheral, it’s not worth using this setup at all, as it would take far to long to bit-bang all the data required.
If you only have 2 free pins, and you can’t get a bigger microcontroller, this may be the option for you. But, if you have less than 32 switches to scan, you should have a look at the hacks page first. One of the hacks might be easier, faster, and less expensive to implement.