Raspberry Pi Pico PID Line Follower Robot with 5-Channel IR Array, TB6612FNG & Obstacle Stop

Raspberry Pi Pico line follower robot with TB6612FNG driver, 5-channel IR sensor array, HC-SR04 sensor and OLED on a two-wheel chassis following a black line

Build a fast Raspberry Pi Pico line follower robot with PID steering, a 5-channel IR sensor array, a TB6612FNG motor driver, an ultrasonic obstacle stop and a live OLED status screen.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCURaspberry Pi Pico (RP2040)
  • Parts13 items
  • CodeMicroPython

Need it ready-made? Buy Ready Project

This Raspberry Pi Pico line follower robot tracks a black tape line on a white floor using a 5-channel IR sensor array and smooth PID steering. A TB6612FNG driver runs the two gear motors, an HC-SR04 ultrasonic sensor stops the robot before it hits anything placed on the track, and a small OLED shows what each sensor sees, the obstacle distance, the battery voltage and the run time.

It is a complete robotics combination project: sensors, motor control, a control loop, power regulation and a user interface, all written in MicroPython. It is ideal for college mini projects, robotics competitions and anyone who wants to understand how PID control really works on a moving robot.

Raspberry Pi Pico line follower robot with TB6612FNG driver, 5-channel IR sensor array, HC-SR04 sensor and OLED on a two-wheel chassis following a black line

How It Works

  • Reading the line: each of the five IR sensors shines infrared light at the floor. White reflects it and black absorbs it, so each digital output tells the Pico whether that sensor is over the line. Most modules output LOW over black; set LINE_IS_LOW to match yours.
  • Position error: the sensors get weights of -2, -1, 0, +1 and +2 from left to right. The average weight of the sensors that see the line is the error: 0 means the line is centred, a negative value means it is to the left, a positive value means it is to the right.
  • PID steering: the correction is KP × error + KI × integral + KD × change in error. The correction is added to the left wheel speed and taken away from the right wheel speed, so the robot turns back towards the line smoothly instead of zig-zagging.
  • Motor driver: the TB6612FNG is a MOSFET driver, so it wastes far less voltage than an L298N. The Pico drives its PWM pins at 20 kHz (silent) and uses the IN pins for direction. Setting both IN pins high gives a short brake for quick stops.
  • Lost line and crossings: if no sensor sees the line, the robot spins towards the side where it last saw it until it finds it again. If all five see black (a cross or a finish mark), it keeps going straight.
  • Obstacle stop: the HC-SR04 is read every 60 ms. If something is closer than 15 cm the robot brakes and the buzzer sounds; it moves on as soon as the path is clear.
  • Power: two 18650 cells (7.4V) feed the motors directly through the TB6612 VM pin, and a buck converter makes a clean 5V for the Pico VSYS pin and the ultrasonic sensor. A 10 kΩ and 4.7 kΩ divider lets the Pico ADC measure the battery and warn when it is low.

Components Required

  • Raspberry Pi Pico or Pico W (with headers) – 1
  • 5-channel IR line sensor array (TCRT5000 type, digital outputs) – 1
  • TB6612FNG dual motor driver module – 1
  • N20 or TT gear motors (6V, 200 to 300 RPM) with wheels – 2
  • Caster ball wheel – 1
  • HC-SR04 ultrasonic sensor – 1
  • 0.96 inch SSD1306 I2C OLED (128×64) – 1
  • 2S 18650 battery holder with switch and two 18650 cells (7.4V) – 1
  • Mini buck converter (MP1584 or LM2596) set to 5V – 1
  • Active buzzer module (3.3V) – 1
  • Tactile push button – 1
  • Resistors: 1 kΩ and 2 kΩ (echo divider), 10 kΩ and 4.7 kΩ (battery monitor) – 1 each
  • Robot chassis plate (acrylic or 3 mm MDF), jumper wires, screws and 19 mm black electrical tape for the track

Wiring Table

Part / pinPico pinNotes
IR array S1, S2, S3, S4, S5GP2, GP3, GP4, GP5, GP6S1 is the far-left sensor; power the array from 3V3
IR array VCC / GND3V3 (pin 36) / GND3.3V supply keeps outputs safe for the Pico
TB6612 PWMA / AIN1 / AIN2GP16 / GP17 / GP18Left motor on A01 and A02
TB6612 PWMB / BIN1 / BIN2GP22 / GP20 / GP21Right motor on B01 and B02
TB6612 STBYGP19Set HIGH by the code to enable the driver
TB6612 VCC / VM / GND3V3 / battery + (7.4V) / GNDVM takes the motor supply
HC-SR04 VCC / GNDBuck 5V / GNDSensor needs 5V
HC-SR04 TRIGGP143.3V trigger is enough
HC-SR04 ECHOGP15 through 1 kΩ, 2 kΩ to GNDNever connect the 5V ECHO pin directly
OLED SDA / SCLGP0 / GP1I2C0, address 0x3C
Push buttonGP10 to GNDStart and stop
Active buzzer +GP11Negative pin to GND
Battery monitorGP26 (ADC0)Battery + to 10 kΩ to GP26, 4.7 kΩ GP26 to GND
Buck converter OUT 5VVSYS (pin 39)Set to 5.0V with a meter before connecting the Pico

Connection Diagram

The illustration near the top shows how the parts sit on the chassis. It is a layout guide only. Follow the pin-accurate drawing below, which matches the wiring table exactly.

