Robot vacuum cleaners and toy robots use infrared sensors to avoid bumping into things. The obstacle avoidance sensor sends out infrared light and watches for it to bounce back off something close. In this lesson, an LED and a buzzer warn you when something is in front of it.
What you'll learn
- How infrared obstacle sensors work
- How to set the detection distance
- How to combine two outputs (LED and buzzer)
What you need
- UNO R3 board and USB cable (UNO R3 Starter Kit)
- IR obstacle avoidance sensor module (45-in-1 Sensor Kit)
- 1 red LED and 1 resistor, 220 Ω (UNO R3 Starter Kit)
- Active buzzer (UNO R3 Starter Kit)
- Breadboard and jumper wires (UNO R3 Starter Kit)
Wiring

| From | To |
|---|---|
| Sensor GND | GND |
| Sensor + | 5V |
| Sensor OUT | UNO pin 2 |
| Sensor EN | Not connected (the jumper on the module keeps it switched on) |
| UNO pin 8 | 220 Ω resistor, then the LED's long leg |
| UNO pin 7 | Buzzer + (longer leg) |
| LED short leg and buzzer − | GND |
Sensor modules from different makers can label and order their pins differently. Always follow the labels printed on your module.
Set the distance
The module has two small knobs. Hold your hand about 10 cm in front of the sensor and turn the distance knob until the module's obstacle LED lights up. Then move your hand away and check that it goes off.
The sketch
const int SENSOR_PIN = 2;
const int LED_PIN = 8;
const int BUZZER_PIN = 7;
const int OBSTACLE = LOW; // most modules pull OUT LOW when something is close
void setup() {
Serial.begin(9600);
pinMode(SENSOR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
bool obstacle = digitalRead(SENSOR_PIN) == OBSTACLE;
digitalWrite(LED_PIN, obstacle ? HIGH : LOW);
if (obstacle) {
digitalWrite(BUZZER_PIN, HIGH); // short warning beeps
delay(60);
digitalWrite(BUZZER_PIN, LOW);
delay(140);
Serial.println("Obstacle!");
} else {
digitalWrite(BUZZER_PIN, LOW);
delay(50);
}
}
How it works
The clear LED on the module sends infrared light forward, and the dark one detects light that bounces back. When enough comes back, something is close, and OUT changes. The knob sets how much reflected light counts as an obstacle, which sets the distance. Dark objects reflect less, so they're detected at a shorter distance than light-coloured ones.
Try this next
- Compare the detection distance for a white sheet of paper and a black one.
- Combine this with the servo lesson to "turn away" when something is close.
- Count how many times something passed in front of the sensor.
Troubleshooting
- The alarm never stops: turn the distance knob down, and keep the sensor away from bright sunlight.
-
It's silent when it should beep: change
OBSTACLEtoHIGH. - Nothing is detected: check that the EN jumper is in place on the module.