Datasheet
Light-Sensitive Navigation with Phototransistors • Chapter 6
Robotics with the BOE Shield-Bot • 195
A charge transfer measurement takes seven steps:
(1) Set the I/O pin high to charge the capacitor.
(2) Wait long enough for the capacitor to charge.
(3) Change the I/O pin to input.
(4) Check the time.
(5) Wait for the voltage to decay and pass below the Arduino’s 2.1 V threshold.
(6) Check the time again.
(7) Subtract the step-3 time from the step-6 time. That’s the amount of time
the decay took.
{
pinMode(pin, OUTPUT); // Step 1, part 1
digitalWrite(pin, HIGH); // Step 1, part 2
delay(1); // Step 2
pinMode(pin, INPUT); // Step 3 part 1
digitalWrite(pin, LOW); // Step 3, part 2
long time = micros(); // Step 4
while(digitalRead(pin)); // Step 5
time = micros() - time; // Step 6 & 7
return time;
}
In this sketch, Step 1 has two sub-steps. First, pinMode(pin, OUPUT) sets the I/O pin to an
output, then
digitalWrite(pin, HIGH) makes it supply 5 V to the circuit.
Step 3 also has two sub-steps, because the I/O pin is sending a high signal. When the sketch
changes the I/O pin’s direction from output-high to input, it adds 10 kΩ of resistance to the
circuit, which must be removed. Adding
digitalWrite(pin, LOW) after pinMode(pin,
INPUT) removes that resistance and allows the capacitor to drain its charge normally
through the phototransistor.