IR Obstacle Sensor Arduino: FC-51 Wiring, Range Setting and Code
FC-51 IR obstacle sensor with Arduino: IR LED and receiver, LM393 digital output, 2–30 cm range trimmer, black surfaces and sunlight, robot and counter code.
The FC-51 IR obstacle sensor is a small, cheap module that notices an object in front of it by the reflection of invisible infrared light and gives the Arduino a single digital signal. An IR LED shines constantly, the receiver next to it measures the light that comes back, and when the reflection crosses a threshold the output pin goes LOW. It doesn't measure distance; it only answers "is something in front of me?" with yes or no, which makes it ideal for obstacle-avoiding robots, object counters, touchless buttons and automatic dispensers.
In this guide you'll see the parts on the module, how to wire it to an Arduino Uno, ESP32 and Raspberry Pi Pico, how to set the range potentiometer properly, and how surface colour, shine and sunlight change the range. Then you'll build, step by step, a first test with an LED and buzzer, a noise-proof object counter, an obstacle-avoiding robot with two sensors, an interrupt-based counter on the ESP32 and MicroPython code for the Pico.
What is the FC-51 IR obstacle sensor and how does it work?
On the front of the module there are two parts side by side: the IR LED with a clear body and the dark IR receiver. If the infrared light from the LED hits an object and bounces back, the receiver senses it as a change in voltage. This weak signal goes to an LM393 comparator, which compares it with a threshold voltage set by the potentiometer. If the reflection is stronger than the threshold, the output goes LOW and the "obstacle" LED on the board lights up; if it's weaker, the output stays HIGH. So the module doesn't measure a distance but a reflection-strength threshold: a sheet of white paper is noticed from far away, black fabric only very close up. IR light is invisible to the eye, but if you look through most phones' front cameras you'll see the LED glowing purple-white, which is the easiest way to check that it works.
| Feature | Value |
|---|---|
| Supply | 3.3–5 V |
| Output | Digital; LOW with an obstacle, HIGH without |
| Detection range | 2–30 cm (manufacturer figure; real range depends on the surface) |
| Detection angle | About 35° |
| Comparator | LM393 |
| Current | A few tens of mA (the IR LED is always on) |
| Pins | VCC, GND, OUT |
Parts on the module
| Part | What it does |
|---|---|
| IR LED (clear) | Emits infrared light continuously |
| IR receiver (dark) | Turns the reflected light into a voltage |
| LM393 | Compares the receiver signal with the threshold and produces the digital output |
| Blue potentiometer | Sets the threshold and therefore the range |
| Power LED | Lights when the module is powered |
| Obstacle LED | Lights when the output is LOW, i.e. when an obstacle is seen |
FC-51 wiring: Arduino Uno, ESP32 and Pico
| FC-51 pin | Arduino Uno | ESP32 | Raspberry Pi Pico |
|---|---|---|---|
| VCC | 5V | 3V3 | 3V3(OUT), pin 36 |
| GND | GND | GND | GND |
| OUT | D2 | GPIO 27 | GP15 |
Setting the range: turning the potentiometer the right way
- Power the module; the power LED should light up. If the obstacle LED is on while nothing is in front of it, turn the potentiometer anticlockwise until it goes out.
- Place the object you want to detect (e.g. a white box) at the distance you want; for a robot, 10–15 cm is a good starting point.
- Slowly turn the potentiometer clockwise until the obstacle LED lights up, then back it off by about a quarter turn.
- Move the object away and closer to check that the LED goes off and on at the same point; if the LED flickers on its own with nothing in front, lower the sensitivity a little more.
- Do the adjustment in the real environment: a sensor set up on your desk behaves differently next to a window or in front of a wall of another colour.
The effect of surface colour, material and sunlight
Because the FC-51 looks at the amount of reflected light, two objects at the same distance can give different results. White and light-coloured matt surfaces reflect plenty of light in every direction, so they're detected from furthest away. Matt black surfaces swallow most of the infrared light; a black chair leg or a black cat is only seen from a few centimetres, sometimes not at all. Mirrors and shiny metal reflect light in one direction: if they face the sensor squarely they're detected from far away, if they're at an angle not at all. Glass and clear plastic let most of the light through. Some black plastics, on the other hand, behave like light colours in the infrared and are detected surprisingly well. The values below are typical indoor ranges with the potentiometer at its most sensitive setting; I recommend measuring with your own module and making your own table.
| Surface | Typical detection distance | Note |
|---|---|---|
| White paper, white wall | 10–20 cm | Best result |
| Light wood, cardboard | 8–15 cm | Good |
| Human hand | 5–12 cm | Varies with skin tone and angle |
| Grey or dark fabric | 3–8 cm | Needs higher sensitivity |
| Matt black plastic, black foam | 0–3 cm | Often not detected |
| Mirror, shiny metal | Depends on angle: far if square-on, none if tilted | Unreliable |
| Glass, clear plastic | Usually none | Light passes through |
Step by step: first test with Arduino (LED and buzzer)
Connect the module's VCC to 5V, GND to GND and OUT to D2. The Uno's built-in LED on D13 is enough as an indicator; for a sound alert, connect an active or passive buzzer between D8 and GND. The code below lights the LED, plays a 2 kHz tone when an obstacle is seen and prints the state to the Serial Monitor.
1// FC-51: OUT -> D2, engel varsa LED (D13) ve buzzer (D8)
2// FC-51: OUT -> D2, LED (D13) and buzzer (D8) when an obstacle is seen
3const int SENSOR_PIN = 2;
4const int LED_PIN = 13;
5const int BUZZER_PIN = 8;
6
7void setup() {
8 Serial.begin(9600);
9 pinMode(SENSOR_PIN, INPUT); // modülde pull-up var / the module has its own pull-up
10 pinMode(LED_PIN, OUTPUT);
11 pinMode(BUZZER_PIN, OUTPUT);
12}
13
14void loop() {
15 bool obstacle = (digitalRead(SENSOR_PIN) == LOW); // engel = LOW (aktif düşük) / obstacle = LOW (active low)
16 digitalWrite(LED_PIN, obstacle ? HIGH : LOW);
17 if (obstacle) {
18 tone(BUZZER_PIN, 2000); // 2 kHz uyarı / 2 kHz beep
19 } else {
20 noTone(BUZZER_PIN);
21 }
22 Serial.println(obstacle ? "Engel var / Obstacle" : "Yol acik / Clear");
23 delay(100);
24}The most important detail in the code is that the logic is inverted: digitalRead() returns LOW when there's an obstacle. pinMode() is left as INPUT because the module has its own pull-up resistor; INPUT_PULLUP does no harm either. tone() produces a specific frequency on a passive buzzer; with an active buzzer, digitalWrite(BUZZER_PIN, HIGH) instead of tone is enough. Printing to Serial every 100 ms is handy for testing; in a real project it's cleaner to print only when the state changes.
Object counter: edge detection and noise filtering
To count boxes passing on a belt or people walking through a door, you need to count not how long the output is LOW but the moment it goes from HIGH to LOW, that is, the edge. There's another problem: when the object is right at the edge of the range, the output can chatter for a few milliseconds and a single box gets counted several times. The code below solves this with a stability time: a new state isn't accepted until the raw reading has stayed unchanged for 30 ms. If you're counting small objects that pass quickly, lower it to 5–10 ms; if you're counting people, you can raise it to 100 ms. An example that uses two sensors to tell people coming in from people going out is in the Arduino people counter article.
1// FC-51 ile nesne sayacı: kararlı kenar algılama / object counter with a stable edge
2const int SENSOR_PIN = 2;
3const unsigned long STABLE_MS = 30; // durum en az 30 ms aynı kalmalı / state must hold for 30 ms
4
5unsigned long count = 0;
6bool stableState = HIGH; // HIGH = yol açık / clear
7bool lastRead = HIGH;
8unsigned long lastChange = 0;
9
10void setup() {
11 Serial.begin(9600);
12 pinMode(SENSOR_PIN, INPUT);
13}
14
15void loop() {
16 bool now = digitalRead(SENSOR_PIN);
17 if (now != lastRead) { // ham okuma değişti, sayacı sıfırla / raw value changed, restart timer
18 lastRead = now;
19 lastChange = millis();
20 }
21 if (millis() - lastChange >= STABLE_MS && now != stableState) {
22 stableState = now;
23 if (stableState == LOW) { // HIGH -> LOW: yeni nesne geldi / a new object arrived
24 count++;
25 Serial.print("Sayi / Count: ");
26 Serial.println(count);
27 }
28 }
29}An obstacle-avoiding robot with two sensors
If you place two FC-51 sensors at the front corners of the robot, angled outwards by about 30°, you'll also know which side the obstacle is on. If it's on the left, the robot turns right; if it's on the right, it turns left; if both see something, it first backs up and then turns on the spot. The motors are driven by an L298N motor driver: ENA and ENB set the speed via PWM, and IN1–IN4 set the direction. In the code below the left sensor goes to D2 and the right one to D3.
1// İki FC-51 + L298N ile engelden kaçan robot / obstacle-avoiding robot with two FC-51s + L298N
2const int LEFT_IR = 2, RIGHT_IR = 3; // sol ve sağ sensör / left and right sensor
3const int ENA = 5, IN1 = 6, IN2 = 7; // sol motor / left motor
4const int ENB = 10, IN3 = 8, IN4 = 9; // sağ motor / right motor
5const int SPEED = 160; // 0-255 PWM
6
7void drive(int left, int right) { // -1 geri, 0 dur, 1 ileri / -1 back, 0 stop, 1 forward
8 digitalWrite(IN1, left > 0); digitalWrite(IN2, left < 0);
9 digitalWrite(IN3, right > 0); digitalWrite(IN4, right < 0);
10 analogWrite(ENA, left ? SPEED : 0);
11 analogWrite(ENB, right ? SPEED : 0);
12}
13
14void setup() {
15 pinMode(LEFT_IR, INPUT);
16 pinMode(RIGHT_IR, INPUT);
17 int outs[] = {ENA, IN1, IN2, ENB, IN3, IN4};
18 for (int p : outs) pinMode(p, OUTPUT);
19}
20
21void loop() {
22 bool left = digitalRead(LEFT_IR) == LOW; // LOW = engel / obstacle
23 bool right = digitalRead(RIGHT_IR) == LOW;
24
25 if (left && right) { // ikisi de görüyor: geri çekil ve dön / both: back up and turn
26 drive(-1, -1); delay(300);
27 drive(1, -1); delay(350);
28 } else if (left) {
29 drive(1, -1); // engel solda: sağa dön / obstacle left: turn right
30 } else if (right) {
31 drive(-1, 1); // engel sağda: sola dön / obstacle right: turn left
32 } else {
33 drive(1, 1); // yol açık: ileri / clear: forward
34 }
35 delay(20);
36}This code is an idea and a starting point; the turn times and the SPEED value need tuning for your motors and battery voltage. Because the FC-51's range is short, a fast robot may hit the obstacle anyway; the faster it goes, the more range the sensor needs. The most robust way not to miss black obstacles is to combine the two IR sensors with an HC-SR04 at the front: the ultrasonic sensor catches the distant wall and the FC-51s catch the corners. For the chassis and assembly step by step, see the obstacle-avoiding robot article.
Interrupt-based counter with the ESP32
On the ESP32, power the module from the 3V3 pin and connect the output to GPIO 27. Doing the counting in an interrupt means no pass is missed even while the main loop is busy with Wi-Fi or a display. The interrupt function is marked with IRAM_ATTR and doesn't count a new edge unless 20 ms have passed since the last one, so a chattering output gives a single count. Because the ESP32 has two cores, the shared counter is protected with a portMUX critical section. If you'd like to send the count to the internet, you can add the method from the ESP32 Telegram bot article.
1// ESP32: FC-51 OUT -> GPIO 27 (modül 3V3 ile beslenir), kesmeyle sayaç
2// ESP32: FC-51 OUT -> GPIO 27 (module powered from 3V3), interrupt counter
3const int SENSOR_PIN = 27;
4const unsigned long DEAD_TIME_US = 20000; // 20 ms içindeki tekrarları yok say / ignore repeats within 20 ms
5
6volatile unsigned long count = 0;
7volatile unsigned long lastEdgeUs = 0;
8portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
9
10void IRAM_ATTR onObstacle() {
11 unsigned long t = micros();
12 if (t - lastEdgeUs > DEAD_TIME_US) {
13 portENTER_CRITICAL_ISR(&mux);
14 count++;
15 portEXIT_CRITICAL_ISR(&mux);
16 }
17 lastEdgeUs = t;
18}
19
20void setup() {
21 Serial.begin(115200);
22 pinMode(SENSOR_PIN, INPUT);
23 attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), onObstacle, FALLING); // HIGH -> LOW = engel geldi / obstacle arrived
24}
25
26void loop() {
27 static unsigned long shown = 0;
28 portENTER_CRITICAL(&mux);
29 unsigned long c = count;
30 portEXIT_CRITICAL(&mux);
31 if (c != shown) {
32 shown = c;
33 Serial.printf("Sayi / Count: %lu\n", c);
34 }
35 delay(50);
36}FC-51 with Raspberry Pi Pico and MicroPython
On the Pico, power the module from the 3V3(OUT) pin and connect the output to GP15. The MicroPython code below lights the board's onboard LED while there's an obstacle and counts passes with an IRQ that fires on falling edges; a 30 ms lockout filters out the chatter. Writing Pin("LED") selects the onboard LED on both the Pico and the Pico W. If this is your first time with the Pico, start with the what is the Raspberry Pi Pico article.
1# Raspberry Pi Pico: FC-51 OUT -> GP15, VCC -> 3V3(OUT), dahili LED ile gösterge
2# Raspberry Pi Pico: FC-51 OUT -> GP15, VCC -> 3V3(OUT), onboard LED as indicator
3from machine import Pin
4import time
5
6sensor = Pin(15, Pin.IN)
7led = Pin("LED", Pin.OUT) # Pico ve Pico W dahili LED / onboard LED on Pico and Pico W
8count = 0
9last_ms = 0
10
11def on_obstacle(pin):
12 global count, last_ms
13 now = time.ticks_ms()
14 if time.ticks_diff(now, last_ms) > 30: # 30 ms kilit / 30 ms lockout
15 count += 1
16 last_ms = now
17
18sensor.irq(trigger=Pin.IRQ_FALLING, handler=on_obstacle)
19
20shown = -1
21while True:
22 led.value(sensor.value() == 0) # engel varken LED yanar / LED on while blocked
23 if count != shown:
24 shown = count
25 print("Sayi / Count:", count)
26 time.sleep_ms(50)FC-51, TCRT5000 or HC-SR04: which one should you choose?

