const int analogInPin = 36; // Analog input
const int PIN_COUNT = 8;
const int SAMPLE_COUNT = 10;
const int pin[PIN_COUNT] = {15, 2, 4, 16, 17, 18, 19, 22};
const float r1[PIN_COUNT] = {1000.0, 3300.0, 10000.0, 33000.0, 100000.0, 330000.0, 1000000.0, 10000000.0};
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
// send all the pins we'll use low, and then configure them as inputs
for (int i=0; i<PIN_COUNT; i++) {
pinMode(pin[i], OUTPUT);
digitalWrite(pin[i],LOW);
pinMode(pin[i], INPUT);
}
}
// take SAMPLE_COUNT succesive readings of the voltage and average them
float averageVoltage() {
float total = 0.0;
for (int i=0;i<SAMPLE_COUNT;i++) {
delay(5);
total += float(analogRead(analogInPin));
}
// convert to voltage and average
return 3.3*total/(SAMPLE_COUNT*1023.0);
}
// see blog post for details of this caluclation
float calculateResistance(float r, float v) {
return r/(3.3/v-1.0);
}
void loop() {
float minimum = 1.65;
float resistance = 0; // default value
/* loop through finding the best estimate
which we'll get when the measured voltage is closest
to 2.5v */
for (int i=0; i<PIN_COUNT; i++) {
pinMode(pin[i], OUTPUT);
digitalWrite(pin[i],HIGH);
float v = averageVoltage();
digitalWrite(pin[i],LOW);
pinMode(pin[i], INPUT);
float difference = abs(v-1.65);
if (3.3 > v && difference < minimum) {
minimum = difference;
resistance = calculateResistance(r1[i], v);
}
}
Serial.print("resistance = ");
Serial.println(resistance);
delay(3000);
}