Putting sensors and actuators together¶
Most interesting embedded projects sense something in the real world and then react. In this page you combine simple sensors and actuators on the ESP32 to create small interactive behaviors.
1. Light‑controlled LED (LDR + LED)¶
Goal: turn on an LED when it gets dark.
Hardware:
- 1× LDR (light‑dependent resistor)
- 1× fixed resistor (e.g. 10 kΩ)
- 1× LED + 220 Ω resistor
Wire the LDR and resistor as a voltage divider:
- One side of the LDR → 3.3 V.
- Other side of the LDR → analog input pin (e.g. GPIO 4) and one side of the 10 kΩ resistor.
- Other side of the 10 kΩ resistor → GND.
Wire the LED:
- GPIO 25 → 220 Ω resistor → LED anode (long leg).
- LED cathode (short leg) → GND.
Example sketch:
const int LDR_PIN = 4; // analog input
const int LED_PIN = 25; // digital output
// Adjust this threshold for your environment
const int THRESHOLD = 2000;
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
}
void loop() {
int lightValue = analogRead(LDR_PIN);
Serial.print("Light value: ");
Serial.println(lightValue);
if (lightValue < THRESHOLD) {
digitalWrite(LED_PIN, HIGH); // dark -> LED on
} else {
digitalWrite(LED_PIN, LOW); // bright -> LED off
}
delay(200);
}
Adjust THRESHOLD until the LED switches at the light level you want.
2. Button‑controlled buzzer (input + actuator)¶
Goal: play a tone when a button is pressed.
Hardware:
- 1Ă— push button
- 1× active buzzer (with built‑in oscillator)
Wiring:
- Button between GPIO 26 and GND.
- Buzzer + pin → GPIO 27 (through a suitable resistor if needed by your hardware).
Buzzer – pin → GND.
Example sketch:
const int BUTTON_PIN = 26;
const int BUZZER_PIN = 27;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP); // button to GND
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
int buttonState = digitalRead(BUTTON_PIN);
if (buttonState == LOW) { // pressed
digitalWrite(BUZZER_PIN, HIGH); // buzzer on
} else {
digitalWrite(BUZZER_PIN, LOW); // buzzer off
}
}
3. From thresholds to behavior¶
Once you can:
- read sensor values,
- apply simple rules (thresholds, ranges),
- and drive actuators,
you can build many variations:
- Temperature above X → turn on fan or heater.
- Light below Y → turn on street light.
- Distance below Z → beep faster as objects get closer.
Combine this page with the Serial Monitor, communication protocols, and your components pages to build small, realistic prototypes.