Light Sensor

From STEAMwiki
Jump to: navigation, search

Wire up the light sensor. Use a 10k resistor. Any analog sensor can be used instead of the light sensor. For example, a temperature sensor or moisture sensor.

Arduino-light-detector-circuit.png File source: http://www.learningaboutelectronics.com/Articles/Arduino-light-detector-circuit.php

void setup() {
    pinMode(A0, INPUT);
    Serial.begin(9600);
}

void loop() {   
    Serial.println(analogRead(A0));
}

Launch the Arduino IDE, and open Tools -> Serial Monitor. You may need to select the proper serial port first from Tools -> Port

Use the Serial Monitor to look at different light readings. Find the readings for bright and dark according to your ambient light.

Once you have the readings, you can write code. For example, make a LED blink fast if its bright out, and slow if its dim:

void setup() {
    pinMode(D7, OUTPUT);
    pinMode(A0, INPUT);
    Serial.begin(9600);
}

void loop() {
    Serial.println(analogRead(A0));
    // 3400 = bright lights
    // 2100 = covered with finger
    // 1100 = covered with phone
    
    if (analogRead(A0) > 3300) {
        digitalWrite(D7, HIGH);
        delay(100);
        digitalWrite(D7, LOW);
        delay(100);
    } else if (analogRead(A0) > 2100) {
        digitalWrite(D7, HIGH);
        delay(1000);
        digitalWrite(D7, LOW);
        delay(1000);
    } 

}