I am trying to interface a Duemilanove to some digital circuits. I am having trouble using Pin 9 as a digital input - it does not seem to be responding, and if I repeatedly read it with nothing connected I get:
011110000111000111100011
Can I use that pin as a digital output, if not an input?
This is the test sketch:
const int ledPin = 13; // LED connected to digital pin 13
const int testPin_o = 5; //CTS, just as a source
const int testPin_i = 9; // - which I cannot get working
unsigned long mlednext;
unsigned long mleddelay = 1000;
int initialstate = HIGH;
void setup() // run once, when the sketch starts
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
pinMode(testPin_o, OUTPUT);
pinMode(testPin_i, INPUT);
Serial.begin(9600);
mlednext = millis();
}
void loop() // run over and over again
{
if (millis() > mlednext + mleddelay) {
int tess = digitalRead(testPin_i);
Serial.print(tess);
digitalWrite(ledPin, initialstate); // sets the LED on
initialstate = (initialstate==HIGH) ? LOW : HIGH;
mlednext = millis();
}
}
If you read a digital input with nothing connected, the pin can "float", which will result in random strings of zero and one as you have seen. Try connecting the pin to 5V through, say, a resistor of a few k Ohms. Arduino inputs are high impedance CMOS inputs and will pick up noise from the mains, from cell phones and from nearby electronics if not specifically connected to something.
Yes you can use pin 9 as both a digital input and output.
The reason you're seeing the random values when doing the digitalRead is because you don't have the pin connected to anything (referred to as floating). You're seeing random electrical noise.
You always want to make sure you have some kind of bias stop input pins from floating. This usually consists of a pull-up or pull-down resistor depending on the circuit.
As stated you are fighting a floating input signal. A simple software fix is to add a digital write in your setup section and this will apply a 'soft pull-up' to the input pin and it should then read as a high until wired to something externally (like a switch wired to ground) that can pull it low when desired.
pinMode(testPin_i, INPUT);
digitalWrite(testPin_i, HIGH); // This will activate the internal pull-up.
Thank you for your responses.
I have now to check my wiring, and the circuit board for dry joints - I can see the digital signal going between 5V and 0V elsewhere on the circuit board, but am losing it as it gets to the arduino header.