0
votes

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 ??

2
You might want to learn what the pinouts are rather than test them and be bewildered by what you find. The pinout diagram says it's clk0, so it's probably outputting a clock signal. - user1228
Yup. arduino.cc/en/Reference/SPI - user1228
@Will He's not initializing SPI, so it shouldn't be real cause. He is, however, stating "there is nothing connected" and the code shows: pinMode(Pin, INPUT);, so it might be more like floating input issue. - KIIV
If nothing is connected to the input then why do you care what the input is? If you care then consider adding a pull up resistor and/or connect something up. - Ben T
Yep, thats it. You have a Pin in an undefined state. This is called floating-pin. As KIIV and blt stated, you should consider a Pull-Up or Pull-Down resistor. Depending on your Arduino, the AtMega comes with internal resistors as well, that can be configured. - Tom Mekken

2 Answers

6
votes

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.

0
votes

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.