Raspberry Pi Pico Line Follower Robot – Pin-Accurate Wiring Power (2S 7.4V) Battery + to switch, then TB6612 VM and buck converter IN+ Buck OUT 5V to Pico VSYS (pin 39) and HC-SR04 VCC All grounds common: battery -, buck -, Pico GND, TB6612 GND Battery + to 10 kΩ to GP26, 4.7 kΩ from GP26 to GND IR array (3.3V) VCC to Pico 3V3 (pin 36), GND to GND S1 GP2, S2 GP3, S3 GP4, S4 GP5, S5 GP6 (S1 = far left) TB6612FNG VCC to 3V3, STBY to GP19 PWMA GP16, AIN1 GP17, AIN2 GP18 (left motor on A01/A02) PWMB GP22, BIN1 GP20, BIN2 GP21 (right motor on B01/B02) HC-SR04 TRIG to GP14 ECHO to 1 kΩ to GP15, 2 kΩ from GP15 to GND OLED + UI OLED SDA GP0, SCL GP1, VCC 3V3, GND Button GP10 to GND (internal pull-up) Buzzer + to GP11, – to GND
Pin-accurate connection diagram for the Raspberry Pi Pico line follower robot.

Mechanical Setup

  • Mount the IR array at the front, 5 to 10 mm above the floor and centred between the wheels. Too high and it cannot tell black from white; too low and it scrapes.
  • Place the motors at the back and the caster ball at the front, or the other way round, so the robot sits level. The sensor array should be about 6 to 10 cm ahead of the wheel axle for stable steering.
  • Fix the HC-SR04 at the front facing forward, a little above the floor so it does not see the track itself.
  • Keep the battery low and near the wheels so the robot does not tip on sharp turns.
  • Make the track with 19 mm black electrical tape on a white chart sheet or a light floor, with curves no tighter than about 10 cm radius at first.

Code

Flash the latest MicroPython UF2 for your board (Pico or Pico W) and open Thonny. Install the ssd1306 package from Tools > Manage packages (the robot still runs without the OLED if it is missing). Save the code below on the Pico as main.py so it starts on power-up. On a Pico W change the on-board LED line to Pin("LED", Pin.OUT).

# Raspberry Pi Pico PID Line Follower Robot
# 5-channel IR array + TB6612FNG + HC-SR04 obstacle stop + SSD1306 OLED
# MicroPython for Raspberry Pi Pico / Pico W
# Arduino Project Hub - ardiunoprojecthub.online

from machine import Pin, PWM, I2C, ADC, time_pulse_us
import time

try:
    import ssd1306          # install "ssd1306" from Thonny > Tools > Manage packages
    HAVE_OLED = True
except ImportError:
    HAVE_OLED = False

# ---------------- Tuning (change these for your robot) ----------------
BASE_SPEED   = 45      # % duty on a straight line (35-60 is typical)
MAX_SPEED    = 85      # % duty limit for any wheel
KP           = 14.0    # proportional gain
KI           = 0.0     # integral gain (keep 0 at first)
KD           = 55.0    # derivative gain
STOP_CM      = 15      # stop if an obstacle is closer than this
LINE_IS_LOW  = True    # True if the sensor output goes LOW over the black line
LOW_BATT_V   = 6.6     # warn below this battery voltage (2S Li-ion)
DIVIDER      = (10000 + 4700) / 4700   # battery divider ratio (10k top, 4.7k bottom)

# ---------------- Pins ----------------
ir = [Pin(p, Pin.IN) for p in (2, 3, 4, 5, 6)]   # S1 (far left) .. S5 (far right)
WEIGHTS = (-2, -1, 0, 1, 2)

pwma = PWM(Pin(16)); ain1 = Pin(17, Pin.OUT); ain2 = Pin(18, Pin.OUT)   # left motor
stby = Pin(19, Pin.OUT)
bin1 = Pin(20, Pin.OUT); bin2 = Pin(21, Pin.OUT); pwmb = PWM(Pin(22))   # right motor
pwma.freq(20000); pwmb.freq(20000)

trig = Pin(14, Pin.OUT, value=0)
echo = Pin(15, Pin.IN)            # through 1k / 2k divider (5V -> 3.3V)
button = Pin(10, Pin.IN, Pin.PULL_UP)
buzzer = Pin(11, Pin.OUT, value=0)
led = Pin(25, Pin.OUT)            # on-board LED (Pico). On Pico W use Pin("LED")
batt = ADC(26)

oled = None
if HAVE_OLED:
    try:
        i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
        oled = ssd1306.SSD1306_I2C(128, 64, i2c)
    except Exception:
        oled = None

# ---------------- Helpers ----------------
def motor(pwm, in1, in2, speed):
    """speed -100..100 (%)."""
    speed = max(-100, min(100, speed))
    if speed >= 0:
        in1.value(1); in2.value(0)
    else:
        in1.value(0); in2.value(1)
    pwm.duty_u16(int(abs(speed) * 655.35))

def drive(left, right):
    motor(pwma, ain1, ain2, left)
    motor(pwmb, bin1, bin2, right)

def brake():
    ain1.value(1); ain2.value(1); bin1.value(1); bin2.value(1)
    pwma.duty_u16(65535); pwmb.duty_u16(65535)

def read_line():
    """Returns list of 1 (on line) / 0 (off line) for S1..S5."""
    return [(0 if p.value() else 1) if LINE_IS_LOW else p.value() for p in ir]

def distance_cm():
    trig.value(0); time.sleep_us(2)
    trig.value(1); time.sleep_us(10); trig.value(0)
    t = time_pulse_us(echo, 1, 25000)      # 25 ms timeout (~4 m)
    if t < 0:
        return 999
    return t / 58.0

def battery_v():
    return batt.read_u16() * 3.3 / 65535 * DIVIDER

def beep(ms=80, times=1):
    for _ in range(times):
        buzzer.value(1); time.sleep_ms(ms)
        buzzer.value(0); time.sleep_ms(ms)

