Community project

AI Facial Recognition Gimbal Robot

Photo of AI Facial Recognition Gimbal Robot
Generated with AI

Khaled Mahmud (Rαfsนή)

Last updated October 17, 2026

This four-wheel mobile robot combines a pan-and-tilt gimbal head with distance sensing and cliff detection to create an autonomous platform. Built around the ESP32S3 Sense microcontroller, it uses dual motor drivers to control TT motors on each wheel, a PCA9685 servo driver for smooth gimbal movement, and a VL53L0X sensor for obstacle avoidance.

The guide provides a complete wiring diagram, detailed parts list, and step-by-step assembly instructions covering chassis setup, power distribution across two buck converters, motor driver configuration, and sensor integration. Included firmware demonstrates motor control, servo positioning, and sensor reading, giving builders a functional foundation to expand with their own autonomous behaviors.

Wiring diagram

Wiring diagram for AI Facial Recognition Gimbal Robot
Loading diagram…

Gather all the parts

QtyComponent
1

PCA9685 16-channel servo driver breakout

A 3.3 V logic servo controller that gives the Tab5 sixteen stable servo-control outputs.

1

MG90D High-Torque Metal Gear Micro Servo

MG90D pan servo

13g digital micro servo with metal gears, an aluminum output shaft, and double ball bearings, giving noticeably more torque and speed than a standard MG90S or SG90. Wired and controlled exactly like any hobby servo: 3-wire PWM at 4.8-6.6V, drop-in compatible with the Arduino Servo library.

1

MG90D High-Torque Metal Gear Micro Servo

MG90D tilt servo

13g digital micro servo with metal gears, an aluminum output shaft, and double ball bearings, giving noticeably more torque and speed than a standard MG90S or SG90. Wired and controlled exactly like any hobby servo: 3-wire PWM at 4.8-6.6V, drop-in compatible with the Arduino Servo library.

1

5 V 5 A DC-DC buck converter

5.0 V; 5 A continuous minimum

The battery-fed converter that supplies the servos, XIAO, and audio amplifier without needing a wall USB supply.

1

Two-axis micro-servo pan-and-tilt bracket

A mechanical bracket that holds the Tab5 and lets the two servos aim it left-right and up-down.

1

2S 7.4 V 3000 mAh 25C LiPo battery pack

7.4 V nominal, 3000 mAh, 25C minimum

The rechargeable battery pack that powers Mochi away from a wall socket.

1

6 V 5 A DC-DC buck converter

Adjust to 6.0 V; 5 A continuous minimum

The adjustable converter that supplies a steady 6 V to the four wheel motor drivers.

1

TCRT5000 IR Line Tracking Sensor Module

Single-channel infrared reflective sensor module built around the Vishay TCRT5000 IR emitter/phototransistor pair. An onboard LM393 comparator with a sensitivity trim-pot drives a thresholded digital output (DO) for line-detection or obstacle-avoidance, while a separate analog pin (AO) exposes the raw reflected-IR reading. Runs on 3.3V-5V, senses reflective surfaces roughly 1-25mm away, and is the standard low-cost sensor on line-following and obstacle-avoiding robot kits. Sold as a generic 4-pin (VCC/GND/DO/AO) breakout under many brand names (HiLetgo, ACEIRMC, OSOYOO, etc.) rather than by a single official manufacturer.

1

TCRT5000 IR Line Tracking Sensor Module

Single-channel infrared reflective sensor module built around the Vishay TCRT5000 IR emitter/phototransistor pair. An onboard LM393 comparator with a sensitivity trim-pot drives a thresholded digital output (DO) for line-detection or obstacle-avoidance, while a separate analog pin (AO) exposes the raw reflected-IR reading. Runs on 3.3V-5V, senses reflective surfaces roughly 1-25mm away, and is the standard low-cost sensor on line-following and obstacle-avoiding robot kits. Sold as a generic 4-pin (VCC/GND/DO/AO) breakout under many brand names (HiLetgo, ACEIRMC, OSOYOO, etc.) rather than by a single official manufacturer.

1

TCRT5000 IR Line Tracking Sensor Module

Single-channel infrared reflective sensor module built around the Vishay TCRT5000 IR emitter/phototransistor pair. An onboard LM393 comparator with a sensitivity trim-pot drives a thresholded digital output (DO) for line-detection or obstacle-avoidance, while a separate analog pin (AO) exposes the raw reflected-IR reading. Runs on 3.3V-5V, senses reflective surfaces roughly 1-25mm away, and is the standard low-cost sensor on line-following and obstacle-avoiding robot kits. Sold as a generic 4-pin (VCC/GND/DO/AO) breakout under many brand names (HiLetgo, ACEIRMC, OSOYOO, etc.) rather than by a single official manufacturer.

