Electrical – Pin as both input (for a switch) and output (for LED) with ATmega32U4

arduinoatmelbuttonioled

There are several questions close to this topic already, but they are either for another µC family, or target reading analog voltages or other special cases.

So here goes: I would like to read a button and drive a LED from the same I/O pin on the ATmega32U4. Is there anything wrong with:

  • Pin => 22K resistor => button => GND
  • Pin => LED resistor => LED => GND

Then of course the pin would be put into input mode (with internal pullup) ever so often, and be in output mode most of the time.

As far as I can tell, the internal pullup is 50-100K on that µC, so the 22K with the button should be able to sufficiently sink that.

In output mode, when the button is not pressed, all is as normal; if the button is pressed, this will add a path through 22K to GND, which might or might not make the LED slightly darker; anyhow, in my application it would not matter at all how the LED looks while that button is pressed.

Any chance to damage anything? Any pitfall that is not obvious?

Best Answer

Don't do this the way you describe. As I uderstand, your cicruit would look like:

schematic

simulate this circuit – Schematic created using CircuitLab

Now, assume the GPIO is in input mode (high impedance), and the button is not pressed. The voltage on the GPIO will be at about the LED forward voltage. Indeed, even though there will be very little current, there is a path through Rpullup-R2-D1, and there will be about 1.8V~2.5V (depending on the type of led you're using) at the MCU pin, which means logic level will be outside specs (it depends on the supply voltage you're using, but most likely, you'll be between high and low voltage limits). So the MCU won't behave consistently, and you won't really be able to tell if the button is pressed or not. The MCU may also consume excessive power in this case.

Here is what I came up with:

schematic

simulate this circuit

You must either drive the GPIO at low level to turn the led on, or set it to high impedance to turn the led off and eventually read the button state. The GPIO must never be actively driven high from the software, because if the button is pressed at the same time, the pin will be short-circuited.

The obvious drawback of the above circuit is that, when the button is pressed, the led will be fully on. But it seems not to be a problem in your case, and apart from this, this circuit is simple, safe for the MCU (if you follow the above rule) and guarantees correct input levels.

Related Topic