def show(l1, l2="", l3="", l4=""):
    if not oled:
        return
    oled.fill(0)
    for i, t in enumerate((l1, l2, l3, l4)):
        oled.text(t, 0, i * 16)
    oled.show()

# ---------------- Main ----------------
stby.value(1)
brake()
running = False
last_error = 0.0
integral = 0.0
last_seen = 0            # -1 line was on the left, +1 on the right
lap_start = time.ticks_ms()
last_ui = 0
last_sonar = 0
dist = 999
beep(60, 2)

while True:
    now = time.ticks_ms()

    # Start / stop button (active LOW) with simple debounce
    if button.value() == 0:
        time.sleep_ms(30)
        if button.value() == 0:
            running = not running
            brake()
            integral = 0; last_error = 0
            lap_start = now
            beep(120 if running else 40)
            while button.value() == 0:
                time.sleep_ms(10)

    # Ultrasonic every 60 ms (keeps the PID loop fast)
    if time.ticks_diff(now, last_sonar) > 60:
        dist = distance_cm()
        last_sonar = now

    s = read_line()
    count = sum(s)

    if not running:
        brake()
        state = "READY - press btn"
    elif dist < STOP_CM:
        brake()
        state = "OBSTACLE!"
        buzzer.value(1)
    else:
        buzzer.value(0)
        if count == 0:
            # Line lost: spin toward the side where it was last seen
            state = "SEARCH"
            if last_seen < 0:
                drive(-35, 45)
            else:
                drive(45, -35)
        elif count == 5:
            # All black: finish mark or cross line - go straight
            state = "CROSS"
            drive(BASE_SPEED, BASE_SPEED)
        else:
            error = sum(w * v for w, v in zip(WEIGHTS, s)) / count
            if error < 0: last_seen = -1
            elif error > 0: last_seen = 1
            integral = max(-50, min(50, integral + error))
            derivative = error - last_error
            last_error = error
            corr = KP * error + KI * integral + KD * derivative
            left = max(-MAX_SPEED, min(MAX_SPEED, BASE_SPEED + corr))
            right = max(-MAX_SPEED, min(MAX_SPEED, BASE_SPEED - corr))
            drive(left, right)
            state = "RUN e=%+.1f" % error

    # Screen and LED update 4 times a second
    if time.ticks_diff(now, last_ui) > 250:
        last_ui = now
        v = battery_v()
        led.toggle()
        secs = time.ticks_diff(now, lap_start) // 1000 if running else 0
        show(state,
             "IR " + "".join("#" if x else "." for x in s),
             "Dist %3d cm" % min(dist, 999),
             "Bat %.1fV  %ds%s" % (v, secs, " LOW" if v < LOW_BATT_V else ""))

    time.sleep_ms(5)

Tuning the PID

  • Set KI and KD to 0 and BASE_SPEED to about 35.
  • Raise KP until the robot follows gentle curves but wobbles slightly on straights.
  • Raise KD step by step (20, 40, 60) until the wobble goes away and turns become smooth.
  • Only add a small KI (0.2 to 1) if the robot always drifts to one side of the line.
  • Increase BASE_SPEED slowly and re-tune KP and KD at each step.

Testing

  • Lift the robot off the floor, switch it on and check the OLED shows READY and the five sensor marks.
  • Move a strip of black tape under each sensor and confirm the matching # appears on the OLED. Adjust the blue trimmer on each sensor if needed.
  • Press the button: both wheels should spin forward. If one spins backwards, swap that motor’s two wires on the TB6612.
  • Put your hand 10 cm in front of the ultrasonic sensor: the wheels should stop and the buzzer should sound.
  • Place the robot on the track, press the button and tune the PID values.

Troubleshooting

ProblemFix
Robot turns away from the lineThe sensor order or the motors are swapped. Check S1 is on the left, or swap the left and right motor connections on the driver.
Sensors always read black or always whiteAdjust each sensor’s trimmer, change LINE_IS_LOW, and keep the array 5 to 10 mm above the floor. Strong sunlight can blind IR sensors.
Pico resets when the motors startThe motors are pulling the supply down. Use charged 18650 cells, keep the buck converter on its own wires from the battery, and add a 470 µF capacitor across VM and GND.
Robot wobbles on straight linesLower KP or raise KD, and reduce BASE_SPEED.
Robot overshoots sharp curvesLower BASE_SPEED or raise KP; move the sensor array further ahead of the wheels.
Stops for no reasonThe ultrasonic sensor sees the floor or the track edge. Point it slightly upward or reduce STOP_CM.
OLED stays blankCheck SDA on GP0 and SCL on GP1, and that the ssd1306 package is installed. Some modules use address 0x3D.

Ideas to Extend

  • Use a Pico W to send the live error and speed to a phone web page for wireless PID tuning.
  • Add wheel encoders and log lap times to the OLED for competition practice.
  • Use an 8-channel analog sensor array with the Pico ADC for even smoother steering.

Arduino Obstacle Avoiding & Bluetooth Robot Car with L298N, HC-SR04 and Servo

Wiring diagram of Arduino obstacle avoiding and Bluetooth robot car with L298N, HC-SR04, servo and HC-05

Build an Arduino obstacle avoiding robot car that also drives from your phone over HC-05 Bluetooth: L298N motor driver, HC-SR04 on an SG90 servo scanner, buzzer, wiring table, diagram and full code.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUArduino Uno / Nano
  • Parts11 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This Arduino obstacle avoiding robot car is a two-in-one build. In AUTO mode it drives by itself, uses an HC-SR04 ultrasonic sensor mounted on an SG90 servo to spot walls, then looks left and right and turns towards the clearer path. In MANUAL mode you drive it from your Android phone over an HC-05 Bluetooth module, and it still refuses to drive forward into a wall.