1

VL53L0X Time-of-Flight Distance Sensor

ST VL53L0X single-zone time-of-flight ranging sensor. Communicates over I2C; XSHUT and GPIO1/data-ready pins are optional on common breakouts.

1

Seeed Studio XIAO ESP32S3 Sense

A compact Wi-Fi camera and microphone board that detects people and handles voice/AI requests before sending safe commands to the rover.

1

TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio

6 V left-front wheel motor

TT-format bi-metal DC gearbox motor with a 1:90 reduction ratio - roughly double the torque and half the speed of the more common 1:48 TT motor. Runs on 3-6VDC (60-120 RPM no-load depending on voltage), has steel output gears for durability, and is one of several TT-motor gearbox ratios (1:48, 1:90, 1:120) used across 2WD/4WD robot car and crawler chassis kits, this one favoring torque/climbing over speed. Ships with no wires attached and cannot be driven directly from a microcontroller pin; requires a separate high-current motor driver such as a DRV8833 or TB6612FNG.

1

TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio

6 V left-rear wheel motor

TT-format bi-metal DC gearbox motor with a 1:90 reduction ratio - roughly double the torque and half the speed of the more common 1:48 TT motor. Runs on 3-6VDC (60-120 RPM no-load depending on voltage), has steel output gears for durability, and is one of several TT-motor gearbox ratios (1:48, 1:90, 1:120) used across 2WD/4WD robot car and crawler chassis kits, this one favoring torque/climbing over speed. Ships with no wires attached and cannot be driven directly from a microcontroller pin; requires a separate high-current motor driver such as a DRV8833 or TB6612FNG.

1

TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio

6 V right-front wheel motor

TT-format bi-metal DC gearbox motor with a 1:90 reduction ratio - roughly double the torque and half the speed of the more common 1:48 TT motor. Runs on 3-6VDC (60-120 RPM no-load depending on voltage), has steel output gears for durability, and is one of several TT-motor gearbox ratios (1:48, 1:90, 1:120) used across 2WD/4WD robot car and crawler chassis kits, this one favoring torque/climbing over speed. Ships with no wires attached and cannot be driven directly from a microcontroller pin; requires a separate high-current motor driver such as a DRV8833 or TB6612FNG.

1

TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio

6 V right-rear wheel motor

TT-format bi-metal DC gearbox motor with a 1:90 reduction ratio - roughly double the torque and half the speed of the more common 1:48 TT motor. Runs on 3-6VDC (60-120 RPM no-load depending on voltage), has steel output gears for durability, and is one of several TT-motor gearbox ratios (1:48, 1:90, 1:120) used across 2WD/4WD robot car and crawler chassis kits, this one favoring torque/climbing over speed. Ships with no wires attached and cannot be driven directly from a microcontroller pin; requires a separate high-current motor driver such as a DRV8833 or TB6612FNG.

1

Four-wheel TT-motor robot chassis

A four-wheel chassis plate made for four TT gear motors, carrying the battery, electronics, and Tab5 head.

1

TB6612FNG dual H-bridge breakout, left side

A 3.3 V-logic dual motor-driver board that independently powers the front and rear left TT wheel motors from a 6 V motor rail.

1

TB6612FNG dual H-bridge breakout, right side

A 3.3 V-logic dual motor-driver board that independently powers the front and rear right TT wheel motors from a 6 V motor rail.

1

MAX98357A I2S Class-D Mono Amplifier Breakout

I2S-input Class-D mono audio amplifier IC on a compact breakout board. Accepts I2S digital audio input (BCLK, LRC, DIN) and drives a small speaker or transducer directly. No I2C/SPI control bus is needed. The amplifier supply range is 2.5V-5.5V, and the I2S input pins are compatible with 3.3V logic. SD/MODE controls shutdown and channel selection; GAIN selects 3 dB, 6 dB, 9 dB, 12 dB, or 15 dB gain.

1

8Ω Speaker

8 Ω, 1 W or greater

Generic small 8Ω 0.5-3W loudspeaker (~28mm typical). Pair with an I2S amp (MAX98357A) or class-D amp (TPA3116D2) for usable volume; do not drive directly from a GPIO pin. Audio output for music/voice playback.

1

BSS138 4-channel 5 V to 3.3 V logic-level shifter

A small board that reduces the three cliff-sensor signal voltages so they cannot damage the Tab5.

1

Inline automotive blade-fuse holder

For standard automotive blade fuse

The holder placed close to the battery so a short circuit disconnects battery power safely.

1

5 A automotive blade fuse

5 A

The replaceable fuse that opens if the rover draws unsafe current from its battery.

1

DC-rated main power switch

Rated at least 12 V DC, 10 A

