Stap 6: De lichtsensor Code
Vervolgens moeten we een functie voor het verwerken van de lichtsensor gratis transfer-circuit. De basis van deze functie zijn kort pin 5 hoog naar het circuit in rekening brengen en tijd hoe lang duurt de pin te laag gaan instellen. Hoe meer licht raken van de fototransistor des te sneller zal het circuit kwijten. De qtTime() functie doet dit opladen en timing. De functie lightCheck() wordt de functie qtTime() gebruikt om aan te geven of de Boon in het licht of donker. Wij zullen vervolgens lightCheck() binnen loop gebruiken om onze lichtsensor schakeling testen.
uint32_t qtTime(int nQTPin, uint32_t nMaxWait) { // Charge the capacitor digitalWrite(nQTPin, HIGH); delay(5); // Stop charging digitalWrite(nQTPin, LOW); // Start discharge cycle uint32_t nStart = millis(); uint32_t nDuration = 0; // As capacitor discharges through phototransistor sensor // pin will transition from HIGH to LOW while(digitalRead(nQTPin) == HIGH) { // Wait for discharge // In case millis() has rolled over if ( millis() < nStart ) { nStart = millis(); } // Has duration exceeded the DARK threshold time? nDuration = millis() - nStart; if ( nDuration > nMaxWait ) { break; } } // For determining threshold or degugging, output duration String strDuration = ""; strDuration += String(nDuration); strDuration += " ms"; Serial.println( strDuration ); // Above section can be removed or commented once lightCheck() // is working as desired. return nDuration; }
String lightCheck() { String strOut = "LIGHT"; if ( qtTime( LIGHT_SENSOR_PIN, DARK_DISCHARGE_THRESHOLD) >= DARK_DISCHARGE_THRESHOLD ) { strOut = "DARK"; } // Return LIGHT or DARK return strOut; }
void loop() { Serial.println( lightCheck() ); Bean.sleep(500); }