It is a big, combination-level project that brings together motor control with the L298N driver, PWM speed control, ultrasonic distance measurement, servo scanning, Bluetooth serial commands and simple decision-making. Everything runs on a single Arduino Uno (ATmega328P).

Arduino obstacle avoiding robot car wiring with L298N, HC-SR04 on SG90 servo, HC-05 Bluetooth and buzzer

How the Robot Car Works

  • Motor driver: the Arduino cannot power motors directly, so the L298N dual H-bridge does the heavy lifting. IN1/IN2 and IN3/IN4 set the direction of each motor, while PWM on ENA (D5) and ENB (D6) sets the speed.
  • Seeing obstacles: the HC-SR04 sends a 40 kHz ultrasonic pulse and times the echo. Distance in cm is the echo time in microseconds divided by 58. The code takes three readings and uses the middle one to ignore false spikes.
  • AUTO mode: above 45 cm the car drives at full set speed, between 25 and 45 cm it slows down, and under 25 cm it stops, beeps, backs up a little and turns the servo to measure the left and right sides. It turns towards the side with more space, or turns around if both sides are blocked.
  • MANUAL mode: the HC-05 receives single-letter commands (F, B, L, R, S and more) from a free Bluetooth RC car app or any serial terminal app. Keys 0 to 9 set the speed.
  • Safety features: the car starts in MANUAL mode and stopped. In manual mode it stops if no command arrives for 1.5 seconds (for example when you walk out of range), and a forward command is ignored if an obstacle is closer than 25 cm.
  • Feedback: the buzzer beeps on obstacles and mode changes, and the robot sends the measured left and right distances back to your phone app.

Components Required

  • Arduino Uno R3 (ATmega328P) or Arduino Nano – 1
  • L298N dual H-bridge motor driver module – 1
  • BO gear motors (3–6 V) with wheels – 2
  • 2WD robot car chassis with caster wheel – 1
  • HC-SR04 ultrasonic distance sensor – 1
  • SG90 micro servo with sensor bracket – 1
  • HC-05 Bluetooth module – 1
  • Active buzzer (5 V) – 1
  • Resistors: 1 kΩ and 2 kΩ (voltage divider for HC-05 RXD) – 1 each
  • 2 × 18650 Li-ion cells (7.4 V) with holder and an on/off switch – 1 set
  • Jumper wires (male-female and male-male)

Wiring Table

Module pinArduino Uno pinNotes
L298N ENAD5 (PWM)Remove the ENA jumper cap first
L298N IN1 / IN2D7 / D8Left motor direction
L298N ENBD6 (PWM)Remove the ENB jumper cap first
L298N IN3 / IN4A0 / A1Right motor direction (analog pins used as digital)
L298N OUT1 / OUT2Left motorSwap the two wires if it runs backwards
L298N OUT3 / OUT4Right motorSwap the two wires if it runs backwards
L298N 12V terminalBattery + (7.4 V)Through the on/off switch
L298N GNDBattery – and Arduino GNDCommon ground is essential
L298N 5V outputServo red, HC-SR04 VCC, HC-05 VCCKeep the 5V-EN jumper on
Arduino VINBattery + (after switch)Powers the Arduino from the same pack
HC-SR04 TRIG / ECHOA2 / A3GND to common ground
SG90 signal (orange)D10Brown wire to GND
HC-05 TXDD2SoftwareSerial RX
HC-05 RXDD4 through 1 kΩ, with 2 kΩ to GNDDrops 5 V to about 3.3 V for the HC-05
Active buzzer +A4Buzzer – to GND

Connection Diagram

The illustration above shows the general layout of the robot. The pin-accurate drawing below matches the wiring table exactly, so follow this one when you connect the wires.

Arduino Obstacle Avoiding & Bluetooth Robot Car – Pin-Accurate Wiring Arduino Uno D5 (PWM) L298N ENA (remove ENA jumper) – left motor speed D7 L298N IN1 D8 L298N IN2 D6 (PWM) L298N ENB (remove ENB jumper) – right motor speed A0 L298N IN3 A1 L298N IN4 A2 HC-SR04 TRIG A3 HC-SR04 ECHO D10 SG90 servo signal (orange) D2 HC-05 TXD D4 1k ohm -> HC-05 RXD (2k ohm from RXD to GND) A4 Active buzzer + (buzzer – to GND) VIN Battery + (7.4 V) – same wire as L298N 12V terminal GND Battery -, L298N GND and every module GND (common) L298N 5V output -> servo red wire, HC-SR04 VCC and HC-05 VCC. L298N OUT1/OUT2 -> left motor, OUT3/OUT4 -> right motor. Keep the 5V-EN jumper on the L298N (battery under 12 V). Swap a motor’s two wires if it spins the wrong way.
Pin-accurate connection diagram for the Arduino obstacle avoiding and Bluetooth robot car.

Arduino Code

Open the Arduino IDE, select Arduino Uno as the board and upload the sketch below. It only uses the built-in Servo and SoftwareSerial libraries, so nothing extra needs to be installed. Disconnect the HC-05 TXD wire from D2 while uploading if the upload fails. The sketch compiles to about 6.4 KB.

/*
  Arduino Obstacle Avoiding & Bluetooth Robot Car
  Board : Arduino Uno / Nano (ATmega328P)
  Parts : L298N motor driver, 2 x BO gear motors, HC-SR04 ultrasonic sensor
          on an SG90 servo, HC-05 Bluetooth module, active buzzer

  Two modes:
    AUTO   - drives forward, stops when something is closer than STOP_CM,
             looks left and right with the servo and turns to the clearer side.
    MANUAL - you drive it from any Android "Bluetooth RC Car" / serial
             terminal app over the HC-05.

  Bluetooth commands (single characters, 9600 baud):
    F = forward   B = back   L = left   R = right   S = stop
    G = forward-left   I = forward-right  (used by most RC car apps)
    0..9 = speed (0 = slowest, 9 = full)   q = full speed
    A = switch to AUTO mode     M = switch to MANUAL mode
    V = horn (buzzer beep)
*/

