What is wrong with my code?

This is my code-

define Led 13

define wire 2

void setup() { pinMode(wire, INPUT); pinMode(Led, OUTPUT);

}

void loop() {

if (digitalRead(wire) == HIGH) { digitalWrite(Led , HIGH); } if (digitalRead(wire) == LOW) { digitalWrite(Led , LOW); } if (digitalRead(wire) != LOW && digitalRead(wire)!= HIGH) { digitalWrite(Led , LOW); } }

I don't know whether there's a problem with my code or my wire.When I insert the wire into pin 2, the LED starts flickering.When I touch the exposed or even insulated part of the wire the LED switches on.When I connect pin2 to 5v supply and remove it even after the removal, LED stays on for few seconds.What's the problem?

Floating inputs (inputs that are unconnected) can take random values. And your hand and body make a pretty good antenna for stray 60Hz mains current.

Regarding the code: You don’t need the second if statement. It can, instead, be an “else” off the first if statement.

The third if statement is puzzling. Since the pin is either high or low, the if test will always fail.

Loop() could therefore just be:

    digitalWrite(led, digitalRead(wire));

-br

How do I prevent it?

I'm afraid I can't understand your question. Please state your problem more clearly. What do you expect to see, what is happening instead that is a problem, and why is it a problem?

-br

insulate your electronics better :D

How about this? It will put a weak pullup resistor on the wire pin. That way it will not float.

void setup() {
  pinMode(wire, INPUT);
  pinMode(Led, OUTPUT);
  // set weak pullup
  digitalWrite(wire,HIGH); 
}

SurferTim: How about this? It will put a weak pullup resistor on the wire pin. That way it will not float.

void setup() {
  pinMode(wire, INPUT);
  pinMode(Led, OUTPUT);
  // set weak pullup
  digitalWrite(wire,HIGH); 
}

I think on the new versions of arduino, you can just call:

  pinMode(wire, INPUT_PULLUP);

To get the pullup enabled.

It flickers because you have nothing to pull the input one way or another when there is no wire connected. If you bring your finger close to the input, you act as a capacitor. Any charge on your finger will be transferred to the input and trick the arduino into thinking there is a logic 1 or a logic 0.

One more thing:

if (digitalRead(wire) != LOW && digitalRead(wire)!= HIGH)

Will almost certainly never be true, unless you are applying signals which change from high to low in the fraction of a second between the two digital reads. Boolean by definition is either yes or no, aka high or low, there is no maybe.

Classic thread title. I think that Paul may be driven to new heights, or take to needing pills.

OP - if you start another topic on this subject, you're banned. Got it?

Classic thread title. I think that Paul may be driven to new heights, or take to needing pills.

I ignore stuff like this. I read the thread for the laughs, but generally am able to refrain from hitting the reply icon.

I meant new heights of eloquence. Honest!