Electronic – Is it safe for micro to switch pins from input to output in a loop

avrmicrocontrollerteensy

I'm trying to make use of a keypad that I took out of a phone which has 3 columns and 4 rows. I've traced out the schematic on its PCB and figured out a way to drive it that I think might work, but I'm not sure whether it's safe for the microcontroller (it's a teensy++ 2.0 in this case, but I think the answer would be the same for most AVR microcontrollers).

The way the keypad works is that it has 3 pins out for column 1,2,3 and 4 pins out for rows 1,2,3,4 when you press a button to completes a circuit between the row and column that the button is in.

So the circuit I designed would work like this: I have 3 output pins connected to the columns and 4 input pins connected to the rows. I would cycle through the columns putting a high signal and then reading the rows to see if any button was pressed.

I realized one safety issue with this design which is that if you hold down two buttons on the same row, there would be a short between two different columns and since one was set to output high and the other output low that could create an overcurrent condition (like it described in http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino).

To resolve that I had the idea to make the column output pins actually input pins when they're not being used to output a high signal – and adding pull down resistors to my row input pins. What this would mean though is that I'm flicking the pins between input and output mode in a loop that repeats every 15 ms (since I sleep for 5 ms between polling the columns).

Is it safe/healthy for the microcontroller to switch its pins between input and output in a loop of about 15ms? or could this circuit be made safe in a different way?

I would also really appreciate any links to pages that describe which basic circuits with input/output pins are safe and which aren't.

Best Answer

What you describe is the standard way of scanning a matrix keypad. Essentially you are using the outputs as open-collector / open-drain (because you switch between output+low and input). For chips that do not have this possibility a diode can be put in series.

Switching a pin between input and output is totally safe and valid, it is done all the time, when a standard (push-pull type) pin is used to implement protocols like I2C and dallas/maxim 1-wire that need an open-collector output.

Depending on the value of your pull-up resistors you might need to wait a little between switching to a new output and reading the inputs. A few ms would be a starting point.

To suppress key bouncing it might be advisable to have the readings of a key no less than 50 ms apart. This can be used to derive your timing plan.

You seemed to be a little worried about doing things as fast as a few ms apart. For a microcontroler running at a few MHz that is thousands of instructions apart!