Light, sound and IR sensors
8 min read
Sensors are how a project notices the world. Many simple sensor modules work the same way, so once you learn one, you know most of them.
Two kinds of output
- AO is analog. It gives a changing voltage, read with
analogRead(). - DO is digital. It goes HIGH or LOW when the level crosses a limit, read with
digitalRead().
The small blue screw on the module sets that limit. Turn it slowly with a small screwdriver while watching the Serial Monitor.
Light sensor (LDR)
An LDR changes resistance with light. It is more resistant in the dark. On its own it needs a 10 kΩ resistor to make a voltage divider, and modules include this already. Use it for night lights and sun tracking.
Sound sensor
A small microphone turns sound into a signal, and the module reacts to loud sounds. Its output is a short pulse, so check it often in your code, and avoid long delay() calls that could miss a clap.
IR sensor
One part shines invisible infrared light and another watches for its reflection. A pale surface reflects well and a dark line reflects little. Line-following robots use this.
- Keep the sensor a few millimetres above the floor, as the project says.
- Strong sunlight contains infrared and can confuse it.
- Shiny or black objects may not be seen.
A method for every sensor
- Connect VCC and GND, checking the voltage first.
- Print the raw value to the Serial Monitor.
- Note the value in both conditions, such as dark and bright.
- Pick a threshold halfway between them.
An ESP32 takes 3.3 V on its pins. Power a sensor from 3V3, or reduce its output with a divider.
Quick quiz
1. Which output gives a changing value?
2. What does the small screw on a sensor module set?
3. Why might an IR sensor fail outdoors?