Connect an IR sensor with an ESP32 and make an LED glow

To connect an IR sensor with an ESP32 and make an LED glow when the sensor detects something, here’s a simple Arduino code to get you started:

Components:

  • ESP32
  • IR Sensor
  • LED
  • Resistor (220 ohms, for the LED)

Wiring:

  1. IR Sensor:
    • VCC of IR sensor to 3.3V (or 5V) on ESP32.
    • GND of IR sensor to GND on ESP32.
    • OUT (signal) of IR sensor to any available GPIO pin (e.g., GPIO 18) on ESP32.
  2. LED:
    • Anode (long leg) of the LED to a GPIO pin (e.g., GPIO 19) on ESP32.
    • Cathode (short leg) of the LED to GND through a 220-ohm resistor.

Arduino Code:

// Pin definitions
const int irSensorPin = 18;   // Pin connected to IR sensor OUT
const int ledPin = 19;         // Pin connected to LED

void setup() {
  // Initialize the IR sensor pin as an input
  pinMode(irSensorPin, INPUT);
  
  // Initialize the LED pin as an output
  pinMode(ledPin, OUTPUT);
  
  // Start serial communication for debugging
  Serial.begin(115200);
}

void loop() {
  // Read the state of the IR sensor
  int sensorValue = digitalRead(irSensorPin);
  
  // If the IR sensor detects something (sensor value is LOW)
  if (sensorValue == LOW) {
    // Turn the LED ON
    digitalWrite(ledPin, HIGH);
    Serial.println("Object Detected: LED ON");
  } else {
    // Turn the LED OFF
    digitalWrite(ledPin, LOW);
    Serial.println("No Object: LED OFF");
  }
  
  // Delay to prevent excessive serial output
  delay(100);
}

How It Works:

  • The IR sensor’s output pin will be LOW when it detects an object (or the beam is interrupted).
  • The ESP32 reads the signal from the IR sensor.
  • If an object is detected, the ESP32 turns the LED ON.
  • If no object is detected, the LED will stay OFF.

Explanation:

  • pinMode(irSensorPin, INPUT);: Sets the IR sensor pin as input to read data.
  • digitalRead(irSensorPin);: Reads the IR sensor state. If it detects something, it returns LOW; otherwise, it returns HIGH.
  • digitalWrite(ledPin, HIGH);: Turns the LED on by setting the GPIO pin to HIGH.
  • Serial.print(): Prints messages to the Serial Monitor for debugging.

Note:

  • You can adjust the GPIO pins to any other available pins based on your setup.
  • The IR sensor typically works on 3.3V or 5V, so ensure your ESP32’s logic level matches the IR sensor’s requirements.

Upload the code to your ESP32, and when the IR sensor detects an object, the LED will glow.