#include <Servo.h>
#include <SoftwareSerial.h>

// ---------- Pin map (matches the wiring table) ----------
const uint8_t ENA = 5;    // L298N ENA (PWM) - left motor speed
const uint8_t IN1 = 7;    // L298N IN1       - left motor direction
const uint8_t IN2 = 8;    // L298N IN2
const uint8_t ENB = 6;    // L298N ENB (PWM) - right motor speed
const uint8_t IN3 = A0;   // L298N IN3       - right motor direction
const uint8_t IN4 = A1;   // L298N IN4
const uint8_t TRIG_PIN = A2;   // HC-SR04 TRIG
const uint8_t ECHO_PIN = A3;   // HC-SR04 ECHO
const uint8_t SERVO_PIN = 10;  // SG90 signal (orange wire)
const uint8_t BUZZER_PIN = A4; // active buzzer +
const uint8_t BT_RX = 2;       // Arduino receives here  <- HC-05 TXD
const uint8_t BT_TX = 4;       // Arduino sends here     -> divider -> HC-05 RXD

// ---------- Tuning ----------
const int STOP_CM = 25;        // obstacle distance that makes the robot stop
const int SLOW_CM = 45;        // start slowing down below this distance
const int SERVO_CENTER = 90;   // adjust if the sensor does not face straight ahead
const int SERVO_LEFT = 165;
const int SERVO_RIGHT = 15;
const int TURN_MS = 380;       // time for roughly a 90 degree turn (tune on your floor)

Servo scanner;
SoftwareSerial bt(BT_RX, BT_TX);

enum Mode { MANUAL, AUTO };
Mode mode = MANUAL;            // start safely in MANUAL (stopped)
int speedPwm = 200;            // 0..255 motor speed
unsigned long lastCmdMs = 0;   // for the manual-mode safety timeout

// ---------- Motor helpers ----------
// dirL / dirR: 1 = forward, -1 = backward, 0 = stop
void drive(int dirL, int dirR, int pwm) {
  digitalWrite(IN1, dirL > 0);
  digitalWrite(IN2, dirL < 0);
  digitalWrite(IN3, dirR > 0);
  digitalWrite(IN4, dirR < 0);
  analogWrite(ENA, dirL == 0 ? 0 : pwm);
  analogWrite(ENB, dirR == 0 ? 0 : pwm);
}
void forward(int pwm)  { drive(1, 1, pwm); }
void backward(int pwm) { drive(-1, -1, pwm); }
void spinLeft(int pwm) { drive(-1, 1, pwm); }
void spinRight(int pwm){ drive(1, -1, pwm); }
void stopMotors()      { drive(0, 0, 0); }

void beep(int ms) {
  digitalWrite(BUZZER_PIN, HIGH);
  delay(ms);
  digitalWrite(BUZZER_PIN, LOW);
}

// ---------- Ultrasonic ----------
// Returns distance in cm, or 400 when nothing echoes back (open space).
int readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(3);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, 25000UL);  // 25 ms timeout ~ 4 m
  if (us == 0) return 400;
  return (int)(us / 58UL);
}

// Take three readings and return the middle one to ignore odd spikes.
int medianDistance() {
  int a = readDistanceCm(); delay(8);
  int b = readDistanceCm(); delay(8);
  int c = readDistanceCm();
  if ((a <= b && b <= c) || (c <= b && b <= a)) return b;
  if ((b <= a && a <= c) || (c <= a && a <= b)) return a;
  return c;
}

int lookAt(int angle) {
  scanner.write(angle);
  delay(350);                 // let the servo arrive and stop shaking
  return medianDistance();
}

// ---------- AUTO mode ----------
void autoStep() {
  int front = medianDistance();

  if (front > SLOW_CM) {
    forward(speedPwm);
  } else if (front > STOP_CM) {
    forward(max(120, speedPwm / 2));   // slow down near objects
  } else {
    // Obstacle: stop, back off a little, then look both ways
    stopMotors();
    beep(80);
    backward(170);
    delay(250);
    stopMotors();

    int left = lookAt(SERVO_LEFT);
    int right = lookAt(SERVO_RIGHT);
    scanner.write(SERVO_CENTER);
    delay(200);

    bt.print(F("Obstacle! L=")); bt.print(left);
    bt.print(F("cm R=")); bt.print(right); bt.println(F("cm"));

    if (left < STOP_CM && right < STOP_CM) {
      // Dead end: turn around
      spinRight(200);
      delay(TURN_MS * 2);
    } else if (left > right) {
      spinLeft(200);
      delay(TURN_MS);
    } else {
      spinRight(200);
      delay(TURN_MS);
    }
    stopMotors();
    delay(100);
  }
}

// ---------- Bluetooth commands ----------
void handleCommand(char c) {
  lastCmdMs = millis();
  if (c >= '0' && c <= '9') {             // speed 0..9 -> PWM 110..255
    speedPwm = map(c - '0', 0, 9, 110, 255);
    return;
  }
  switch (c) {
    case 'q': speedPwm = 255; break;
    case 'A':
      mode = AUTO;
      scanner.write(SERVO_CENTER);
      beep(60); delay(80); beep(60);
      bt.println(F("AUTO mode"));
      break;
    case 'M':
      mode = MANUAL;
      stopMotors();
      beep(150);
      bt.println(F("MANUAL mode"));
      break;
    case 'V': beep(200); break;
  }
  if (mode != MANUAL) return;              // drive keys only work in MANUAL

  switch (c) {
    case 'F':
      // Even in manual mode, refuse to drive into a wall
      if (readDistanceCm() <= STOP_CM) { stopMotors(); beep(40); }
      else forward(speedPwm);
      break;
    case 'B': backward(speedPwm); break;
    case 'L': spinLeft(speedPwm); break;
    case 'R': spinRight(speedPwm); break;
    case 'G': drive(0, 1, speedPwm); break;   // forward-left (pivot)
    case 'I': drive(1, 0, speedPwm); break;   // forward-right (pivot)
    case 'S': stopMotors(); break;
  }
}

