Go Down

Topic: Trouble with digitalRead(). (Read 974 times) previous topic - next topic

Amateur123

hi guys, I am using Arduino UNO and I am having same kind of trouble with all of my pins. But I will post what I am getting at pin 7.
This is the code I am running.
void setup() {
  Serial.begin(9600);
  pinMode(7, INPUT);

}
void loop() {
  int sensorValue = digitalRead(7);
  Serial.print(sensorValue);
  delay(1000);
}

... and this is what I am reading in my serial monitor.
110000000111100000010111000000111110000110000000001111110000001110.

I inserted one end of hookup wire in pin 7 and the other end is just left hanging, there is no connection. According to the references, When a pin is configured as an INPUT with pinMode, and read with digitalRead, the microcontroller will report HIGH if a voltage of 3 volts or more is present at the pin. There is no way the wire I inserted is sending 3 volts to pin 7. Basically there shouldn't be any 1's being displayed at the serial monitor. Once I remove the wire from pin 7 things go back to normal and I read only 0's at the serial monitor. I have also tried using  digitalWrite(7,LOW); under pinMode(); with same results. I am attempting to interface the Arduino with a weighing scale in the long run. I need the pins to react to the voltages coming out of the scale's pins that are directly connecting to the LCD. So I don't want to set the pins to output or set the pinMode to HIGH. 
         The wire I am using is a 22-guage, stranded hookup wire Rated 300V, 80 deg C, from RadioShack.  Is there any compatibility issues  with the wire I am using? is there something wrong with pins in my Arduino? or most likely I am missing something obvious. If anyone can point me in the right direction I will be eternally grateful. This has been pretty frustrating. Please help. =( =(   





nickgammon

You are picking up noise. A "hanging" wire has undefined results. You need to connect it via a resistor (eg. 10K) to either +5V or Gnd. That gives it a defined input. Then you activate it by connecting it to the other side.

A simple way is to do:

Code: [Select]
digitalWrite (7, HIGH);

Then it will read HIGH until such time as you touch the wire to ground. This is with the pin still set as input. That connects an internal pull-up resistor.
Please post technical questions on the forum, not by personal message. Thanks!

More info: http://www.gammon.com.au/electronics

Amateur123

Thank you very much. I knew I was messing up on something to do with basic electronics. I followed your directions with a resistor and it worked as intended. Thanks again.

Go Up