← All posts Blog Post

Reading IR Sensor Values with ESP8266

Viktoria Builds

How to connect and use an IR sensor with ESP8266. Explains each pin, shows the wiring, and demonstrates reading both digital and analog values from the sensor.

Watch on YouTube

IR sensors are one of the most versatile components for robotics. They detect infrared light reflected from surfaces and are used for obstacle avoidance, line following, and proximity detection.

The sensor pins

Most IR sensor modules have three pins: VCC, GND, and a digital output. Some also expose an analog output pin.

  • VCC → 3.3V
  • GND → GND
  • Digital OUT → D1
  • Analog OUT → A0 (optional)

Reading the sensor

In digital mode the sensor outputs HIGH or LOW depending on whether it detects reflected IR light. The analog pin gives a raw value from 0 to 1023 — useful for measuring proximity more precisely.

The code

Full source: github.com/viktoriabuilds/esp8266-ir-sensor

const int IR_DIGITAL = D1;
const int IR_ANALOG  = A0;

void setup() {
  Serial.begin(115200);
  delay(1000);
  pinMode(IR_DIGITAL, INPUT);
  Serial.println();
  Serial.print("Start");
}

void loop() {
  int digitalState = digitalRead(IR_DIGITAL);
  int analogValue  = analogRead(IR_ANALOG);

  Serial.print("Digital: ");
  if (digitalState == HIGH) {
    Serial.print("HIGH");
  } else {
    Serial.print("LOW");
  }

  Serial.print("  Analog: ");
  Serial.println(analogValue);

  delay(500);
}

Open the Serial Monitor at 115200 baud. You will see both the digital state and the raw analog value printed every half second.

Tips

  • Adjust the onboard potentiometer to tune the detection threshold
  • Strong ambient light (especially sunlight) can interfere with readings
  • Works best on matte, non-reflective surfaces

Enjoying this tutorial?

Support the channel on Patreon and get early access to projects, build logs, and more.

Support on Patreon →