Welcome to Module 3! In our previous module, we relied on you manually pushing buttons like some kind of medieval peasant. Now, itâs time to make our Arduino smart enough to react to its environment automatically, so you donât have to babysit it.
Our first sensor is the Photoresistor, also known as a Light Dependent Resistor (LDR). It tells the Arduino if itâs bright or dark. Simple, effective, and it wonât judge you for staying up until 3 AM writing bad code.
A photoresistor allows your Arduino to measure ambient light.
A photoresistor is exactly what it sounds like: a resistor whose resistance changes depending on how much light hits its surface.
By placing a photoresistor in a circuit, we can use an analog pin on our Arduino to âreadâ the light level.
An Arduino cannot measure resistance directly; it can only measure voltage. To convert the changing resistance of the LDR into a changing voltage, we use a basic circuit called a Voltage Divider.
We need two resistors:
When they are connected in series between 5V and GND, the voltage at the point between them shifts depending on the light level. We connect this middle point to an Arduino analog pin.
Letâs build a classic âNight Lightâ circuit that turns on an LED when the room gets dark.
[Need to restock your components? Pick up a massive assortment of photoresistors and sensors here: photoresistors assortment]
We will read the analog voltage, print it to the Serial Monitor to see our baseline room light, and then turn on the LED if the value drops below a certain threshold.
const int ldrPin = A0; // Photoresistor connected to A0
const int ledPin = 9; // LED connected to Pin 9
int lightLevel = 0; // Variable to store the sensor reading
int threshold = 400; // The value at which it is considered "dark"
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // Start serial communication for debugging
}
void loop() {
lightLevel = analogRead(ldrPin); // Read the light level (0-1023)
Serial.print("Light Level: ");
Serial.println(lightLevel); // Print it to the monitor
// If the light level is lower than our threshold, turn the LED on
if (lightLevel < threshold) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(100); // Short delay to prevent flickering
}
Upload the code and open your Serial Monitor (magnifying glass icon in the top right). Cover the photoresistor with your hand and watch the numbers drop. Shine your phoneâs flashlight on it and watch them spike.
Depending on the lighting in your room, you might need to adjust the threshold variable in the code. If your room usually reads 600, and drops to 250 when you cover it, setting the threshold to 400 is perfect!
Now that we can sense light, letâs learn how to sense temperature. In Lesson 122, weâll introduce the TMP36 analog temperature sensor.