# TurboPi Setup Guide (Fresh Raspberry Pi OS)

Consolidated from HiWonder's official documentation (Lessons 1, 5, and Power-On Guide).
For Pi 5 running stock Debian Trixie (NOT HiWonder's custom image).

## Prerequisites

- HiWonder TurboPi robot car (assembled)
- Raspberry Pi 5 (16 GB) running Debian Trixie 13
- 2x 18650 batteries (charged via included charger, ~3 hours, green=done)
- Battery case switch set to OFF during setup

## Step 1: Power Architecture

The 18650 battery pack is the **single power source** for everything — the Pi AND
the controller board are both powered through the expansion board. There is no
separate USB-C power input; the Pi receives 5V via the GPIO header from the
expansion board's voltage regulator.

- Battery switch ON → powers Pi + STM32 controller + motors + servos + LEDs
- Battery switch OFF → everything is off
- No separate USB-C needed (and it's hard to reach physically)

1. Charge both 18650 batteries (charger indicator: red=charging, green=done)
2. Insert batteries into case (correct polarity!)
3. Close battery cover

### Power-On Indicators (after setup)
- **LED1** = power indicator (dim = low battery)
- **LED2** = communication indicator (blinks = AP mode, solid = LAN mode)
- On successful boot with HiWonder image: buzzer beeps + pan-tilt centers (~60s)
- Low voltage alarm at 7.1V (continuous beeping)

## Step 2: Install System Dependencies

```bash
# Update system
sudo apt-get update -y && sudo apt-get upgrade -y

# Clean unnecessary packages
sudo apt-get autoremove -y && sudo apt-get autoclean -y && sudo apt-get clean -y

# Install required packages
sudo apt-get install -y vim git terminator htop curl python3-opencv gedit libjpeg-dev xclip wl-clipboard python3-serial

# Allow pip to install system-wide
mkdir -p ~/.pip
cat > ~/.pip/pip.conf << 'EOF'
[global]
break-system-packages = True
EOF

# Install GPIO library
pip3 install gpiod

# Verify GPIO detection
gpiodetect
# Expected: gpiochip0-4 including pinctrl-rp1
```

## Step 3: Enable UART Interface

### 3.1 Via raspi-config (headless)

```bash
# Enable Serial Port, disable Serial Console
sudo raspi-config nonint do_serial_hw 0    # Enable serial hardware
sudo raspi-config nonint do_serial_cons 1  # Disable serial console
```

### 3.2 Edit config.txt

```bash
sudo nano /boot/firmware/config.txt
```

Add at the end of the file:

```
dtoverlay=pi3-miniuart-bt
Force_turbo=1
```

**What these do:**
- `dtoverlay=pi3-miniuart-bt` — Moves Bluetooth to the mini-UART, freeing the
  full PL011 UART (`ttyAMA0`) for the controller board. This is critical because
  Bluetooth otherwise claims the high-speed UART.
- `Force_turbo=1` — Prevents CPU frequency scaling which can cause UART baud
  rate instability at high speeds (1 Mbaud).

### 3.3 Set serial permissions

```bash
sudo chmod 777 /dev/ttyAMA0
```

### 3.4 Reboot

```bash
sudo reboot
```

### 3.5 Verify serial port assignment

After reboot:

```bash
ls -la /dev/serial*
```

**Expected on Pi 5:** `serial0 -> ttyAMA10`

**Note:** On Pi 5, the UART maps to `/dev/ttyAMA10` (not `/dev/ttyAMA0` like Pi 4).
The SDK's default `Board(device="/dev/ttyAMA0")` may need to be changed to
`/dev/ttyAMA10`, OR `serial0` can be used as a portable alias.

## Step 4: Fix SDK Path

The SDK hardcodes `/home/pi/TurboPi/`. Since our user is `rajesh`:

```bash
sudo ln -sf /home/rajesh /home/pi
```

This makes `/home/pi/TurboPi/` resolve to `/home/rajesh/TurboPi/`.

## Step 5: Hardware Test

1. **Turn battery switch ON** — wait a few seconds for the controller board to boot
2. Run the test:

```python
import sys
sys.path.append('/home/pi/TurboPi/')
import HiwonderSDK.ros_robot_controller_sdk as rrc
import time

# Try ttyAMA10 first (Pi 5), fall back to ttyAMA0
for port in ['/dev/ttyAMA10', '/dev/ttyAMA0', '/dev/serial0']:
    try:
        board = rrc.Board(device=port)
        time.sleep(0.5)
        print(f"Connected on {port}")
        break
    except Exception as e:
        print(f"{port}: {e}")
        continue

# Buzzer test (most obvious feedback)
board.set_buzzer(1000, 0.5, 0.5, 1)
time.sleep(1.5)

# Servo test (pan camera left-right)
board.pwm_servo_set_position(0.3, [[1, 1800]])
time.sleep(0.4)
board.pwm_servo_set_position(0.3, [[1, 1500]])
time.sleep(0.4)

# Motor test (each wheel briefly)
for i in range(1, 5):
    board.set_motor_duty([[i, 35]])
    time.sleep(0.5)
    board.set_motor_duty([[i, 0]])
    time.sleep(0.3)

print("All tests passed!")
```

## Step 6: Install Vision Dependencies (optional)

```bash
# OpenCV (if not installed via apt)
pip3 install opencv-python-headless

# MediaPipe for face/gesture tracking
pip3 install mediapipe

# PyYAML for config files
pip3 install pyyaml
```

## Troubleshooting

### Nothing moves, no buzzer
- **UART not configured** — Most likely cause on fresh Pi OS. Follow Steps 3-4.
- **Dead batteries** — Check LED1 on expansion board (dim/off = dead battery).
  Note: if the Pi is running, the battery is fine (single power source).

### Serial returns 0 bytes
- **UART not enabled** — Run `raspi-config` serial setup + config.txt changes
- **Wrong port** — Pi 5 uses `ttyAMA10`, not `ttyAMA0`. Check `ls -la /dev/serial*`
- **Bluetooth conflict** — Ensure `dtoverlay=pi3-miniuart-bt` is in config.txt

### CH340 on /dev/ttyUSB0
- This is **NOT** the controller board. The CH340 USB-serial adapter is likely
  the ultrasonic sensor or another peripheral.
- The controller board connects via **GPIO UART** (pins 8/10 = TX/RX)

### SDK path errors
- Ensure `/home/pi` symlink exists: `sudo ln -sf /home/rajesh /home/pi`
- Or modify `sys.path.append` in scripts to use actual path

## Hardware Connections

| Component | GPIO Pin | Header Pin |
|-----------|----------|------------|
| UART TX   | GPIO14   | Pin 8      |
| UART RX   | GPIO15   | Pin 10     |
| GND       | GND      | Pin 6      |

Serial protocol: 0xAA 0x55 header, CRC8 checksum, 1 Mbaud.

## Google Drive Resources

- **Root folder:** https://drive.google.com/drive/folders/1r3Jbn0MGWH1XD74dS-m_UzUlHFutRjrm
- **Local copy:** `/tmp/turbopi-docs/` (partial download, ~939 MB)
- **Key PDFs:** Lesson 1 (GPIO setup), Lesson 5 (UART config), Power-On Instructions
