Mistaken pinMode() leads to ... results.

I noticed today that my code was mistakenly setting one pin’s pinMode twice, and another pin’s pinMode not at all, as such:

const byte buttonInputWhatever = 11;
const byte buttonLEDInputWhatever = A4;

void setup() {
  pinMode(buttonInputWhatever, INPUT_PULLUP);
  // ... more code
  pinMode(buttonInputWhatever, OUTPUT); // should be buttonLEDInputWhatever -- oops

The strange thing is that I have been working on this project for literally months, and the input button was working properly. I don’t get it. The pin was being used as a digital input pin, but it was in OUTPUT mode the whole time. I guess maybe putting it into INPUT_PULLUP mode first activated the pullup resistor, and then putting it into OUTPUT mode meant it was constantly HIGH, but when the momentary button was pushed, it shorted to ground and went LOW, and therefore read correctly? That’s the only way I can think of to explain it, except then why isn’t my Arduino’s digital pin fried? No clue.

Meanwhile, we have the LED pin that was being written to as HIGH and LOW to turn on and off the LED, and it was working, but the LED was super-dim. I thought it was just because it was a green LED, when all the others in the project were red, but now I think it’s because the LED’s analog pin was actually in digital input mode, and digitalWriting HIGH and LOW was activating and deactivating the pullup resistor, causing it to weakly pull towards 5v just enough to light the LED. Again… I have no idea, just guessing.

I've read the Atmega328 datasheet a few times and I'm still not clear what the differences are. I have experienced the dim LED problem for the same reason as you.


The LED works because, even though the pin is set to an input, you are turning the pullup resistor on and off. This pullup resistor basically connects the pin to +5v through a ~60k resistor. The LED will light, but it will be very dim.

The button still works because the input circuitry is never disconnected. The uC can measure the voltage of what it is driving the pin to. You drive the pin high and digitalRead() will return 1 (and vice versa). When you press the button, you are shorting the output to ground so your digitalRead() will return 0. HOWEVER this is not good at all for the pin driver as you are basically shorting it out when you press the switch.

The moral is, check your code twice. Shorting driver pins is NOT a good idea.

[quote author=Tom Carpenter link=topic=195709.msg1444382#msg1444382 date=1382879827] The moral is, check your code twice. Shorting driver pins is NOT a good idea. [/quote]

So, basically, I just appear to have gotten lucky that I didn't burn out the pin? It's a momentary button, so it's never pressed for long, and it's the least-used button on my project.