Light alarm for a secret boxTinkerPieCircuit tutorial 16 of 24 · Intermediate · 20 minutes
Use a light sensor and a buzzer to build an alarm that beeps when the lid of a box is opened.
Open this circuit in TinkerPieCircuit (free, runs in your browser)
What you will learn
- Combining a sensor and an output
- Thresholds and hysteresis ideas
- Debugging with the Serial monitor
Parts
Steps
Make the light sensor
Wire
3V3→ LDR →P11, andP11→ 10 kΩ →GND(the same divider as the night light).Add the buzzer
Wire the buzzer + to
P12and − toGND.Write the code
When
analogRead(P11)is above 2500 (bright), playtone(P12, 880). OtherwisenoTone(P12).Test in the dark
Press ▶ Start with the LDR slider low: silence. Slide it up: the alarm beeps.
Tune it
Watch the Serial monitor numbers and pick a threshold that suits your box.
The code
function loop() {
const light = analogRead(P11);
Serial.println("light = " + light);
if (light > 2500) {
tone(P12, 880);
} else {
noTone(P12);
}
delay(100);
}
Copy this into the Code tab. It is Arduino-style JavaScript. The real board uses the same pin names (S1, P10…) in TinkerPie Studio.
How it works
The sensor value tells the program about the real world. The program then decides what to do. This pattern (sense, decide, act) is in every smart device.
← Traffic light · All 24 circuit tutorials · Dot game on the LED matrix →