The manual switch that turns the robot's battery power on and off.

1

Latching mushroom emergency-stop switch, normally closed

Normally closed; DC-rated at least 12 V, 10 A

The large push-button that immediately removes power from the motors, servos, and external electronics when pressed.

1

Two-branch fused power distribution block

10 A DC minimum

The terminal block that splits protected battery power and ground into separate motor and logic converter branches.

1

2S LiPo low-voltage alarm

2S; set alarm no lower than 3.5 V per cell

The small alarm that plugs into the battery balance lead and beeps before the LiPo is discharged too far.

1

1000 µF 16 V electrolytic capacitor

1000 µF, 16 V or higher

The polarized capacitor that smooths motor-current spikes near the motor driver power inputs.

1

0.1 µF ceramic motor-noise capacitor

0.1 µF ceramic, 50 V

The small non-polarized capacitor soldered across the left-front motor terminals to reduce electrical noise.

1

0.1 µF ceramic motor-noise capacitor

0.1 µF ceramic, 50 V

The small non-polarized capacitor soldered across the left-rear motor terminals to reduce electrical noise.

1

0.1 µF ceramic motor-noise capacitor

0.1 µF ceramic, 50 V

The small non-polarized capacitor soldered across the right-front motor terminals to reduce electrical noise.

1

0.1 µF ceramic motor-noise capacitor

0.1 µF ceramic, 50 V

The small non-polarized capacitor soldered across the right-rear motor terminals to reduce electrical noise.

Assemble it in 11 steps

1. Mount the chassis and motors

Bolt the four motors to rover_base, fit the wheels, and strap drive_battery low in the centre. Keep every wire away from the wheels and motor shafts.

  • Do not pierce, crush, or screw through the LiPo battery — a damaged battery can catch fire.

2. Solder motor noise capacitors

Solder left_front_noise_cap, left_rear_noise_cap, right_front_noise_cap, and right_rear_noise_cap directly across the two tabs of their matching motor. These tiny capacitors have no plus or minus direction.

  • Keep each capacitor's leads short so it can reduce motor electrical noise effectively.

3. Mount the head and sensors

Fit pan_servo and tilt_servo into pan_tilt_bracket, secure the Tab5 to the moving plate, and mount ai_sense facing forward with its camera and microphone clear. Mount the three cliff sensors 5–15 mm above the floor and front_range facing straight ahead.

  • Leave the servo horns off until the powered servos have centred — fitting a horn at the wrong angle can break the servo gears.

4. Install the protected battery path

With the battery disconnected, wire drive_battery BAT+ to main_fuse_holder IN (battery power), then main_fuse_holder OUT to main_power_switch IN (protected power), main_power_switch OUT to emergency_stop IN (switched power), and emergency_stop OUT to power_distribution POS_IN (emergency-cut power). Wire drive_battery BAT- to power_distribution GND_IN (ground). Insert main_fuse into main_fuse_holder.

  • Mount emergency_stop where you can hit it immediately. Pressing it must remove battery power before any wheel test.
  • Keep the fuse holder within 15 cm of the battery positive lead so an accidental short has as little unfused wire as possible.

5. Wire the two battery converters

Connect power_distribution MOTOR_POS to drive_buck VIN+ and MOTOR_GND to drive_buck VIN- (motor converter input). Connect LOGIC_POS to servo_supply VIN+ and LOGIC_GND to servo_supply VIN- (5 V converter input). Set drive_buck to exactly 6.0 V and servo_supply to exactly 5.0 V with a multimeter before connecting the rover electronics.

  • A fully charged 2S LiPo is about 8.4 V. Never connect it directly to the 6 V motors, drivers, servos, or XIAO.

6. Add the motor rail capacitor

Place motor_bulk_capacitor close to the TB6612 boards. Connect its long positive lead to drive_buck VOUT+ (6 V motor power) and its striped negative lead to the shared ground (ground).

  • Reversing this capacitor can make it burst when power is applied.

7. Wire both motor drivers

Connect drive_buck VOUT+ to both TB6612 VM pins (6 V motor power) and drive_buck VOUT- to shared GND (ground). For left_driver wire AIN1 → GPIO3, AIN2 → GPIO4, PWMA → GPIO2, BIN1 → GPIO16, BIN2 → GPIO17, PWMB → GPIO18, and STBY → GPIO45 (motor control); connect its A01/A02 to left_front_motor and B01/B02 to left_rear_motor. For right_driver wire AIN1 → GPIO48, AIN2 → GPIO47, PWMA → GPIO35, BIN1 → GPIO52, BIN2 → GPIO5, PWMB → GPIO19, and STBY → GPIO50 (motor control); connect its A01/A02 to right_front_motor and B01/B02 to right_rear_motor.

  • If a wheel spins backward, press emergency_stop or disconnect the battery, then swap only that motor's two wires.