void setup() {
  pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  stopMotors();

  scanner.attach(SERVO_PIN);
  scanner.write(SERVO_CENTER);

  Serial.begin(9600);   // USB debug
  bt.begin(9600);       // HC-05 default baud rate
  bt.println(F("Robot ready. Send A for AUTO, M for MANUAL."));
  beep(100);
}

void loop() {
  while (bt.available()) {
    char c = bt.read();
    if (c != '\r' && c != '\n') handleCommand(c);
  }

  if (mode == AUTO) {
    autoStep();
  } else {
    // Safety: stop if the phone stops sending for 1.5 s (out of range)
    if (millis() - lastCmdMs > 1500) stopMotors();
  }
}

Bluetooth Commands

CommandAction
ASwitch to AUTO (obstacle avoiding) mode
MSwitch to MANUAL mode and stop
F / BForward / backward
L / RSpin left / spin right
G / IForward-left / forward-right pivot
SStop
0 to 9, qSet speed (0 slowest, 9 or q full speed)
VHorn (buzzer beep)

Setup and Testing

  • Lift the car so the wheels are off the table, switch on the battery and pair your phone with the HC-05 (default PIN 1234 or 0000).
  • Open a Bluetooth RC car or serial terminal app, connect to the HC-05 and press F. Both wheels should turn forward. If one turns backwards, swap that motor’s two wires on the L298N.
  • Hold your hand 15 cm in front of the sensor and press F again. The car should beep and refuse to move forward.
  • Put the car on the floor and send A. It should drive, slow down near objects, stop, scan left and right, and turn away.
  • Tune TURN_MS so one turn is about 90 degrees on your floor, and change SERVO_CENTER if the sensor does not face straight ahead.

Power Tips

Two 18650 cells (7.4 V) are a good choice. The L298N drops about 2 V across its transistors, so the motors get roughly 5 to 6 V, which suits BO motors. Do not power the motors from the Arduino 5V pin or a 9 V PP3 battery; the 9 V battery cannot give enough current and the robot will keep resetting. Always join all grounds together.

Troubleshooting

ProblemFix
Car resets or the servo twitches when motors startUse fresh 18650 cells, add a 470 uF capacitor across the 5V and GND rails, and keep motor wires away from signal wires.
Motors hum but do not turnSpeed is too low. Send 9 or q, or raise the minimum value in the map() line.
Always sees an obstacleCheck TRIG and ECHO are not swapped and that the sensor is not pointing at the floor or chassis.
Phone connects but car does not respondHC-05 TXD must go to D2, and the baud rate must be 9600. Check the 1 kΩ / 2 kΩ divider on RXD.
Car stops by itself in manual modeUse an app that repeats the command while the button is held; the 1.5 s safety timeout stops the car otherwise.
Turns too much or too littleAdjust TURN_MS in the sketch.

Ideas to Extend

  • Add two IR line sensors and a third mode for line following.
  • Add IR sensors on the sides for better wall following in narrow spaces.
  • Replace the Uno and HC-05 with an ESP32 to drive the car from a web page over Wi-Fi.
  • Add an MPU6050 gyro so turns are exactly 90 degrees regardless of floor or battery level.

IR Remote Controlled Stepper Motor with Arduino Uno, 28BYJ-48 and ULN2003

Arduino Uno wired to a ULN2003 driver, 28BYJ-48 stepper motor, IR receiver and remote control

Control a 28BYJ-48 stepper motor with any IR remote using Arduino Uno and ULN2003: precise 45° moves, absolute angles, speed control, wiring table, tested IRremote code and Hindi explanation.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUArduino Uno
  • Parts7 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Arduino Uno wired to a ULN2003 driver, 28BYJ-48 stepper motor, IR receiver and remote control

Stepper motors move in precise, repeatable steps, which is why they are used in 3D printers, CNC machines, camera sliders and automatic curtain openers. In this beginner project you will build an IR remote controlled stepper motor with Arduino Uno, a 28BYJ-48 stepper and the ULN2003 driver board. Using an ordinary TV/”Car MP3″ infrared remote you can rotate the shaft by exactly 45°, jump to fixed angles, run it continuously in either direction, change the speed and send it back to the home position.

The 28BYJ-48 + ULN2003 kit costs very little, runs from 5 V and needs no special power supply for light loads, so it is the perfect first stepper project. You will find the components list, a pin-to-pin wiring table, compile-tested code, a full explanation, troubleshooting tips, an FAQ and a simple Hindi explanation below.

How It Works

The 28BYJ-48 is a small unipolar geared stepper motor. Its internal motor makes 32 full steps per revolution and a 1:64 (approximately) gearbox reduces that, so the output shaft needs about 2048 steps for one full turn in full-step mode. That gives roughly 0.18° per step – very fine positioning. The Arduino cannot drive the coils directly (they need more current than a pin can provide), so the ULN2003 Darlington transistor array switches the four coils on and off when the Arduino sets IN1–IN4 HIGH or LOW.

The IR receiver (VS1838B or TSOP1838) receives the 38 kHz light pulses from the remote and outputs a digital signal. The IRremote library decodes the NEC protocol used by most cheap remotes and gives us a one-byte command code for each key. The sketch maps those codes to actions such as “rotate 45° clockwise”.

