input turns itself high

Do I have a defect unit. When I turn my Arduino Mega on it will within 20 secounds say that port 10 is high, not when he hole is empty. If I plug a cable in port 10 and dosen't connect it to anything it will say high (how is this posible).

int ledPin = 8;
int val = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(10, INPUT);
}
int stepp =0;
void loop()
{
if (stepp==0)
{
val = digitalRead(10);
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
if (val == HIGH)
{
digitalWrite(ledPin, HIGH);
stepp=1;
}

}
}

An unconnected pin can return HIGH or LOW when you read from it. Basically, it will pick up random electrical noise.

Then how am I suppost to make a button when it swings like this 10101011111100 when the cable is connected???

Use a pull-up or pull-down resistor. Search the forum for those terms for more info.

You can also program an input pin to use it’s internal pull-up resistor and then use a switch to ground to change from a 1 to a 0. Your code will then have to work with a 0 as a active button state. Also beware that most switches have some degree of contact bounce and that some software functions need to be used to work around that physical problem.

Lefty

I finaly found a solution:)
I put a resistor in 10 and connected the other side of the resistor to GND which returns 000000000000000. Then when you push he button it ports from 5V directly to the 10 port (not from the other side of the resistor). This wil make it 111111111111111111111111111

Thank for your help guys :slight_smile:

What you did is called using a "pulldown" resistor.
You can eliminate the resistor by doing as retrolefty suggested and wiring the button between your pin (10?) and ground and using the pullup resistor (to +5V) that's built in to the chip. You do have use a line of software to tell the chip to switch the resistor into the circuit. Like this.

And as he also said be aware that switch contacts usually 'bounce' -- switch rapidly off and on for about 10 milliseconds or so when you change them from open to closed (less often but still possible when you change them from closed to open). You may need to account for that in your code (one way is to do a short delay() after sensing a change before continuing).

void setup()
{
pinMode(10, INPUT); // if you are using pin 10
digitalWrite(10, HIGH); // writing a HIGH to an input pin switches
// in the pullup resistor.
}

void loop()
{
if(digitalRead(10) == LOW) // pushing the button connects 10 to GND
{
// do this
}
else
{ // do this
}
......
}