The sketch LeftLightSensor charges the capacitor in the pin 8 QT circuit, measures the voltage decay time, and displays it in the Serial Monitor. Remember, with this circuit and sketch, lower numbers mean brighter light.
We’ll be using this light-sensing technique for the rest of the chapter, so you can take the BOE Shield-Bot from one room to another without having to worry about finding the right resistors for different ambient light levels.
/* * Robotics with the BOE Shield - LeftLightSensor * Measures and displays microsecond decay time for left light sensor. */ void setup() // Built-in initialization block { tone(4, 3000, 1000); // Play tone for 1 second delay(1000); // Delay to finish tone Serial.begin(9600); // Set data rate to 9600 bps } void loop() // Main loop auto-repeats { long tLeft = rcTime(8); // Left rcTime -> tLeft Serial.print("tLeft = "); // Display tLeft label Serial.print(tLeft); // Display tLeft value Serial.println(" us"); // Display tLeft units + newline delay(1000); // 1 second delay } // rcTime function at pin long rcTime(int pin) // ..returns decay time { pinMode(pin, OUTPUT); // Charge capacitor digitalWrite(pin, HIGH); // ..by setting pin ouput-high delay(1); // ..for 5 ms pinMode(pin, INPUT); // Set pin to input digitalWrite(pin, LOW); // ..with no pullup long time = micros(); // Mark the time while(digitalRead(pin)); // Wait for voltage < threshold time = micros() - time; // Calculate decay time return time; // Return decay time }
Before moving on to navigation, you’ll need to run the same test on the right (pin 6) light sensor circuit. Both circuits have to be working well before you can move on to using them for navigation—there’s that subsystem testing again!
It would also be nice to have a third sketch that tests both phototransistor circuits.
void loop() // Main loop auto-repeats { long tLeft = rcTime(8); // Left rcTime -> tLeft Serial.print("tLeft = "); // Display tLeft label Serial.print(tLeft); // Display tLeft value Serial.print(" us "); // Display tLeft units long tRight = rcTime(6); // Left rcTime -> tRight Serial.print("tRight = "); // Display tRight label Serial.print(tRight); // Display tRight value Serial.println(" us"); // Display tRight units + newline delay(1000); // 1 second delay }