8. Wire the 5 V equipment and safety sensors

Connect servo_supply VOUT+ to servo_driver V+, pan_servo VCC, tilt_servo VCC, ai_sense 5V, each cliff-sensor VCC, and cliff_level_shifter HV (5 V power). Join servo_supply VOUT- to the shared ground (ground). Wire cliff DO outputs to the shifter HV1/HV2/HV3, then LV1 → GPIO0, LV2 → GPIO1, and LV3 → GPIO49 (safe edge signals). Connect shifter LV to Tab5 3V3 and shifter GND to GND.

  • Do not bypass cliff_level_shifter — a 5 V sensor signal can permanently damage the Tab5.

9. Wire the head, range sensor, and audio

Connect servo_driver VCC to Tab5 3V3 (logic power), GND to GND (ground), SDA to GPIO53 (data), and SCL to GPIO54 (clock); plug pan_servo into channel 0 and tilt_servo into channel 1. Connect front_range VIN to 3V3, GND to GND, SDA to GPIO53, and SCL to GPIO54. Connect ai_sense TX → GPIO38 and RX → GPIO37 (data). Connect voice_amp VIN to 3V3, GND to GND, BCLK → GPIO6, LRC → GPIO7, DIN → GPIO51; then voice_amp SPK+ → voice_speaker POS and SPK- → voice_speaker NEG.

  • Do not connect either speaker terminal to ground — that can damage the amplifier.

10. Connect the battery alarm

Plug lipo_alarm into the drive_battery balance connector, matching the three balance wires in order. Set it to warn at no lower than 3.5 V per cell.

  • Use the balance connector only for the alarm and a proper 2S balance charger; never use it to power the robot.

11. Perform the first safe power test

Raise all wheels off the floor. With emergency_stop pressed, turn on main_power_switch and check both converter outputs again. Release emergency_stop only after the display boots. Press emergency_stop and confirm the external electronics and wheel power immediately turn off. Then press Deploy, centre the servos, fit the servo horns, and test sensors and wheel direction before a slow supervised floor test.

  • The TT motors have no encoder feedback, so Mochi cannot correct wheel slip. Keep all early floor tests slow and far from stairs, people, and loose cables.

Review all connections

1. Connections between "servo_driver" and "ESP32"

Functionservo_driverESP32
powerVCC3V3
groundGNDGND
i2cSDAGPIO 53
i2cSCLGPIO 54

2. Connections between "pan_servo" and "ESP32"

Functionpan_servoESP32
groundGNDGND
pwmSIGNAL → PCA9685 16-channel servo driver breakout PWM0-PWM15EXT
powerVCC → 5 V 5 A DC-DC buck converter VOUT+EXT

3. Connections between "tilt_servo" and "ESP32"

Functiontilt_servoESP32
groundGNDGND
pwmSIGNAL → PCA9685 16-channel servo driver breakout PWM0-PWM15EXT
powerVCC → 5 V 5 A DC-DC buck converter VOUT+EXT

4. Connections between "drive_buck" and "ESP32"

Functiondrive_buckESP32
powerVOUT+VIN
groundVOUT-GND

5. Connections between "left_front_motor" and "ESP32"

Functionleft_front_motorESP32
powerM1 → TB6612FNG dual H-bridge breakout, left side A01EXT
powerM2 → TB6612FNG dual H-bridge breakout, left side A02EXT

6. Connections between "left_rear_motor" and "ESP32"

Functionleft_rear_motorESP32
powerM1 → TB6612FNG dual H-bridge breakout, left side B01EXT
powerM2 → TB6612FNG dual H-bridge breakout, left side B02EXT

7. Connections between "right_front_motor" and "ESP32"

Functionright_front_motorESP32
powerM1 → TB6612FNG dual H-bridge breakout, right side A01EXT
powerM2 → TB6612FNG dual H-bridge breakout, right side A02EXT

8. Connections between "right_rear_motor" and "ESP32"

Functionright_rear_motorESP32
powerM1 → TB6612FNG dual H-bridge breakout, right side B01EXT
powerM2 → TB6612FNG dual H-bridge breakout, right side B02EXT

9. Connections between "cliff_left" and "ESP32"

Functioncliff_leftESP32
groundGNDGND
digitalDO → BSS138 4-channel 5 V to 3.3 V logic-level shifter HV1EXT
powerVCC → 5 V 5 A DC-DC buck converter VOUT+EXT

10. Connections between "cliff_center" and "ESP32"

Functioncliff_centerESP32
groundGNDGND
digitalDO → BSS138 4-channel 5 V to 3.3 V logic-level shifter HV2EXT
powerVCC → 5 V 5 A DC-DC buck converter VOUT+EXT

