Input only normal with pin13

Hello everyone. I have got a strang thing:
With this schema:

and this code:

* Switch test program
int switchPin = 2; // Switch connected to digital pin 2
void setup() // run once, when the sketch starts

  • Serial.begin(9600); // set up Serial library at 9600 bps*
  • pinMode(switchPin, INPUT); // sets the digital pin as input to read switch*
    void loop() // run over and over again
  • Serial.print("Read switch input: ");*
  • Serial.println(digitalRead(switchPin)); // Read the pin and display the value*
  • delay(100);*

I connect all things.

but when I read analoge input, I get 0...1....0...1...,the button doesn't work at all. After manipulation, I found out if I put the resistor connected the pin2 even without connecting the breadboard, the alternation 0&1 occurs. What happens here?

Moreover, I have tried other pins, only pin13 works with this schema and code. Why?


You need this after the pinMode statement to turn on the internal pullup

digitalWrite (switchPin, HIGH);

Then it will read High until you ground the pin to make it read Low.

Pin 13 has an LED to resistor to ground, I imagine you see that read as a consisent 0?

COOL, you are so right CrossRoads, that answer all my questions.

Thank you very very much again.

But I have another question:
Why it alternate with 0 and 1 with my first code?

Pin 13 has an LED to resistor to ground, I imagine you see that read as a consisent 0?

I too would caution that with a ? As the led would not be forwarded biased when wired to a 'floating' input pin, I'm not convienced it would indeed act like a pull-down, but rather most likely a open circuit and as such might have no effect on the pin and the pin would remain in a 'floating' input state.


"Why it alternate with 0 and 1 with my first code?"
Pin 2 would read inconsistently if not connected to +5 or to Gnd because it would be "floating"- the pin when in input mode requires very little current flow to make it high or low, with nothing connected it can drift back & forth, with just a finger touch often being enough to make it change.

Maybe the LED/resister wouldn't seem enough to make it read low - but if you are seeing a steady low, then maybe it is.

I don't have any bootload arduino's on hand at the moment, need to get a couple programmed so I could try this myself.

Ok guys, lets the alternation aside for the moment.
I have another problem: digitalWrite (switchPin, HIGH); makes it "read High", but when I wirte : digitalWrite (switchPin, LOW); I can't make it read low until I connect the 5V to make it read high. How come?

Why would you write your pin that is setup as an input Low?
Writing it high enables the internal pullup resister. Writing it low turns it off - then you are back to a floating input again. Then you need to pull it low externally to make it read low.
Do you have anything connected to this pin?

Have a read of this:-