Connecting a switch

I'm going to reply to this post with actual question, because it contains images and forum does not allow to post them at first :)

I'm IT guy with school based electronics background, so forgive me for this dum question.

In book "Getting started with Arduino" found a picture how a button should be connected.

Wiring diagram I suppose is like this:

I understand that positive output cannot be directly connected to input pin, because it would cause high current and short circuit (I = U/R = 5/very low wire resistance). So suitable load or resistor is placed, to limit current.

But why it is connected in separate branch to the ground and not in same line to input like this:

Those two schematics are not the same. In the correct one the input pin is connected to ground through a resistor. When the switch is closed it is connected to 5V and the resistor is connected across the 5V.

In the second diagram the input is left floating when not connected to 5v.


Good question no doubt about it. The arduino’s inputs can float unless they are set to a logic high or low so the swith example fixes that by forcing the input to be high or low.

But you can use a method like yours, but without the resistor even, if you connect the input pin 7 to ground through the switch but only if you add the line of code:

pinMode(7, INPUT);
digitalWrite(7, HIGH); // ← extra line

You have to have this in your setup and you only have to run it once in your program. This tells the arduino to internally tie the input pin high.

Hope this helps.


Forgive me if I'm blunt?

I understand that positive output cannot be directly connected to input pin, because it would cause high current...

Ummm... no. That shows that you DON'T understand.

As long as the pin has not been configured as an output, it will present a large resistance, little current will flow through it whether you connect it to 5v or to ground.

More at...

... and pages linked to it.

Thank you all for answers. Grumpy_Mike's tutorial was very helpful. Still reading other references on pull up / down resistors.

tkbyd my mistake was that I've imagined 5V output and 7 pin input as positive / negative terminals of a battery, now its more clear to me.