11. Connections between "cliff_right" and "ESP32"

Functioncliff_rightESP32
groundGNDGND
digitalDO → BSS138 4-channel 5 V to 3.3 V logic-level shifter HV3EXT
powerVCC → 5 V 5 A DC-DC buck converter VOUT+EXT

12. Connections between "front_range" and "ESP32"

Functionfront_rangeESP32
powerVIN3V3
groundGNDGND
i2cSDAGPIO 53
i2cSCLGPIO 54

13. Connections between "ai_sense" and "ESP32"

Functionai_senseESP32
groundGNDGND
uartTXGPIO 38
uartRXGPIO 37
power5V → 5 V 5 A DC-DC buck converter VOUT+EXT

14. Connections between "left_driver" and "ESP32"

Functionleft_driverESP32
powerVMVIN
powerVCC3V3
groundGNDGND
digitalAIN1GPIO 3
digitalAIN2GPIO 4
pwmPWMAGPIO 2
digitalBIN1GPIO 16
digitalBIN2GPIO 17
pwmPWMBGPIO 18
digitalSTBYGPIO 45

15. Connections between "right_driver" and "ESP32"

Functionright_driverESP32
powerVMVIN
powerVCC3V3
groundGNDGND
digitalAIN1GPIO 48
digitalAIN2GPIO 47
pwmPWMAGPIO 35
digitalBIN1GPIO 52
digitalBIN2GPIO 5
pwmPWMBGPIO 19
digitalSTBYGPIO 50

16. Connections between "voice_amp" and "ESP32"

Functionvoice_ampESP32
powerVIN3V3
groundGNDGND
dataBCLKGPIO 6
dataLRCGPIO 7
dataDINGPIO 51
dataSPK+ → 8Ω Speaker POSEXT
dataSPK- → 8Ω Speaker NEGEXT

17. Connections between "cliff_level_shifter" and "ESP32"

Functioncliff_level_shifterESP32
powerLV3V3
groundGNDGND
digitalLV1GPIO 0
digitalLV2GPIO 1
digitalLV3GPIO 49
powerHV → 5 V 5 A DC-DC buck converter VOUT+EXT

18. Connections between "drive_battery" and "ESP32"

Functiondrive_batteryESP32
powerBAT+ → Inline automotive blade-fuse holder INEXT
groundBAT- → Two-branch fused power distribution block GND_INEXT

19. Connections between "main_fuse" and "ESP32"

Functionmain_fuseESP32
powerFUSE → Inline automotive blade-fuse holder INEXT

20. Connections between "main_fuse_holder" and "ESP32"

Functionmain_fuse_holderESP32
powerOUT → DC-rated main power switch INEXT

21. Connections between "main_power_switch" and "ESP32"

Functionmain_power_switchESP32
powerOUT → Latching mushroom emergency-stop switch, normally closed INEXT

22. Connections between "emergency_stop" and "ESP32"

Functionemergency_stopESP32
powerOUT → Two-branch fused power distribution block POS_INEXT

23. Connections between "power_distribution" and "ESP32"

Functionpower_distributionESP32
powerMOTOR_POS → 6 V 5 A DC-DC buck converter VIN+EXT
groundMOTOR_GND → 6 V 5 A DC-DC buck converter VIN-EXT
powerLOGIC_POS → 5 V 5 A DC-DC buck converter VIN+EXT
groundLOGIC_GND → 5 V 5 A DC-DC buck converter VIN-EXT

24. Connections between "servo_supply" and "ESP32"

Functionservo_supplyESP32
powerVOUT+ → PCA9685 16-channel servo driver breakout V+EXT
groundVOUT-GND

25. Connections between "motor_bulk_capacitor" and "ESP32"

Functionmotor_bulk_capacitorESP32
power+ → 6 V 5 A DC-DC buck converter VOUT+EXT
ground-GND

26. Connections between "left_front_noise_cap" and "ESP32"

Functionleft_front_noise_capESP32
powerA → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M1EXT
powerB → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M2EXT

27. Connections between "left_rear_noise_cap" and "ESP32"

Functionleft_rear_noise_capESP32
powerA → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M1EXT
powerB → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M2EXT

28. Connections between "right_front_noise_cap" and "ESP32"

Functionright_front_noise_capESP32
powerA → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M1EXT
powerB → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M2EXT

29. Connections between "right_rear_noise_cap" and "ESP32"

Functionright_rear_noise_capESP32
powerA → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M1EXT
powerB → TT Motor Bi-Metal Gearbox - 1:90 Gear Ratio M2EXT

30. Connections between "lipo_alarm" and "ESP32"

