Parth Mehta
Parth Mehta

Reputation: 1

ARDUINO pin is constantly changing from HIGH to LOW?

I used this code to check the state of Arduino pin 8. To see if the pin is High or Low but my output continuously changes from high to low.

I am not connecting anything to pin 8 while running this code.

const int Pin = 8; 
int Reading=0;

void setup() {
  Serial.begin(9600);
  delay(2000);
  pinMode(Pin, INPUT); 
}

void loop() {
  Reading = digitalRead(Pin); 
  if(Reading == HIGH)
  {
    Serial.println("HIGH");
    delay(2000);
  }

  if(Reading == LOW)
  {
    Serial.println("LOW");
    delay(2000);
  }

}

But my Output Comes like this: OUTPUT:

HIGH
HIGH
LOW
LOW
HIGH
HIGH
LOW
LOW
HIGH
HIGH
LOW
LOW
HIGH
HIGH
LOW
LOW

Don't know what to do ??

Upvotes: 0

Views: 2374

Answers (2)

Ashish Kumar
Ashish Kumar

Reputation: 1

As the internal pull ups are weak, sometimes adding

pinMode(Pin, INPUT_PULLUP);

won't solve the problem so you need to add a 10K or higher value resistance between pin and ground/power to initially make the pin pull up or pull down.

Upvotes: 0

Bumsik Kim
Bumsik Kim

Reputation: 6653

This is the correct behavior.

Since you don't connect the pin the read should be undefined (meaning it's unstable). Check "floating" state to learn more.

If you want to make it stable, consider using the internal pull-up resister. Change the line

pinMode(Pin, INPUT);

to

pinMode(Pin, INPUT_PULLUP);

to make it always HIGH while disconnected. In this case you should consider the internal pull-up resistance when you actually try to connect the pin.

The official Arduino documentation provides more detailed descriptions on each GPIO states.

Upvotes: 6

Related Questions