ArduinoArduino UnoExact chip

Op-amp night light (LM358)

An LM358 compares the light sensor with half the supply: when it gets dark the LED comes on, with no code in the way. The Uno reads both and prints them.

Op-amp night light (LM358) in Argynix Lab

The code

sketch.inoC++
// A night light made of an op-amp: the LM358 compares the light sensor's AO (higher
// when it is dark) with 2.5 V from two 10 kΩ resistors, and its output lights the LED.
// The Uno does not switch anything: it reads the comparator on pin 3 and the sensor on
// A0, and says what changed. Set the light in the sensor's settings: under about
// 100 lux the LED comes on.

int was = -1;

void setup() {
  Serial.begin(115200);
  pinMode(3, INPUT);
}

void loop() {
  int dark = digitalRead(3);
  if (dark != was) {
    float volts = analogRead(A0) * 5.0 / 1023.0;
    Serial.print(dark ? "Dark: the LED is on" : "Light: the LED is off");
    Serial.print(" (sensor at ");
    Serial.print(volts, 2);
    Serial.println(" V)");
    was = dark;
  }
  delay(50);
}