Functionlipo_alarmESP32
powerCELL1 → 2S 7.4 V 3000 mAh 25C LiPo battery pack BALANCEEXT
powerCELL2 → 2S 7.4 V 3000 mAh 25C LiPo battery pack BALANCEEXT
groundGND → 2S 7.4 V 3000 mAh 25C LiPo battery pack BALANCEEXT

Deploy the firmware

#include <M5Unified.h>
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <Adafruit_VL53L0X.h>

static constexpr int PCA_SDA_PIN = 53, PCA_SCL_PIN = 54;
static constexpr int LEFT_FRONT_IN1_PIN = 3, LEFT_FRONT_IN2_PIN = 4, LEFT_FRONT_PWM_PIN = 2;
static constexpr int LEFT_REAR_IN1_PIN = 16, LEFT_REAR_IN2_PIN = 17, LEFT_REAR_PWM_PIN = 18;
static constexpr int LEFT_STBY_PIN = 45;
static constexpr int RIGHT_FRONT_IN1_PIN = 48, RIGHT_FRONT_IN2_PIN = 47, RIGHT_FRONT_PWM_PIN = 35;
static constexpr int RIGHT_REAR_IN1_PIN = 52, RIGHT_REAR_IN2_PIN = 5, RIGHT_REAR_PWM_PIN = 19;
static constexpr int RIGHT_STBY_PIN = 50;
static constexpr int CLIFF_LEFT_PIN = 0, CLIFF_CENTER_PIN = 1, CLIFF_RIGHT_PIN = 49;
static constexpr int AI_UART_RX_PIN = 38, AI_UART_TX_PIN = 37;
// External MAX98357A voice amplifier. These pins are reserved for its I2S connection.
// Power is protected by the battery fuse and normally-closed hardware emergency stop; this code remains a secondary safety layer after the verified final power wiring check.
static constexpr int VOICE_I2S_BCLK_PIN = 6, VOICE_I2S_LRC_PIN = 7, VOICE_I2S_DIN_PIN = 51;
static constexpr uint8_t PCA_ADDRESS = 0x40, PAN_CHANNEL = 0, TILT_CHANNEL = 1;
static constexpr uint16_t SERVO_MIN_TICKS = 110, SERVO_MAX_TICKS = 510, STOP_DISTANCE_MM = 280;
static constexpr uint8_t DRIVE_PWM = 120, PWM_RESOLUTION = 8;
static constexpr uint32_t PWM_FREQUENCY = 20000, FACE_FRAME_MS = 50, TURN_TIME_MS = 700, BACK_UP_TIME_MS = 500;
static constexpr int CLIFF_TRIGGER_LEVEL = HIGH;

Adafruit_PWMServoDriver servoDriver(PCA_ADDRESS);
Adafruit_VL53L0X rangeSensor;
HardwareSerial aiUart(1);
enum Emotion { HAPPY, CURIOUS, LISTENING, REGISTERING, THINKING, ALERT, PATROLLING };
enum RobotMode { SAFE_STOP, PATROL, AVOID_BACKUP, AVOID_TURN, PERSON_WAIT, GREETING };
Emotion emotion = HAPPY;
RobotMode mode = SAFE_STOP;
String statusLine = "Starting local safe demo...";
uint32_t lastFace = 0, lastThink = 0, lastRange = 0, modeAt = 0, frame = 0;
uint16_t frontDistance = 8190;
bool rangeAvailable = false;