Components Required

  • Arduino Uno R3 (or Nano) – 1
  • 28BYJ-48 5 V stepper motor – 1
  • ULN2003 stepper driver board – 1 (usually sold together with the motor)
  • IR receiver: VS1838B / TSOP1838 or a 3-pin IR receiver module – 1
  • IR remote (21-key “Car MP3” NEC remote, or any NEC TV remote) – 1
  • Breadboard and jumper wires
  • USB cable; optional separate 5 V 1 A supply for the motor

Wiring Table (Pin-to-Pin)

ModuleModule PinArduino Uno PinNotes
ULN2003 boardIN1D8Stepper pins are passed as 8, 10, 9, 11 in code (IN1, IN3, IN2, IN4)
ULN2003 boardIN2D9
ULN2003 boardIN3D10
ULN2003 boardIN4D11
ULN2003 board+ (5–12V)5VFor a light load; use an external 5 V supply for heavier loads
ULN2003 board– (GND)GNDCommon ground is required if you use an external supply
28BYJ-485-pin connectorULN2003 white socketKeyed plug – only fits one way
IR receiverOUT / SD2IR_RECEIVE_PIN = 2
IR receiverGND / –GNDCheck pin order printed on your module
IR receiverVCC / +5V

Bare VS1838B receivers have the pin order OUT – GND – VCC when you look at the dome from the front, but 3-pin modules vary, so always follow the labels on your board. Make sure the ULN2003 board’s power jumper is fitted, otherwise the motor gets no power.

Libraries Used (with Licenses)

Complete Arduino Code

Board used for the compile test: Arduino Uno (arduino:avr core) with IRremote 4.x. It compiled without errors (about 11.6 KB of flash).

// Arduino Uno IR Remote Controlled 28BYJ-48 Stepper Motor (ULN2003 driver)
// Libraries: IRremote (Arduino-IRremote, MIT) 4.x and Stepper (Arduino, LGPL-2.1)
#include <IRremote.hpp>
#include <Stepper.h>

const int IR_RECEIVE_PIN = 2;          // VS1838B / TSOP1838 OUT pin
const int STEPS_PER_REV  = 2048;       // 28BYJ-48 in full-step mode
// ULN2003 IN1=D8, IN2=D9, IN3=D10, IN4=D11 -> pass in order IN1, IN3, IN2, IN4
Stepper motor(STEPS_PER_REV, 8, 10, 9, 11);

// Command codes of the common 21-key "Car MP3" NEC remote.
// Your remote may differ: open Serial Monitor, press a key and copy the code shown.
const uint8_t KEY_PREV  = 0x44;   // |<<  : 45 degrees counter-clockwise
const uint8_t KEY_NEXT  = 0x40;   // >>|  : 45 degrees clockwise
const uint8_t KEY_PLAY  = 0x43;   // >||  : start / stop continuous rotation
const uint8_t KEY_MINUS = 0x07;   // -    : slower
const uint8_t KEY_PLUS  = 0x15;   // +    : faster
const uint8_t KEY_EQ    = 0x09;   // EQ   : change continuous direction
const uint8_t KEY_ZERO  = 0x16;   // 0    : go back to home position
const uint8_t KEY_DIGIT[9] = {0x0C, 0x18, 0x5E, 0x08, 0x1C, 0x5A, 0x42, 0x52, 0x4A}; // 1..9

int rpm = 10;                 // 28BYJ-48 works well between 5 and 15 RPM
bool continuous = false;
int direction = 1;            // 1 = clockwise, -1 = counter-clockwise
long position = 0;            // steps from the home position

void releaseCoils() {         // switch coils off so the motor and driver stay cool
  for (int pin = 8; pin <= 11; pin++) digitalWrite(pin, LOW);
}

void moveSteps(long steps) {
  motor.step(steps);
  position += steps;
  releaseCoils();
}

void setup() {
  Serial.begin(9600);
  motor.setSpeed(rpm);
  IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK);
  Serial.println(F("IR Stepper ready. Press a key on the remote."));
}

void loop() {
  if (IrReceiver.decode()) {
    uint8_t cmd = IrReceiver.decodedIRData.command;
    bool isRepeat = IrReceiver.decodedIRData.flags & IRDATA_FLAGS_IS_REPEAT;
    IrReceiver.resume();

    if (!isRepeat) {
      Serial.print(F("Key code: 0x"));
      Serial.println(cmd, HEX);

      if (cmd == KEY_NEXT)       { continuous = false; moveSteps(STEPS_PER_REV / 8); }
      else if (cmd == KEY_PREV)  { continuous = false; moveSteps(-STEPS_PER_REV / 8); }
      else if (cmd == KEY_PLAY)  { continuous = !continuous; if (!continuous) releaseCoils(); }
      else if (cmd == KEY_EQ)    { direction = -direction; }
      else if (cmd == KEY_PLUS)  { rpm = min(rpm + 2, 15); motor.setSpeed(rpm); }
      else if (cmd == KEY_MINUS) { rpm = max(rpm - 2, 3);  motor.setSpeed(rpm); }
      else if (cmd == KEY_ZERO)  { continuous = false; moveSteps(-position); }
      else {
        for (int i = 0; i < 9; i++) {
          if (cmd == KEY_DIGIT[i]) {   // digit n -> absolute angle n x 40 degrees
            continuous = false;
            long target = (long)(i + 1) * STEPS_PER_REV * 40L / 360L;
            moveSteps(target - position);
          }
        }
      }
      Serial.print(F("RPM: ")); Serial.print(rpm);
      Serial.print(F("  Position (deg): ")); Serial.println(position * 360.0 / STEPS_PER_REV, 1);
    }
  }

  if (continuous) {
    motor.step(direction * 8);         // small chunks keep the remote responsive
    position = (position + direction * 8) % STEPS_PER_REV;
  }
}