| Feature | FC-51 | TCRT5000 module | HC-SR04 |
|---|---|---|---|
| Method | IR reflection, threshold | IR reflection, very close | Ultrasonic echo |
| Range | ~2–30 cm (surface-dependent) | ~1–15 mm | 2–400 cm |
| Gives a distance? | No, only yes/no | Roughly (analog output) | Yes, in centimetres |
| Black surfaces | Poor | Tells black from white | Not affected |
| Sunlight | Clearly affected | Slightly affected | Not affected |
| Typical use | Robot corners, counters, touchless buttons | Line following, tachometer | Walls, parking sensor, level measurement |
In short, the FC-51 is the right choice for "did something come close?", the TCRT5000 for lines and marks on a surface, and the HC-SR04 for "how far away is it?". For a more detailed comparison, see the distance sensor comparison article.
FC-51 project ideas
- Touchless soap or sanitiser dispenser: when a hand comes within 5–8 cm, run a mini pump for half a second.
- Automatic bin lid: a servo opens the lid when a hand approaches; a detailed example is in the smart trash can article.
- Product counter on a belt: combine the counter code from this article with a 7-segment display and show the items that have passed.
- Table-edge warning: mount an FC-51 facing down under the robot; when the table ends the reflection disappears and the robot stops.
- Touchless light switch: wave your hand in front of the sensor and a relay module turns the lamp on or off.
Common mistakes and how to fix them
| Symptom | Likely cause | Fix |
|---|---|---|
| Obstacle LED always on | Sensitivity too high or sunlight | Turn the potentiometer anticlockwise, shade the sensor |
| Doesn't detect anything | Sensitivity at zero, IR LED faulty or object is black | Turn the potentiometer, check the LED through a phone camera, test with white paper |
| Code does the opposite | Active-low logic forgotten | Obstacle = LOW; write the condition as == LOW |
| Counter counts one object several times | Output chattering at the edge of the range | Add a stability or lockout time, make objects pass well inside the range |
| ESP32 behaves randomly | Module powered from 5 V | Power the module from 3V3 or add a divider on the output |
| Two sensors trigger each other | Light from one reaches the other's receiver | Point the sensors in different directions, put a small shield between them |
If you'd like to see the FC-51 in a real project, take a look at the Obstacle-Avoiding Robot, TCRT5000 black-and-white surface detection and L298N Bluetooth-controlled car projects in the BlueGrays app; each has a step-by-step circuit diagram and ready-to-use code. By adding the two-sensor code from this article to the robot projects, you can also catch obstacles at the corners.
Frequently asked questions
How far can an IR obstacle sensor detect?
For the FC-51 the manufacturer gives 2–30 cm, but the real range depends on the object's colour and surface. White paper is usually detected from 10–20 cm, a hand from 5–12 cm and a matt black object only from a few centimetres. You set the range with the potentiometer on the board.
Why doesn't the FC-51 detect black objects?
Matt black surfaces absorb most of the infrared light, so the light returning to the receiver isn't enough to cross the threshold. Raising the sensitivity helps a little, but the range still stays at a few centimetres. If black obstacles must be detected reliably too, use an ultrasonic sensor such as the HC-SR04.
Is the FC-51 output HIGH or LOW with an obstacle?
When an obstacle is detected the output goes LOW and the obstacle LED on the module lights up; with no obstacle the output is HIGH. This is called an active-low output. In your code, write the condition as digitalRead(pin) == LOW.
Can you measure distance with the FC-51?
No, the FC-51 only tells you whether a threshold has been crossed and gives no distance value. Because its output is digital, you can't tell 5 cm from 15 cm. For measurements in centimetres, use a distance sensor such as the HC-SR04 or VL53L0X.
Does the FC-51 work with an ESP32 at 3.3 V?
Yes, the module runs from 3.3 to 5 V. When you use it with an ESP32, power it from the 3V3 pin; that way the output is also 3.3 V and the ESP32 input stays safe. At 3.3 V the IR LED glows a little weaker, so the range may be slightly shorter than at 5 V.
Is the FC-51 the same as an IR remote receiver?
No. Remote receivers (e.g. the VS1838B) only react to infrared signals pulsing at 38 kHz and decode the codes coming from a remote. The FC-51 is an obstacle sensor that measures the reflection of its own LED and can't read remote codes. For remotes, see the IR receiver and remote article.
Projects to build after reading this
See all projects
HC-SR04 Distance Measurement (Serial Display)
The HC-SR04 sensor works just like a bat finding its way in the dark: it sends out a sound you cannot hear, listens for the echo and measures how far away the object in front of it is.

Obstacle Avoidance Robot
How about building a smart vehicle that finds its own way? The Obstacle Avoidance Robot constantly scans its surroundings thanks to the ultrasonic sensor in front of it.

Reading Reflection (Proximity) with TCRT5000
With a small sensor that sends out invisible light and measures how much bounces back, you can detect the surface in front of it.

TCRT5000 Black and White Surface Detection
With the little sensor that acts as the eye of line-following robots, you can tell whether the floor is black or white.

Bluetooth Controlled Car with L298N
Turn your phone into a remote and drive your own robot car. The Arduino receives commands from a remote-control app on your phone through a Bluetooth module and spins the wheels with a motor driver…

Laser Warning System
You set up an invisible beam fence, just like in the movies. A laser shines onto a light sensor on the other side; the moment someone walks through and breaks the beam, the LED lights up and the…

Motion Detector with Motion Sensor
A simple guard that tells you when someone walks into the room. The motion sensor picks up the warmth given off by the human body, and the Arduino keeps the LED on as long as there is movement and…

Parking Sensor with HC-SR04
A mini version of a car's parking sensor: the closer something gets, the faster the beeps.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