void setupMotorChannel(int in1, int in2, int pwm) { pinMode(in1, OUTPUT); pinMode(in2, OUTPUT); ledcAttach(pwm, PWM_FREQUENCY, PWM_RESOLUTION); digitalWrite(in1, LOW); digitalWrite(in2, LOW); ledcWrite(pwm, 0); }
void driveChannel(int in1, int in2, int pwm, int speed) { int duty = constrain(abs(speed), 0, 255); if (!duty) { digitalWrite(in1, LOW); digitalWrite(in2, LOW); ledcWrite(pwm, 0); return; } digitalWrite(in1, speed > 0 ? HIGH : LOW); digitalWrite(in2, speed > 0 ? LOW : HIGH); ledcWrite(pwm, duty); }
void driveSides(int leftSpeed, int rightSpeed) { driveChannel(LEFT_FRONT_IN1_PIN, LEFT_FRONT_IN2_PIN, LEFT_FRONT_PWM_PIN, leftSpeed); driveChannel(LEFT_REAR_IN1_PIN, LEFT_REAR_IN2_PIN, LEFT_REAR_PWM_PIN, leftSpeed); driveChannel(RIGHT_FRONT_IN1_PIN, RIGHT_FRONT_IN2_PIN, RIGHT_FRONT_PWM_PIN, rightSpeed); driveChannel(RIGHT_REAR_IN1_PIN, RIGHT_REAR_IN2_PIN, RIGHT_REAR_PWM_PIN, rightSpeed); }
void stopRover() { driveSides(0, 0); }
uint16_t servoTicks(int angle) { return map(constrain(angle, 0, 180), 0, 180, SERVO_MIN_TICKS, SERVO_MAX_TICKS); }
void gimbal(int pan, int tilt) { servoDriver.setPWM(PAN_CHANNEL, 0, servoTicks(constrain(pan, 25, 155))); servoDriver.setPWM(TILT_CHANNEL, 0, servoTicks(constrain(tilt, 40, 140))); }
// Short local cues use the Tab5's built-in speaker. No speech, recordings, or network data are used in safe-demo mode.
void cue(uint16_t frequency, uint16_t duration) { M5.Speaker.tone(frequency, duration); }
void drawStatic() { M5.Display.fillScreen(TFT_NAVY); M5.Display.setTextDatum(middle_center); M5.Display.setTextColor(TFT_WHITE, TFT_NAVY); M5.Display.setTextSize(2); M5.Display.drawString("Mochi - Local Safe Demo", M5.Display.width()/2, 52); }
void drawFace() { int w=M5.Display.width(), h=M5.Display.height(), eyeY=h/2-45, leftX=w/2-150, rightX=w/2+150; bool blink=(frame%100)<2; M5.Display.fillRect(leftX-80,eyeY-85,160,170,TFT_NAVY); M5.Display.fillRect(rightX-80,eyeY-85,160,170,TFT_NAVY); M5.Display.fillRect(w/2-380,h/2+35,760,190,TFT_NAVY); if(blink||emotion==LISTENING){M5.Display.drawLine(leftX-45,eyeY,leftX+45,eyeY,TFT_WHITE);M5.Display.drawLine(rightX-45,eyeY,rightX+45,eyeY,TFT_WHITE);}else{M5.Display.fillCircle(leftX,eyeY,48,TFT_WHITE);M5.Display.fillCircle(rightX,eyeY,48,TFT_WHITE);M5.Display.fillCircle(leftX,eyeY+8,18,TFT_NAVY);M5.Display.fillCircle(rightX,eyeY+8,18,TFT_NAVY);} M5.Display.setTextDatum(middle_center);M5.Display.setTextColor(TFT_WHITE,TFT_NAVY);M5.Display.setTextSize(2);M5.Display.drawString(statusLine,w/2,h-115);if(emotion==ALERT)M5.Display.drawCircle(w/2,h/2+80,30,TFT_RED);else if(emotion==HAPPY)M5.Display.drawArc(w/2,h/2+60,85,82,20,160,TFT_WHITE);else if(emotion==CURIOUS)M5.Display.drawCircle(w/2,h/2+80,30,TFT_WHITE);else M5.Display.drawLine(w/2-55,h/2+80,w/2+55,h/2+80,TFT_WHITE); }
bool cliffDetected(){return digitalRead(CLIFF_LEFT_PIN)==CLIFF_TRIGGER_LEVEL||digitalRead(CLIFF_CENTER_PIN)==CLIFF_TRIGGER_LEVEL||digitalRead(CLIFF_RIGHT_PIN)==CLIFF_TRIGGER_LEVEL;}
void updateRange(){if(!rangeAvailable||millis()-lastRange<80)return;lastRange=millis();VL53L0X_RangingMeasurementData_t measurement;rangeSensor.rangingTest(&measurement,false);frontDistance=measurement.RangeStatus==4?8190:measurement.RangeMilliMeter;}
void setMode(RobotMode newMode){mode=newMode;modeAt=millis();}
void beginAvoidance(){stopRover();emotion=ALERT;statusLine="Edge or obstacle - backing away";gimbal(90,105);cue(330,120);setMode(AVOID_BACKUP);}
void updateAutonomy(){updateRange();if(mode==SAFE_STOP||mode==PERSON_WAIT||mode==GREETING){stopRover();return;}if(cliffDetected()||(rangeAvailable&&frontDistance<STOP_DISTANCE_MM)){beginAvoidance();return;}if(mode==PATROL){emotion=PATROLLING;statusLine="Patrolling - local safe demo";driveSides(DRIVE_PWM,DRIVE_PWM);}else if(mode==AVOID_BACKUP){driveSides(-DRIVE_PWM,-DRIVE_PWM);if(millis()-modeAt>=BACK_UP_TIME_MS){statusLine="Turning away safely";setMode(AVOID_TURN);}}else if(mode==AVOID_TURN){driveSides(DRIVE_PWM,-DRIVE_PWM);if(millis()-modeAt>=TURN_TIME_MS){gimbal(90,85);setMode(PATROL);}}}
void handleGateway(String message){message.trim();if(message=="A"||message=="AUTONOMY ON"){emotion=PATROLLING;statusLine="Patrolling - local safe demo";gimbal(90,85);cue(660,70);setMode(PATROL);}else if(message=="X"||message=="AUTONOMY OFF"){emotion=ALERT;statusLine="Safety stop";cue(220,250);setMode(SAFE_STOP);}else if(message=="PERSON:VISIBLE"||message=="PERSON:UNKNOWN"){stopRover();statusLine="Hello! May I register your name and face template?";emotion=CURIOUS;gimbal(105,88);cue(880,100);aiUart.println("CONSENT:REQUESTED");setMode(PERSON_WAIT);}else if(message=="CONSENT:ACCEPTED"){statusLine="Consent received - no data saved in local demo";emotion=REGISTERING;cue(1040,100);setMode(PERSON_WAIT);}else if(message=="CONSENT:DECLINED"){statusLine="No problem - nothing was saved";emotion=HAPPY;cue(520,80);setMode(GREETING);}else if(message.startsWith("PERSON:KNOWN:")||message.startsWith("REGISTERED:")){statusLine="Identity service is offline - no record used";emotion=ALERT;cue(220,180);setMode(PERSON_WAIT);}else if(message=="REGISTERING"){statusLine="Registration needs the private gateway";emotion=REGISTERING;setMode(PERSON_WAIT);}else if(message=="LISTENING"){statusLine="Listening is unavailable in local demo";emotion=LISTENING;setMode(PERSON_WAIT);}else if(message=="THINKING"){statusLine="Gateway is unavailable - ask again later";emotion=THINKING;lastThink=0;setMode(PERSON_WAIT);}else if(message.startsWith("SAY:")){statusLine=message.substring(4);emotion=HAPPY;cue(780,80);setMode(PERSON_WAIT);}}
void readCommandStream(Stream &port,String &line){while(port.available()){char character=(char)port.read();if(character=='\n'||character=='\r'){if(line.length())handleGateway(line);line="";}else if(line.length()<240)line+=character;}}
void setup(){auto config=M5.config();M5.begin(config);Serial.begin(115200);aiUart.begin(115200,SERIAL_8N1,AI_UART_RX_PIN,AI_UART_TX_PIN);pinMode(VOICE_I2S_BCLK_PIN, OUTPUT);pinMode(VOICE_I2S_LRC_PIN, OUTPUT);pinMode(VOICE_I2S_DIN_PIN, OUTPUT);setupMotorChannel(LEFT_FRONT_IN1_PIN,LEFT_FRONT_IN2_PIN,LEFT_FRONT_PWM_PIN);setupMotorChannel(LEFT_REAR_IN1_PIN,LEFT_REAR_IN2_PIN,LEFT_REAR_PWM_PIN);setupMotorChannel(RIGHT_FRONT_IN1_PIN,RIGHT_FRONT_IN2_PIN,RIGHT_FRONT_PWM_PIN);setupMotorChannel(RIGHT_REAR_IN1_PIN,RIGHT_REAR_IN2_PIN,RIGHT_REAR_PWM_PIN);pinMode(LEFT_STBY_PIN,OUTPUT);pinMode(RIGHT_STBY_PIN,OUTPUT);digitalWrite(LEFT_STBY_PIN,HIGH);digitalWrite(RIGHT_STBY_PIN,HIGH);pinMode(CLIFF_LEFT_PIN,INPUT_PULLUP);pinMode(CLIFF_CENTER_PIN,INPUT_PULLUP);pinMode(CLIFF_RIGHT_PIN,INPUT_PULLUP);stopRover();Wire.begin(PCA_SDA_PIN,PCA_SCL_PIN);servoDriver.begin();servoDriver.setOscillatorFrequency(27000000);servoDriver.setPWMFreq(50);rangeAvailable=rangeSensor.begin(0x29,false,&Wire);gimbal(90,85);emotion=PATROLLING;statusLine=rangeAvailable?"Patrolling - local safe demo":"Patrolling - distance sensor unavailable";setMode(PATROL);drawStatic();drawFace();cue(660,80);Serial.println("Mochi local safe demo. Send X to stop; PERSON:VISIBLE to request consent.");aiUart.println("ROVER:READY:LOCAL_SAFE_DEMO");}
void loop(){M5.update();static String usbLine,aiLine;readCommandStream(Serial,usbLine);readCommandStream(aiUart,aiLine);updateAutonomy();uint32_t now=millis();if(emotion==THINKING&&now-lastThink>=700){lastThink=now;gimbal((frame/14)%2?82:98,92);}if(now-lastFace>=FACE_FRAME_MS){lastFace=now;++frame;drawFace();}delay(1);}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik