Approach B · DIY Camera Build

Orange Pi 5
Build Guide

Author: René SBC: Orange Pi 5 (RK3588S) Camera: OV13850 13MP MIPI Released: 2026-02-27

1. Project Overview

This guide documents the full process of building a standalone DIY camera based on the Orange Pi 5 single-board computer. The system consists of:

The goal is a fully self-contained camera that works without a keyboard or mouse, using only touch input for operation.

2. Hardware Requirements

ComponentModel / Details
SBCOrange Pi 5 (RK3588S)
Camera ModuleOV13850 13MP MIPI — official Orange Pi module
Camera CableFPC ribbon cable (included with camera module)
DisplayWaveshare 3.5" HDMI LCD (B) — 800×480 IPS resistive touch
Display ConnectionHDMI cable + 26-pin GPIO header
Power5V/4A USB-C power supply
StorageMicroSD card (16GB+) or eMMC
OptionalUSB keyboard and mouse (for initial setup only)
⚠️ The FPC ribbon cable is fragile and a common failure point. If the camera is not detected, try a replacement cable before assuming software issues.
The display uses HDMI for video and the 26-pin GPIO header for touch (SPI). The micro USB port on the display is power only — it does NOT carry touch data.

3. Software & System Info

ItemDetails
OS ImageOrangepi5_1.2.2_ubuntu_jammy_desktop_xfce_linux6.1.99
OSUbuntu 22.04 LTS (Jammy)
Kernel6.1.99-rockchip-rk3588
DesktopXFCE
Python3.10
GStreamer1.20.3
OpenCV4.5.4 (python3-opencv)

Download the official OS image from orangepi.org. Flash using balenaEtcher or Win32DiskImager.

4. Reference Documents & Links

Official Documentation

Drivers & Tools Used

Important Compatibility Notes

Do NOT use the Waveshare LCD-show scripts or waveshare-ads7846.dtbo — they target brcm,bcm2835 (Raspberry Pi) and are incompatible with RK3588.

The ADS7846 kernel driver (CONFIG_TOUCHSCREEN_ADS7846) is disabled in the Orange Pi 6.1 kernel. The userspace daemon approach in this guide bypasses this entirely.

5. Wiring Reference

26-Pin GPIO Header — SPI4 Pinout (Touch)

Physical PinFunctionGPIOWiringPi#Display Signal
19SPI4_TXD (MOSI)GPIO1_B1—TP_SI
21SPI4_RXD (MISO)GPIO1_B0—TP_SO
23SPI4_CLKGPIO1_B2—TP_SCK
24SPI4_CS1GPIO1_B4—(CS bridge — see note)
22GPIO2_D4GPIO 9213TP_IRQ
26PWM1GPIO 3516TP_CS
6/9/14/20/25GND——GND
1/173.3V——VCC
⚠️ Critical CS Pin: TP_CS is routed to pin 26, but SPI4_CS1 is on pin 24. The XPT2046 will not respond without CS on pin 26. This is handled via software in Patch 3 (Step 4).

Camera Connector

Connect the OV13850 to the CAM1 port. Use overlay ov13850-c1 — do not use c2 or c3 for this connector.

6. Step 1 — OS Setup

1.1 Flash the image

Flash the Ubuntu 22.04 image to a microSD card. Default credentials: orangepi / orangepi.

1.2 Update the system

sudo apt update && sudo apt upgrade -y

1.3 Enable Device Tree overlays

sudo nano /boot/orangepiEnv.txt

Set the overlays line to:

overlays=ov13850-c1 spi4-m0-cs1-spidev
⚠️ Never use spi4-m1-cs1-spidev — the M1 mux conflicts with the ethernet interface and will cause the network adapter to disappear after reboot.
sudo reboot

1.4 Verify SPI device

ls /dev/spidev4.1

7. Step 2 — Camera Setup

7.1 Connect the camera

Connect the OV13850 module to the CAM1 port using the FPC ribbon cable. Ensure both latches are fully closed.

⚠️ FPC cable failure is the most common hardware issue. If the camera is not detected after correct software setup, replace the cable first.

7.2 Verify the overlay is loaded

dmesg | grep ov13850

Expected output:

ov13850 7-0010: driver version: 00.01.05
ov13850 7-0010: Detected ov13850 sensor, CHIP ID = 0x138500

If you see Unexpected sensor id(000000), ret(-5) — the camera is not communicating. Check the FPC cable.

7.3 Verify the video device

v4l2-ctl --list-devices

The correct capture device is /dev/video11 (under rkisp_mainpath).

7.4 Test video capture

gst-launch-1.0 v4l2src device=/dev/video11 io-mode=4 ! \
  video/x-raw,format=NV12,width=1920,height=1080,framerate=30/1 ! \
  mpph264enc header-mode=1 bps=20000000 ! \
  h264parse config-interval=-1 ! matroskamux ! \
  filesink location=~/test.mkv

Press Ctrl+C to stop. Play with mpv ~/test.mkv.

Maximum capture resolution via the app is 2112×1568 (ISP V4L2 limit). The physical sensor supports up to 4208×3120 but requires ISP tuning.

8. Step 3 — Display Setup

The Waveshare 3.5" HDMI LCD is plug-and-play for video — HDMI is detected automatically at 800×480. No configuration needed.

  1. Connect HDMI cable from display to Orange Pi 5
  2. Connect display 26-pin connector to Orange Pi 5 26-pin header (align pin 1)
  3. The micro USB on the display can be connected for power but is not required
Do not use Raspberry Pi LCD-show scripts. They modify /boot/config.txt and install RPi-specific overlays that are incompatible with Orange Pi / RK3588.

9. Step 4 — Touch Input Setup

The resistive touch controller (XPT2046) has no kernel driver in this build — CONFIG_TOUCHSCREEN_ADS7846 is compiled out. Instead, a userspace daemon reads raw SPI data and injects X11 pointer events.

9.1 Install build dependencies

sudo apt install libx11-dev libxtst-dev -y

9.2 Install WiringOP

git clone https://github.com/zhaolei/WiringOP.git -b h3
cd WiringOP
chmod +x ./build
./build

9.3 Clone and patch the ADS7846 daemon

git clone https://github.com/Tomasz-Mankowski/ADS7846-X11-daemon.git
cd ADS7846-X11-daemon

Patch 1 — Fix C++ pointer comparison (compile error fix):

sed -i 's/if (gc < 0)/if (gc == nullptr)/' main.cpp

Patch 2 — Increase calibration timeout to 60 seconds:

sed -i 's/int waitTime = 5;/int waitTime = 60;/' main.cpp

Patch 3 — Software CS on pin 26 (critical — without this, touch never responds):

python3 - << 'EOF'
content = open('ADS7846.cpp').read()
content = content.replace(
    '#include "ADS7846.h"',
    '#include "ADS7846.h"\n#include <wiringPi.h>\n#define CS_PIN 16'
)
content = content.replace(
    '\tioctl(spiHandler_, SPI_IOC_MESSAGE(1), spi_message);',
    '\tpinMode(CS_PIN, OUTPUT);\n\tdigitalWrite(CS_PIN, LOW);\n\tioctl(spiHandler_, SPI_IOC_MESSAGE(1), spi_message);\n\tdigitalWrite(CS_PIN, HIGH);'
)
open('ADS7846.cpp', 'w').write(content)
print('Done')
EOF

9.4 Compile

make

9.5 Calibrate

sudo DISPLAY=:0.0 XAUTHORITY=/home/orangepi/.Xauthority \
  bash -c 'cd /home/orangepi/ADS7846-X11-daemon && \
  ./ADS7846-X11 --spi /dev/spidev4.1 --pin 13 --cal'

Tap each of the 3 crosshair targets. Verify calibration (values should not be 8191;8191):

cat ~/ADS7846-X11-daemon/calibpoints.cal

Expected output (values differ per calibration):

3458;3466
2065;808
684;2134

9.6 Test touch

sudo DISPLAY=:0.0 XAUTHORITY=/home/orangepi/.Xauthority \
  bash -c 'cd /home/orangepi/ADS7846-X11-daemon && \
  ./ADS7846-X11 --spi /dev/spidev4.1 --pin 13'

Touch the screen — the cursor should follow your finger.

10. Step 5 — Camera App Installation

10.1 Install Python dependencies

sudo apt install python3-opencv -y

Verify GStreamer Python bindings:

python3 -c "import gi; gi.require_version('Gst','1.0'); from gi.repository import Gst; Gst.init(None); print('OK')"

10.2 Install the camera app

Save the source code from Section 15 as camera_app.py in your home directory, then run:

cp camera_app.py ~/camera_app.py

10.3 Run the app

python3 ~/camera_app.py /dev/video11

10.4 Controls

KeyAction
PTake photo
VStart / stop video recording
SOpen settings menu
QQuit

In the settings menu:

KeyAction
1–4Select resolution
6–8Select photo format (JPEG / PNG / TIFF)
A–BSelect video format (MP4 H.264 / MKV H.264)
SClose settings

All photos and videos are saved to ~/Pictures/camera/.

11. Step 6 — Autostart Configuration

Create an autostart entry so the touch daemon launches automatically after login:

mkdir -p ~/.config/autostart
cat > ~/.config/autostart/touch.desktop << 'EOF'
[Desktop Entry]
Type=Application
Name=Touch Daemon
Exec=bash -c 'sleep 8 && DISPLAY=:0.0 XAUTHORITY=/home/orangepi/.Xauthority cd /home/orangepi/ADS7846-X11-daemon && sudo ./ADS7846-X11 --spi /dev/spidev4.1 --pin 13'
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
EOF

Add sudoers rule so the daemon runs without a password prompt:

echo 'orangepi ALL=(ALL) NOPASSWD: /home/orangepi/ADS7846-X11-daemon/ADS7846-X11' | \
  sudo tee /etc/sudoers.d/touch
The 8-second sleep gives the X session time to fully initialize. If touch still doesn't start, increase to sleep 15.

Reboot and confirm touch works without manually starting the daemon:

sudo reboot

12. Troubleshooting

SymptomLikely causeFix
Unexpected sensor id(000000)Faulty FPC cableReplace the ribbon cable
/dev/spidev4.1 missingWrong overlayCheck orangepiEnv.txt for spi4-m0-cs1-spidev
Touch returns 8191;8191CS pin not drivenEnsure Patch 3 was applied before compiling
Touch always clicks top-leftBad calibration filesudo rm calibpoints.cal and recalibrate
Ethernet disappears after rebootWrong SPI overlayChange spi4-m1 → spi4-m0 in orangepiEnv.txt
No camera preview in appGStreamer issueVerify io-mode=4 in pipeline; reinstall python3-opencv
MP4 corrupt / unplayableNo clean EOS signalUse MKV format for more robust recording
Touch daemon doesn't startSleep too shortIncrease sleep 8 to sleep 15 in autostart

13. Known Limitations

LimitationDetails
Max resolution via app2112×1568 (ISP V4L2 limit)
No H.265 videompph265enc not available in this GStreamer build
No touch kernel driverCONFIG_TOUCHSCREEN_ADS7846=n — userspace daemon required
No kernel headersCannot compile external kernel modules on this image
Touch requires X11Calibration and daemon require a running X session

14. FAQ

Can I use Raspberry Pi LCD-show scripts?

No. Those scripts modify /boot/config.txt and install RPi-specific device tree overlays that are incompatible with Orange Pi / RK3588.

Why is the ADS7846 kernel module not available?

The Orange Pi 6.1 kernel was compiled with CONFIG_TOUCHSCREEN_ADS7846=n. Enabling it requires recompiling the kernel from source, which also requires kernel headers not distributed for this image. The userspace daemon bypasses this entirely.

Can I connect to CAM2 or CAM3 instead of CAM1?

Yes — change the overlay accordingly: ov13850-c2 for CAM2 or ov13850-c3 for CAM3.

Why does video recording freeze the preview?

It doesn't — the app uses a GStreamer tee to split the stream so preview and recording run simultaneously from the same camera pipeline.

Can I add a physical shutter button?

Yes. Connect a button between physical pin 7 (GPIO1_C6, WiringPi 2) and any GND pin. Install python3-opi.gpio and the app will detect it automatically.

15. Camera App Source Code

Save the following as camera_app.py in your home directory:

#!/usr/bin/env python3
"""
OrangePi 5 Camera App
- Live preview always on via GStreamer tee
- Recording branches off tee without interrupting preview
- Photos: JPEG, PNG, TIFF
- Video:  MP4 H.264, MKV H.264
- Keys:   P=photo  V=record/stop  S=settings  Q=quit
- GPIO:   Pin 7 shutter (optional)
"""

import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstApp', '1.0')
from gi.repository import Gst, GstApp, GLib

import cv2
import numpy as np
import threading
import os
import time
import signal
from datetime import datetime

Gst.init(None)

# ── Config ─────────────────────────────────────────────────────────────────────

DEVICE   = "/dev/video11"
SAVE_DIR = os.path.expanduser("~/Pictures/camera")

RESOLUTIONS = [
    ("2112x1568", 2112, 1568, 15),
    ("1920x1080", 1920, 1080, 30),
    ("1280x720",  1280,  720, 30),
    ("720x576",    720,  576, 30),
]