Remote Key Map

KeyCode (hex)Action
>>| (Next)0x40Rotate 45° clockwise
|<< (Prev)0x44Rotate 45° counter-clockwise
>|| (Play/Pause)0x43Start/stop continuous rotation
EQ0x09Reverse the continuous direction
+ / –0x15 / 0x07Speed up / slow down (3–15 RPM)
1 – 90x0C … 0x4AGo to an absolute angle of 40°, 80° … 360°
00x16Return to the home (start) position

Code Explanation

  • Stepper motor(2048, 8, 10, 9, 11): the 28BYJ-48 needs its coils energised in the order IN1-IN3-IN2-IN4 with the Arduino Stepper library, which is why the middle two pins are swapped. If you pass 8, 9, 10, 11 the motor only vibrates.
  • IrReceiver.begin(2, ENABLE_LED_FEEDBACK) starts the decoder; the Uno’s on-board LED (D13) blinks every time an IR signal is received – a quick wiring check.
  • decodedIRData.command is the 8-bit key code. Repeat frames (sent when a key is held) are ignored so one press = one action.
  • moveSteps() moves the motor, updates the position counter and then calls releaseCoils(), which sets IN1–IN4 LOW so the motor and ULN2003 do not heat up while idle.
  • Digit keys calculate an absolute target: n × 2048 × 40 / 360 steps, then move by the difference from the current position.
  • Continuous mode moves 8 steps per loop so the remote is checked between small moves and the motor reacts immediately when you press Play again.
  • Every key press prints its hex code, the speed and the shaft angle to the Serial Monitor at 9600 baud.

Step-by-Step Build Instructions

  1. Install IRremote by Armin Joachimsmeyer from the Library Manager (version 4.x). The Stepper library is built in.
  2. Plug the 28BYJ-48 cable into the ULN2003 board.
  3. Connect IN1–IN4 of the ULN2003 to D8–D11 of the Uno, and its + and – pins to 5V and GND.
  4. Insert the IR receiver into the breadboard and connect OUT → D2, GND → GND, VCC → 5V.
  5. Upload the code with board Arduino Uno selected.
  6. Open the Serial Monitor at 9600 baud and press any key on the remote. You should see “Key code: 0x…”. If your remote shows different codes, copy them into the KEY_… constants at the top of the sketch and upload again.
  7. Press >>| – the shaft turns 45° clockwise. Press 0 to return home. Try Play for continuous rotation and + / – to change speed.
  8. Attach a small pointer or a cardboard disc to the shaft to see the angles clearly.

सरल हिंदी में समझें (Simple Hindi Explanation)

इस प्रोजेक्ट में हम एक साधारण IR रिमोट से स्टेपर मोटर को कंट्रोल करते हैं। स्टेपर मोटर छोटे-छोटे कदमों (steps) में घूमती है – 28BYJ-48 मोटर को एक पूरा चक्कर लगाने के लिए लगभग 2048 steps चाहिए। Arduino सीधे मोटर को करंट नहीं दे सकता, इसलिए बीच में ULN2003 ड्राइवर बोर्ड लगाया जाता है।

IR रिसीवर रिमोट के बटन का कोड पढ़कर Arduino को देता है। कोड में हर बटन का काम तय किया गया है – जैसे >>| दबाने पर मोटर 45° घूमती है, Play दबाने पर लगातार घूमती है, + और – से स्पीड बदलती है और 0 दबाने पर मोटर अपनी शुरुआती जगह (home) पर लौट आती है। अगर आपके रिमोट के कोड अलग हैं, तो Serial Monitor में दिख रहे कोड को प्रोग्राम में बदल दें।

Troubleshooting

ProblemFix
Motor vibrates but does not turnPin order is wrong. Use Stepper(2048, 8, 10, 9, 11) exactly, and keep IN1→D8 … IN4→D11.
Motor does not move at all, LEDs on ULN2003 darkCheck the power jumper on the ULN2003 board and the 5V/GND wires.
Nothing happens when keys are pressedCheck that the D13 LED blinks when you press a key. If not, re-check IR receiver pin order and that OUT is on D2.
Wrong key does the wrong thingYour remote uses different codes. Read them in Serial Monitor and edit the KEY_ constants.
Motor skips steps or stalls at high speed28BYJ-48 is slow by design. Keep speed at 15 RPM or less and use an external 5 V supply for loads.
Arduino resets when the motor startsUSB current is too low. Power the ULN2003 from a separate 5 V supply and connect grounds together.

Project Ideas

  • Remote-controlled curtain or blind opener.
  • Rotating display turntable for product photos.
  • Pan head for a small camera or phone.
  • Automatic fish feeder that turns a disc a fixed angle.

Frequently Asked Questions

Why 2048 steps and not 2038 or 4096?

In full-step mode the output shaft needs about 2048 steps (the exact gear ratio is 63.68:1, so some sources say 2038). In half-step mode, with other libraries such as AccelStepper, it is about 4096.

Can I use any TV remote?

Most remotes using the NEC protocol work directly. Other protocols (Sony, RC5, Samsung) are also decoded by IRremote, but the command codes will be different – read them from the Serial Monitor.

Can I drive a NEMA 17 stepper the same way?

No. NEMA 17 motors are bipolar and need a driver such as the A4988 or DRV8825 with a 12 V supply. The ULN2003 is only for small unipolar motors.

Does the Arduino remember the position after power-off?

No. The position is counted in RAM. For a real application, add a limit switch to find home at start-up.

Why does the motor get warm?

The coils draw current whenever they are energised. The code releases the coils after every move to keep it cool.

Related Projects

Browse more Robotics on Arduino Project Hub.