The input stage of the analog-to-digital converter is a sample-and-hold
capacitor. When you take an analog reading, the capacitor is connected
to the input pin, it is charged to the voltage you want to measure, then
it is disconnected from the input and it “holds” the voltage while the
conversion is in progress.
You can leverage this capacitor to detect whether your input pin is
floating. If you try to take an analog reading from a floating pin, the
sample-and-hold capacitor will not be able to charge or discharge
through it. You should then get a reading that is close to the
previous reading you took, although not exactly the same, as floating
pins a very prone to noise. Thus I suggest the following algorithm:
- take a reading from a pin tied to GND, and discard this reading
- take a reading from your input pin and record it
- take a reading from a pin tied to +5V and discard it
- take and record a second reading from your input pin
If the input pin is floating, the first recorded reading should be close
to zero, and the second one close to 1023.
Here is a test sketch demonstrating this approach. It uses
digitalWrite()
to tie the required pins to GND and +5V, thus no
external connections are needed:
const uint8_t pin_input = A0; // the one we are interested in
const uint8_t pin_low = A1; // will be tied to GND
const uint8_t pin_high = A2; // will be tied to +5V
void setup() {
Serial.begin(9600);
pinMode(pin_input, INPUT);
pinMode(pin_low, OUTPUT);
digitalWrite(pin_low, LOW);
pinMode(pin_high, OUTPUT);
digitalWrite(pin_high, HIGH);
}
void loop() {
analogRead(pin_low); // take a reading and discard it
Serial.print(analogRead(pin_input));
Serial.print(" ");
analogRead(pin_high); // take a reading and discard it
Serial.println(analogRead(pin_input));
delay(200);
}
And here is a sample output from an Arduino Uno:
167 710
271 748
287 753
287 751
284 748
281 746
279 741
271 736
268 733
264 732
It looks like the capacitor does not hold its charge very well across
consecutive readings. This is presumably caused by the parasitic
capacitance of the input pin, which partially charges and discharges the
sample-and-hold. Yet, the difference between consecutive recorded
readings (about 460) is still very high, and this very clearly shows
that the input pin is not connected to a stable voltage.