ESP32-CAM Pan-Tilt Object Tracking Camera
This project mounts an ESP32-CAM on a two-axis bracket and moves the camera toward a detected person. A computer performs object detection using YOLO, estimates the centre of the detected bounding box, and sends small pan/tilt corrections to a separate microcontroller that drives the servos.
Separating camera capture, vision processing, and motor power makes the build easier to debug. The camera board is responsible for images; the computer decides which way the target is from the frame centre; and an Arduino-compatible controller produces servo pulses. Driving two servos directly from the camera board can introduce supply dips and uses pins that may conflict with the camera or SD-card interface, so a second controller is recommended.
The tracker is a learning prototype, not a person-identification system. It follows the centre of a detected object class; it does not identify a particular individual or decide whether a person is authorised to enter a space. A face leaving the frame, occlusion, or two people crossing can cause the tracker to switch targets.
Components
6 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
🚨 Danger
Do not power servos from the ESP32-CAM 3.3 V pin or from a weak USB-to-serial adapter. Use a separate supply sized for servo stall current and connect the controller ground to the servo-supply ground. Set conservative mechanical limits before attaching the camera, and keep fingers and cables clear of the bracket.
1. Mechanical and electrical setup
Fix the pan-tilt bracket to a stable base. Mount the camera so that its cable and antenna-free board can move without snagging the servo horns. Before loading the camera, centre both servo horns and verify the travel range by commanding small movements.
Connect the servo controller as follows:
| Part | Connection |
|---|---|
| Pan servo signal | Arduino D9 |
| Tilt servo signal | Arduino D10 |
| Both servo positive leads | External supply positive matching the servo rating |
| Both servo ground leads | External supply ground |
| Arduino GND | External supply ground |
| Arduino USB | Computer for serial commands |
Use the servos' voltage rating, not a guessed universal value. The Arduino pins provide control signals only; they must not supply motor current. Keep the ESP32-CAM powered by its own stable 5 V source and confirm the camera still streams while the bracket moves.
2. Servo controller firmware
Install the Servo library available with Arduino IDE. The sketch below accepts serial commands in the form P90,T90. The parser clamps motion to safe example limits of 25–155 degrees; narrow those limits further if the bracket binds before reaching them. Open Serial Monitor at 115200 baud to test the commands manually before connecting the vision script.
#include <Servo.h>
Servo panServo;
Servo tiltServo;
int panAngle = 90;
int tiltAngle = 90;
String commandLine;
constexpr int PAN_PIN = 9;
constexpr int TILT_PIN = 10;
constexpr int MIN_ANGLE = 25;
constexpr int MAX_ANGLE = 155;
void applyAngles(int pan, int tilt) {
panAngle = constrain(pan, MIN_ANGLE, MAX_ANGLE);
tiltAngle = constrain(tilt, MIN_ANGLE, MAX_ANGLE);
panServo.write(panAngle);
tiltServo.write(tiltAngle);
Serial.print("OK P");
Serial.print(panAngle);
Serial.print(",T");
Serial.println(tiltAngle);
}
void setup() {
Serial.begin(115200);
panServo.attach(PAN_PIN);
tiltServo.attach(TILT_PIN);
applyAngles(90, 90);
}
void loop() {
while (Serial.available()) {
const char ch = static_cast<char>(Serial.read());
if (ch == '\n' || ch == '\r') {
if (commandLine.length() > 0) {
int pan = panAngle;
int tilt = tiltAngle;
int parsed = sscanf(commandLine.c_str(), "P%d,T%d", &pan, &tilt);
if (parsed == 2) applyAngles(pan, tilt);
else Serial.println("ERR expected P<number>,T<number>");
commandLine = "";
}
} else if (commandLine.length() < 40) {
commandLine += ch;
} else {
commandLine = "";
Serial.println("ERR command too long");
}
}
}import time
import cv2
import numpy as np
import requests
import serial
from ultralytics import YOLO
CAMERA_IP = "192.168.1.50"
SERIAL_PORT = "COM5" # Windows example; use /dev/ttyACM0 on Linux
BAUD = 115200
CONFIDENCE = 0.55
STEP = 2
DEAD_BAND = 0.08
camera = "http://" + CAMERA_IP + "/capture"
controller = serial.Serial(SERIAL_PORT, BAUD, timeout=1)
time.sleep(2) # Many Arduino boards reset when serial opens
model = YOLO("yolo26n.pt")
pan, tilt = 90, 90
def snapshot():
response = requests.get(camera, timeout=5)
response.raise_for_status()
frame = cv2.imdecode(np.frombuffer(response.content, np.uint8), cv2.IMREAD_COLOR)
if frame is None:
raise ValueError("Invalid camera JPEG")
return frame
while True:
frame = snapshot()
height, width = frame.shape[:2]
result = model.predict(frame, conf=CONFIDENCE, verbose=False)[0]
people = []
for box in result.boxes:
class_id = int(box.cls.item())
if model.names.get(class_id) != "person":
continue
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().tolist()
people.append(((x1 + x2) / 2, (y1 + y2) / 2, float(box.conf.item())))
if people:
# Track the most confident person in this simple single-target demo.
cx, cy, score = max(people, key=lambda item: item[2])
error_x = (cx - width / 2) / width
error_y = (cy - height / 2) / height
if abs(error_x) > DEAD_BAND:
pan += -STEP if error_x > 0 else STEP
if abs(error_y) > DEAD_BAND:
tilt += STEP if error_y > 0 else -STEP
pan = max(25, min(155, pan))
tilt = max(25, min(155, tilt))
controller.write("P{},T{}\n".format(pan, tilt).encode("ascii"))
print("target confidence={:.2f}, servo=({}, {})".format(score, pan, tilt))
time.sleep(0.4)3. Calibrate direction and movement speed
The example uses a simple proportional-style correction: when the target is clearly to one side of the frame, the command moves the camera a few degrees toward it. The sign may be reversed depending on how the bracket is mounted. Test with small STEP values and a target at the centre, left, right, top, and bottom. If the camera moves away from the target, reverse the relevant direction.
A larger step recentres the target faster but creates overshoot and oscillation. A small dead band stops the servo moving constantly for tiny detection errors. Try increasing the dead band if the camera jitters. The current code selects the most confident person in each image; it does not maintain identity across frames. For multiple people, add a tracker and an explicit rule such as keeping the target nearest the previous bounding-box centre.
4. Camera and servo constraints
Two hobby servos can draw several hundred milliamps or more while moving, especially at startup or near a mechanical stop. A supply that looks sufficient at idle may sag when both axes move together. Keep the camera's power leads separate from motor-current paths and use a common signal ground. Add mechanical stops or clamp values in firmware so the bracket cannot wind up its cables.
Troubleshooting
| Symptom | Check |
|---|---|
| Servos twitch or reset the camera | Separate servo supply, common ground, short signal wiring, and servo stall-current rating |
| Camera moves in the wrong direction | Reverse the correction sign for pan or tilt |
| Target oscillates around frame centre | Reduce STEP, increase DEAD_BAND, and lower the loop rate |
| Serial commands do nothing | Check the port, baud rate, newline termination, and whether another program has opened the port |
| Tracker jumps between people | Restrict the scene to one target or add a multi-object tracker and target-lock rule |
Practical limits
This tracker is only as good as its detections and the camera view. A low frame rate from JPEG snapshots means the motion will be visibly slower than a high-frame-rate robotic gimbal. Keep it for educational demos and non-critical camera positioning. Do not use it to aim lights or actuators at people, and do not present detection as identification.
References: Espressif CameraWebServer and Ultralytics prediction documentation.
Steps
- 1Run CameraWebServer and verify clear snapshots before installing the bracket.
- 2Centre both servo horns, connect the servos to an external supply, and test the Arduino serial parser with small movements.
- 3Set camera IP and the correct serial port in Python, then run inference with only one person in view.
- 4Calibrate pan and tilt direction and reduce the motion step until the target recentres without large oscillations.
- 5Recheck cable clearance, supply stability, and mechanical limits before leaving the tracker running.
5. Make the tracking loop stable
The code is a useful starting point, but real brackets behave differently. Servo deadband, backlash, speed, mounting direction, and camera delay all influence whether a target settles near the centre. Before running AI, send a series of small known angles over serial and note the camera's actual movement. Check that pan changes horizontal framing and tilt changes vertical framing. If a servo buzzes against a mechanical stop, immediately reduce the allowed angle range instead of trying to correct the issue in software with larger steps.
The snapshot-based detector is slower than running detection on a true continuous high-frame-rate stream. The camera can take a new image while the computer is still processing the previous one, and the target might have moved by the time the correction reaches the controller. Keep the control loop slow and conservative. Avoid stacking multiple outstanding commands; send a new position only after the last command has been accepted or after a bounded period. For a more polished design, timestamp detections and ignore frames older than a chosen maximum age.
The simple example follows the most confident person in each frame. That choice can jump between subjects when two people are visible. For a controlled demo, mark a small region of interest and follow only the detection whose centre is closest to the previously selected target. For crowded or occluded scenes, use a tracking algorithm with persistent IDs and an explicit target-lock policy; confidence alone is not identity.
Add a safe fallback when the camera or model is unavailable. The bracket can hold the last safe position or return to centre after a timeout, but it should not move unpredictably in response to a corrupted frame. Clamp servo commands on both the computer and the microcontroller. The microcontroller should reject malformed commands and keep outputs at the last valid angles if a serial line is incomplete.
Use a checklist for final tests: all four frame corners, a centre target, target movement in both directions, temporary occlusion, camera disconnect, USB serial disconnect, and a stalled servo. Record whether the tracker follows smoothly and whether the power remains stable during simultaneous axis motion. Keep the motion limits conservative and do not direct the camera or any attached actuator toward people in a way that could cause harm.
Prevent oscillation and enforce mechanical limits
A tracker can oscillate when it responds to every small detection movement. Begin with small steps, a deadband around the frame centre and a capped command frequency. Wait for the bracket to move before issuing the next adjustment. Real frame-processing delay, servo backlash and mechanical friction mean that the target may not appear centred immediately even when the command direction is correct.
The largest-box selection is only a baseline. If several objects are in view, the selected target can switch unexpectedly from one person to another. A more robust version retains a track ID and follows that target until it is lost, then uses a deliberate reacquisition rule. An ID is only a temporary tracker label, not a person's identity. On frame loss or control-endpoint failure, stop sending movement commands and show a fault.
Calibrate minimum, centre and maximum angle with the mechanism unloaded. Stop before the bracket binds, the ribbon cable pulls tight or a servo reaches a mechanical stop. Store those ranges in configuration and enforce them on the device, not only in the PC script. Use a separate regulated servo supply sized for stall-current peaks and connect grounds between the controller and driver. Test repeated movement under load while watching for voltage dips. Keep fingers and fragile objects clear, and ensure the camera cannot follow people into spaces they did not agree to have monitored.
6. Commissioning matrix: validate the complete control chain
Commission the mechanism in stages rather than starting object detection with the camera already mounted. Keep hands clear of the bracket and remove the camera payload while finding safe travel limits.
| Stage | Test | Pass condition |
|---|---|---|
| Servo controller | Send P90,T90, then small changes on one axis at a time | Both axes move in the expected direction and the controller reports clamped angles |
| Mechanical range | Increase pan and tilt limits gradually with the bracket unloaded | No binding, cable tension, sustained buzzing, or contact with the frame |
| Power integrity | Move both servos repeatedly while the camera streams | No camera resets, brownout symptoms, or unexplained loss of serial control |
| Image pipeline | Request several snapshots and decode them on the computer | Frames decode successfully and width/height are non-zero |
| Detection | Test a person near the centre and each edge of the frame | Person detections are visible and the configured confidence threshold behaves as expected |
| Direction | Move the target left, right, up, and down separately | Each correction moves the target toward the centre; reverse the corresponding sign if not |
| Fault handling | Disconnect the camera or serial controller during a controlled test | The operator sees a clear fault; the mechanism does not receive unbounded or malformed commands |
Tune from measurements, not guesswork
Record the target centre, frame dimensions, detection confidence, commanded angles, and time between capture and movement. Start with a small STEP and a generous dead band. If the target repeatedly crosses the centre, reduce the step size or slow the update rate. If the bracket responds in the right direction but lags behind, first measure capture and inference latency before increasing movement. Larger commands can make oscillation worse.
The computer-side angle clamp is not a substitute for the controller-side clamp: keep the firmware limits enabled and adjust them to the actual bracket. The sample firmware prints the accepted angles, but it does not provide a full acknowledgement protocol for each computer command. For a longer-running installation, add sequence numbers or explicit acknowledgements, ignore stale detections, and stop issuing updates when the camera or serial link is unhealthy.
This design follows a detected person class, not a specific person. It may lose the target during occlusion, switch to another person, or fail in poor lighting. Use visible status indicators for camera offline, detector unavailable, target lost, and manual/maintenance mode. Keep camera access restricted and tell people when the area is being monitored. This is an educational pan-tilt experiment, not a safety-rated tracking or surveillance system.
6. Commission the tracker in stages
Do not start with the camera, AI model, and moving bracket all enabled at once. Validate each layer independently so a wiring fault is not mistaken for a detection problem.
- Mechanical centre: disconnect the camera load if needed, command both axes to their centre positions, and fit the servo horns so the bracket is physically close to level. Move each axis a few degrees at a time and note the real minimum and maximum angles before setting firmware limits.
- Power under motion: measure the servo supply while both axes start and reverse direction. Check for resets, audible strain, hot connectors, or voltage dips. Choose the supply using the servos' rated voltage and stall-current specifications, not just their no-load current.
- Serial contract: send valid commands such as
P90,T90and a malformed line. Confirm the controller reports accepted angles for valid input and leaves the last safe position unchanged for invalid input. Keep the serial monitor closed when the Python process owns the port. - Camera and inference: verify the snapshot endpoint returns a valid JPEG, then run person detection with the bracket stationary. Confirm that a person is actually detected, the bounding-box centre is sensible, and confidence filtering rejects weak detections.
- Direction and dead band: place a target left, right, above, below, and at the centre. Start with a small movement step. If an axis moves away from the target, reverse that axis' correction sign; increase the dead band if small detection noise causes constant motion.
- Fault cases: cover the camera briefly, disconnect the serial controller, move a target out of view, and test two people crossing. The tracker should not issue uncontrolled movements or treat a lost target as a valid detection. Reconnect deliberately and confirm recovery.
What counts as a successful test
A successful demonstration means the target is detected, the camera moves in the expected direction, the bracket stays within calibrated limits, and the power remains stable during repeated movement. It does not prove reliable tracking in crowded, dark, or heavily occluded scenes. Record the camera resolution, model name, confidence threshold, dead band, step size, servo limits, and supply rating with the build so the result can be reproduced.
The sample selects the highest-confidence person independently in each frame, so it can switch targets. For a single-target demo, keep only one person in view. If persistent target selection matters, implement object tracking and an explicit reacquisition policy; do not describe a tracker ID as a real-world identity.