PHOTO_FMTS = ["JPEG", "PNG", "TIFF"]
VIDEO_FMTS = ["MP4 H.264", "MKV H.264"]

# Colors BGR
DARK   = (35,  35,  35)
PANEL  = (50,  50,  50)
WHITE  = (240, 240, 240)
GRAY   = (120, 120, 120)
GREEN  = (60,  200, 80)
RED    = (40,  40,  220)
YELLOW = (30,  210, 230)

# ── GPIO ───────────────────────────────────────────────────────────────────────

gpio_ok = False
GPIO_PIN = 7
try:
    import OPi.GPIO as GPIO
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(GPIO_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    gpio_ok = True
except Exception:
    pass

# ── GStreamer pipeline ─────────────────────────────────────────────────────────

class Camera:
    def __init__(self, device, res_i):
        self.device  = device
        self.res_i   = res_i
        self.frame   = None
        self.lock    = threading.Lock()
        self.rec     = False
        self.rec_bin = None
        self.pipeline= None
        self.appsink = None
        self.tee     = None
        self.preview_queue = None
        self._build()

    def _build(self):
        label, w, h, fps = RESOLUTIONS[self.res_i]

        pipe_str = (
            f"v4l2src device={self.device} io-mode=4 ! "
            f"video/x-raw,format=NV12,width={w},height={h},framerate={fps}/1 ! "
            f"tee name=t "
            f"t. ! queue max-size-buffers=2 leaky=downstream ! "
            f"videoconvert ! video/x-raw,format=BGR ! "
            f"appsink name=preview emit-signals=true drop=true max-buffers=2 "
            f"t. ! queue name=rec_queue max-size-buffers=2 leaky=downstream ! "
            f"fakesink name=rec_sink"
        )

        self.pipeline = Gst.parse_launch(pipe_str)
        self.appsink  = self.pipeline.get_by_name("preview")
        self.tee      = self.pipeline.get_by_name("t")
        self.rec_sink = self.pipeline.get_by_name("rec_sink")
        self.rec_queue= self.pipeline.get_by_name("rec_queue")

        self.appsink.connect("new-sample", self._on_frame)

        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect("message::error", self._on_error)

        self.pipeline.set_state(Gst.State.PLAYING)

    def _on_frame(self, sink):
        sample = sink.emit("pull-sample")
        if sample:
            buf  = sample.get_buffer()
            caps = sample.get_caps()
            w    = caps.get_structure(0).get_value("width")
            h    = caps.get_structure(0).get_value("height")
            ok, mapinfo = buf.map(Gst.MapFlags.READ)
            if ok:
                arr = np.frombuffer(mapinfo.data, dtype=np.uint8).reshape((h, w, 3)).copy()
                buf.unmap(mapinfo)
                with self.lock:
                    self.frame = arr
        return Gst.FlowReturn.OK

    def _on_error(self, bus, msg):
        err, dbg = msg.parse_error()
        print(f"[GST ERROR] {err}: {dbg}")

    def get_frame(self):
        with self.lock:
            return self.frame.copy() if self.frame is not None else None

    def start_recording(self, path, fmt):
        if self.rec:
            return
        if "MP4" in fmt:
            enc_mux = ("mpph264enc header-mode=1 bps=20000000 ! "
                       "h264parse config-interval=-1 ! mp4mux fragment-duration=1000")
        else:
            enc_mux = ("mpph264enc header-mode=1 bps=20000000 ! "
                       "h264parse config-interval=-1 ! matroskamux")
        label, w, h, fps = RESOLUTIONS[self.res_i]
        bin_str = (
            f"videoconvert ! "
            f"video/x-raw,format=NV12,width={w},height={h} ! "
            f"{enc_mux} ! "
            f"filesink location={path}"
        )
        try:
            rec_bin = Gst.parse_bin_from_description(bin_str, True)
            self.pipeline.add(rec_bin)
            tee_src = self.tee.get_request_pad("src_%u")
            rec_sink_pad = rec_bin.get_static_pad("sink")
            tee_src.link(rec_sink_pad)
            rec_bin.sync_state_with_parent()
            self.rec_bin  = rec_bin
            self.tee_pad  = tee_src
            self.rec      = True
            print(f"[CAM] Recording started: {path}")
        except Exception as e:
            print(f"[CAM] Record start error: {e}")

    def stop_recording(self):
        if not self.rec or not self.rec_bin:
            return
        try:
            self.tee_pad.send_event(Gst.Event.new_eos())
            time.sleep(0.5)
            self.tee.release_request_pad(self.tee_pad)
            self.rec_bin.set_state(Gst.State.NULL)
            self.pipeline.remove(self.rec_bin)
        except Exception as e:
            print(f"[CAM] Record stop error: {e}")
        finally:
            self.rec_bin = None
            self.tee_pad = None
            self.rec     = False
            print("[CAM] Recording stopped")

    def restart(self, res_i):
        self.pipeline.set_state(Gst.State.NULL)
        self.pipeline = None
        self.res_i    = res_i
        self._build()

    def stop(self):
        if self.rec:
            self.stop_recording()
        if self.pipeline:
            self.pipeline.set_state(Gst.State.NULL)

# ── App ────────────────────────────────────────────────────────────────────────

class App:
    def __init__(self):
        os.makedirs(SAVE_DIR, exist_ok=True)
        self.res_i   = 1
        self.pfmt_i  = 0
        self.vfmt_i  = 0
        self.flash   = 0
        self.status  = "Ready"
        self.status_t= 0
        self.settings= False
        self.prev_btn= False
        self.rec_t   = 0
        self.cam = Camera(DEVICE, self.res_i)
        cv2.namedWindow("Camera", cv2.WINDOW_NORMAL)
        cv2.resizeWindow("Camera", 1280, 760)

    def msg(self, text, secs=3):
        self.status   = text
        self.status_t = time.time() + secs
        print("[APP]", text)

    def ts(self):
        return datetime.now().strftime("%Y%m%d_%H%M%S")

    def snap(self):
        frame = self.cam.get_frame()
        if frame is None:
            self.msg("No frame!")
            return
        fmt  = PHOTO_FMTS[self.pfmt_i]
        exts = {"JPEG": ".jpg", "PNG": ".png", "TIFF": ".tiff"}
        path = os.path.join(SAVE_DIR, f"photo_{self.ts()}{exts[fmt]}")
        params = []
        if fmt == "JPEG":
            params = [cv2.IMWRITE_JPEG_QUALITY, 95]
        elif fmt == "PNG":
            params = [cv2.IMWRITE_PNG_COMPRESSION, 1]
        cv2.imwrite(path, frame, params)
        self.msg(f"Photo: {os.path.basename(path)}")
        self.flash = time.time() + 0.2

    def toggle_rec(self):
        if self.cam.rec:
            self.cam.stop_recording()
            secs = int(time.time() - self.rec_t)
            self.msg(f"Video saved ({secs}s)")
        else:
            fmt  = VIDEO_FMTS[self.vfmt_i]
            ext  = ".mp4" if "MP4" in fmt else ".mkv"
            path = os.path.join(SAVE_DIR, f"video_{self.ts()}{ext}")
            self.cam.start_recording(path, fmt)
            self.rec_t = time.time()
            self.msg(f"Recording {fmt}...", 99999)

    def set_res(self, i):
        if self.cam.rec:
            self.msg("Stop recording first!")
            return
        self.res_i = i
        self.cam.restart(i)
        self.msg(f"Resolution: {RESOLUTIONS[i][0]}")

    def run(self):
        print(f"OPI5 Camera | {SAVE_DIR}")
        print("P=photo  V=video  S=settings  Q=quit")
        last_frame = None
        while True:
            frame = self.cam.get_frame()
            if frame is not None:
                last_frame = frame
            if last_frame is None:
                time.sleep(0.03)
                continue
            cv2.imshow("Camera", last_frame)
            k = cv2.waitKey(1) & 0xFF
            if not self.key(k):
                break
        self.cam.stop()
        cv2.destroyAllWindows()
        print("Done.")

    def key(self, k):
        if k == -1:
            return True
        if k == ord('q'):
            return False
        elif k == ord('p') and not self.cam.rec:
            self.snap()
        elif k == ord('v'):
            self.toggle_rec()
        elif k == ord('s'):
            self.settings = not self.settings
        return True

# ── Entry ──────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        DEVICE = sys.argv[1]
    if not os.path.exists(DEVICE):
        print(f"Device not found: {DEVICE}")
        os.system("v4l2-ctl --list-devices 2>/dev/null")
        sys.exit(1)
    try:
        App().run()
    except KeyboardInterrupt:
        print("Interrupted.")

16. Changelog

VersionDateNotes
1.02026-02-27Initial release

This guide and the camera application code are released under the MIT License. The ADS7846-X11-daemon is by Tomasz Mankowski — see the original repository for its license.