documentation Documentation

The official documentation for Raspberry Pi computers and microcontrollers

RAW Doc

Technical Documentation: raspberrypi/documentation

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (README.md)

This repository contains the source and tools used to build the Raspberry Pi Documentation.

Licence

The Raspberry Pi documentation is licensed under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA). Documentation tools (everything outside of the documentation/ subdirectory) are licensed under the BSD 3-Clause licence.


Documentation Htaccess Extra (`documentation/htaccess_extra.txt`)

Redirect 302 "/documentation/hardware/raspberrypi/conformity.md" "https://pip.raspberrypi.com"
Redirect 410 "/documentation/configuration/wireless/access-point-routed.md"
Redirect 410 "/documentation/configuration/wireless/access-point-bridged.md"
RedirectMatch 302 "^/documentation/faqs" "/documentation/"
RedirectMatch 302 "^/documentation/rp2040" "/documentation/microcontrollers/"
RedirectMatch 302 "^/documentation/hardware/raspberrypi/compliance/" "https://pip.raspberrypi.com"
RedirectMatch 302 "^/documentation/hardware/camera/" "/documentation/accessories/camera.html"
RedirectMatch 302 "^/documentation/hardware/computemodule/" "/documentation/computers/compute-module.html"
RedirectMatch 302 "^/documentation/hardware/display/" "/documentation/accessories/display.html"
RedirectMatch 302 "^/documentation/hardware/raspberrypi/bcm2711/" "/documentation/computers/processors.html"
RedirectMatch 302 "^/documentation/hardware/raspberrypi/bcm2835/" "/documentation/computers/processors.html"
RedirectMatch 302 "^/documentation/hardware/raspberrypi/bcm2836/" "/documentation/computers/processors.html"
RedirectMatch 302 "^/documentation/hardware/raspberrypi/bcm2837/" "/documentation/computers/processors.html"
RedirectMatch 302 "^/documentation/hardware/raspberrypi/bcm2837b0/" "/documentation/computers/processors.html"
RedirectMatch 302 "^/documentation/hardware/sense-hat/" "/documentation/accessories/sense-hat.html"
RedirectMatch 302 "^/documentation/hardware/tv-hat/" "/documentation/accessories/tv-hat.html"
RedirectMatch 302 "^/documentation/hardware/" "/documentation/computers/raspberry-pi.html"
RedirectMatch 302 "^/documentation/installation/" "/documentation/computers/getting-started.html"
RedirectMatch 302 "^/documentation/linux/kernel/" "/documentation/computers/linux_kernel.html"
RedirectMatch 302 "^/documentation/linux/software/libcamera/" "/documentation/accessories/camera.html"
RedirectMatch 302 "^/documentation/linux/software/" "/documentation/computers/os.html"
RedirectMatch 302 "^/documentation/raspbian/" "/documentation/computers/os.html"
RedirectMatch 302 "^/documentation/remote-access/" "/documentation/computers/remote-access.html"
RedirectMatch 302 "^/documentation/setup/" "/documentation/computers/getting-started.html"
RedirectMatch 302 "^/documentation/usage/camera/" "/documentation/accessories/camera.html"
RedirectMatch 302 "^/documentation/usage/" "/documentation/computers/os.html"
RedirectMatch 302 "^/documentation/configuration/" "/documentation/computers/configuration.html"
RedirectMatch 302 "^/documentation/computers/raspberry-pi-5.html" "/documentation/computers/raspberry-pi.html"
RedirectMatch 302 "^/documentation/microcontrollers/rp1.html" "/documentation/microcontrollers/silicon.html"
RedirectMatch 302 "^/documentation/microcontrollers/rp2040.html" "/documentation/microcontrollers/silicon.html"
RedirectMatch 302 "^/documentation/microcontrollers/raspberry-pi-pico.html" "/documentation/microcontrollers/pico-series.html"
RedirectMatch 302 "^/documentation/microcontrollers/pico.html" "/documentation/microcontrollers/pico-series.html"
RedirectMatch 302 "^/documentation/accessories/usb-3-hub.html" "/documentation/accessories/usb.html"
RedirectMatch 302 "^/documentation/microcontrollers/rp1.html" "/documentation/microcontrollers/microcontroller-chips.html"
RedirectMatch 302 "^/documentation/microcontrollers/rp2040.html" "/documentation/microcontrollers/microcontroller-chips.html"
RedirectMatch 302 "^/documentation/microcontrollers/rp2350.html" "/documentation/microcontrollers/microcontroller-chips.html"
RedirectMatch 302 "^/documentation/microcontrollers/silicon.html" "/documentation/microcontrollers/microcontroller-chips.html"


Documentation Asciidoc Accessories Ai Camera (`documentation/asciidoc/accessories/ai-camera.adoc`)

include::ai-camera/about.adoc[]

include::ai-camera/getting-started.adoc[]

include::ai-camera/details.adoc[]

include::ai-camera/model-conversion.adoc[]


Documentation Asciidoc Accessories Audio (`documentation/asciidoc/accessories/audio.adoc`)

include::audio/introduction.adoc[]

include::audio/dac_pro.adoc[]

include::audio/dac_plus.adoc[]

include::audio/digiamp_plus.adoc[]

include::audio/codec_zero.adoc[]

include::audio/configuration.adoc[]

include::audio/getting_started.adoc[]

include::audio/hardware-info.adoc[]

include::audio/update-firmware.adoc[]


Documentation Asciidoc Accessories Build Hat (`documentation/asciidoc/accessories/build-hat.adoc`)

// Intro

include::build-hat/introduction.adoc[]

include::build-hat/preparing-build-hat.adoc[]

// Python

include::build-hat/py-installing-software.adoc[]

include::build-hat/py-motors.adoc[]

include::build-hat/py-sensors.adoc[]

// .NET

include::build-hat/net-installing-software.adoc[]

include::build-hat/net-brick.adoc[]

include::build-hat/net-motors.adoc[]

include::build-hat/net-sensors.adoc[]

// Close out

include::build-hat/links-to-other.adoc[]

include::build-hat/compat.adoc[]

include::build-hat/mech.adoc[]


Documentation Asciidoc Accessories Camera (`documentation/asciidoc/accessories/camera.adoc`)

include::camera/intro.adoc[]

include::camera/install.adoc[]

include::camera/cm2.adoc[]

include::camera/cm3.adoc[]

include::camera/gs.adoc[]

include::camera/hq.adoc[]

include::camera/lens.adoc[]

include::camera/synchronous_cameras.adoc[]

include::camera/external_trigger.adoc[]

include::camera/filters.adoc[]

include::camera/hardware_specification.adoc[]

include::camera/advanced.adoc[]


Documentation Asciidoc Accessories Keyboard And Mouse (`documentation/asciidoc/accessories/keyboard-and-mouse.adoc`)

include::keyboard-and-mouse/getting-started-keyboard.adoc[]

include::keyboard-and-mouse/getting-started-mouse.adoc[]

include::keyboard-and-mouse/connecting-things.adoc[]


Documentation Asciidoc Accessories Sense Hat (`documentation/asciidoc/accessories/sense-hat.adoc`)

include::sense-hat/intro.adoc[]

include::sense-hat/hardware.adoc[]

include::sense-hat/software.adoc[]


Documentation Asciidoc Computers Camera Software (`documentation/asciidoc/computers/camera_software.adoc`)

include::camera/camera_usage.adoc[]

include::camera/rpicam_apps_intro.adoc[]

include::camera/rpicam_hello.adoc[]

include::camera/rpicam_jpeg.adoc[]

include::camera/rpicam_still.adoc[]

include::camera/rpicam_vid.adoc[]

include::camera/rpicam_raw.adoc[]

include::camera/rpicam_detect.adoc[]

include::camera/rpicam_configuration.adoc[]

include::camera/rpicam_apps_multicam.adoc[]

include::camera/rpicam_apps_packages.adoc[]

include::camera/streaming.adoc[]

include::camera/rpicam_options_common.adoc[]

include::camera/rpicam_options_still.adoc[]

include::camera/rpicam_options_vid.adoc[]

include::camera/rpicam_options_libav.adoc[]

include::camera/rpicam_options_detect.adoc[]

include::camera/rpicam_apps_post_processing.adoc[]

include::camera/rpicam_apps_post_processing_opencv.adoc[]

include::camera/rpicam_apps_post_processing_tflite.adoc[]

include::camera/rpicam_apps_post_processing_writing.adoc[]

include::camera/rpicam_apps_building.adoc[]

include::camera/rpicam_apps_writing.adoc[]

include::camera/qt.adoc[]

include::camera/libcamera_python.adoc[]

include::camera/webcams.adoc[]

include::camera/v4l2.adoc[]

include::camera/csi-2-usage.adoc[]

include::camera/libcamera_differences.adoc[]

include::camera/troubleshooting.adoc[]

include::camera/rpicam_apps_getting_help.adoc[]


Documentation Asciidoc Computers Compute Module (`documentation/asciidoc/computers/compute-module.adoc`)

include::compute-module/introduction.adoc[]

include::compute-module/cm-emmc-flashing.adoc[]

include::compute-module/cm-bootloader.adoc[]

include::compute-module/cm-peri-sw-guide.adoc[]

include::compute-module/cmio-camera.adoc[]

include::compute-module/cmio-display.adoc[]

include::compute-module/datasheet.adoc[]


Documentation Asciidoc Computers Config Txt (`documentation/asciidoc/computers/config_txt.adoc`)

include::config_txt/what_is_config_txt.adoc[]

include::config_txt/autoboot.adoc[]

include::config_txt/common.adoc[]

include::config_txt/audio.adoc[]

include::config_txt/boot.adoc[]

include::config_txt/gpio.adoc[]

include::config_txt/overclocking.adoc[]

include::config_txt/conditional.adoc[]

include::config_txt/memory.adoc[]

include::config_txt/codeclicence.adoc[]

include::config_txt/video.adoc[]

include::config_txt/camera.adoc[]


Documentation Asciidoc Computers Configuration (`documentation/asciidoc/computers/configuration.adoc`)

include::configuration/raspi-config.adoc[]

include::configuration/appearance.adoc[]

include::configuration/audio-display.adoc[]

include::configuration/configuring-networking.adoc[]

include::configuration/localisation.adoc[]

include::configuration/users.adoc[]

include::configuration/interfaces.adoc[]

include::configuration/performance.adoc[]

include::configuration/led_blink_warnings.adoc[]

include::configuration/boot-behaviour.adoc[]

include::configuration/firmware.adoc[]

include::configuration/external-storage.adoc[]

include::configuration/reference.adoc[]


Documentation Asciidoc Computers Getting Started (`documentation/asciidoc/computers/getting-started.adoc`)

include::getting-started/setting-up.adoc[]

include::getting-started/install.adoc[]

include::getting-started/configuring.adoc[]

include::getting-started/wrapping-up.adoc[]


Documentation Asciidoc Computers Legacy Config Txt (`documentation/asciidoc/computers/legacy_config_txt.adoc`)

include::legacy_config_txt/legacy.adoc[]

include::legacy_config_txt/boot.adoc[]

include::legacy_config_txt/overclocking.adoc[]

include::legacy_config_txt/conditional.adoc[]

include::legacy_config_txt/memory.adoc[]

include::legacy_config_txt/video.adoc[]

include::legacy_config_txt/pi4-hdmi.adoc[]

include::legacy_config_txt/misc.adoc[]


Documentation Asciidoc Computers Linux Kernel (`documentation/asciidoc/computers/linux_kernel.adoc`)

include::linux_kernel/about-kernel.adoc[]

include::linux_kernel/building.adoc[]

include::linux_kernel/configuring.adoc[]

include::linux_kernel/patching.adoc[]

include::linux_kernel/headers.adoc[]

include::linux_kernel/contribute.adoc[]


Documentation Asciidoc Computers Os (`documentation/asciidoc/computers/os.adoc`)

include::os/rpi-os-introduction.adoc[]

include::os/updating.adoc[]

include::os/playing-audio-and-video.adoc[]

include::os/graphics-utilities.adoc[]

include::os/accessibility.adoc[]

include::os/using-python.adoc[]

include::os/using-gpio.adoc[]


Documentation Asciidoc Computers Processors (`documentation/asciidoc/computers/processors.adoc`)

include::processors/bcm2835.adoc[]

include::processors/bcm2836.adoc[]

include::processors/bcm2837.adoc[]

include::processors/bcm2837b0.adoc[]

include::processors/bcm2711.adoc[]

include::processors/bcm2712.adoc[]

include::processors/rp3a0.adoc[]


Documentation Asciidoc Computers Raspberry Pi (`documentation/asciidoc/computers/raspberry-pi.adoc`)

include::raspberry-pi/introduction.adoc[]

include::raspberry-pi/raspberry-pi-schematics.adoc[]

include::raspberry-pi/raspberry-pi-compliance.adoc[]

include::raspberry-pi/frequency-management.adoc[]

include::raspberry-pi/boot-eeprom.adoc[]

include::raspberry-pi/boot-eeprom-diagnostics.adoc[]

include::raspberry-pi/bootmodes.adoc[]

include::raspberry-pi/boot-usb.adoc[]

include::raspberry-pi/boot-msd.adoc[]

include::raspberry-pi/boot-net.adoc[]

include::raspberry-pi/boot-gpio.adoc[]

include::raspberry-pi/boot-nvme.adoc[]

include::raspberry-pi/boot-http.adoc[]

include::raspberry-pi/bootflow-legacy.adoc[]

include::raspberry-pi/bootflow-eeprom.adoc[]

include::raspberry-pi/eeprom-bootloader.adoc[]

include::raspberry-pi/display-parallel-interface.adoc[]

include::raspberry-pi/gpio-on-raspberry-pi.adoc[]

include::raspberry-pi/gpio-pad-controls.adoc[]

include::raspberry-pi/raspberry-pi-industrial.adoc[]

include::raspberry-pi/otp-bits.adoc[]

include::raspberry-pi/pcie.adoc[]

include::raspberry-pi/power-button.adoc[]

include::raspberry-pi/power-supplies.adoc[]

include::raspberry-pi/rtc.adoc[]

include::raspberry-pi/spi-bus-on-raspberry-pi.adoc[]

include::raspberry-pi/usb-bus-on-raspberry-pi.adoc[]

include::raspberry-pi/revision-codes.adoc[]


Documentation Asciidoc Computers Remote Access (`documentation/asciidoc/computers/remote-access.adoc`)

include::remote-access/introduction.adoc[]

include::remote-access/find-your-ip-address.adoc[]

include::remote-access/ssh.adoc[]

include::remote-access/vnc.adoc[]

include::remote-access/raspberry-pi-connect.adoc[]

include::remote-access/scp.adoc[]

include::remote-access/rsync.adoc[]

include::remote-access/nfs.adoc[]

include::remote-access/samba.adoc[]

include::remote-access/apache.adoc[]

include::remote-access/network-boot-raspberry-pi.adoc[]

include::remote-access/network-boot-ipv6.adoc[]


Documentation Asciidoc Computers Software Sources (`documentation/asciidoc/computers/software-sources.adoc`)

At Raspberry Pi we're trying to open source as much of our code as possible to make it easy to use and adapt for your own uses. Raspberry Pi develops and supports software specifically for our products and focuses its energy on software which provides the most optimal user experience. For example, drivers that optimise multimedia acceleration such as the 3D, HEVC decode, the camera imaging pipeline, AI acceleration, dual HDMI and audio.

== Finding software sources in Raspberry Pi OS

When looking for software which is distributed with Raspberry Pi OS, there are often upstream software sources that we patch to create our downstream packages (those tagged with pass:[+rpt]). To view the source for those packages it's usually easier to fetch through apt. To do this, you first need to edit your apt lists to include the source packages. Edit the following files to change each "Types: deb" line to "Types: deb deb-src":

  • +/etc/apt/sources.list.d/debian.sources+ (on 64-bit images)
    or
  • +/etc/apt/sources.list.d/raspbian.sources+ (on 32-bit images)
    and
  • +/etc/apt/sources.list.d/raspi.sources+

Next you must update the package lists:

[source,console]

$ sudo apt update

Now you can fetch the package source, for example:

[source,console]

$ apt source labwc

Next, you need to install a helper package:

[source,console]

$ sudo apt install devscripts

Finally you can build the package using the standard Debian building process.

[source,console]

$ sudo apt build-dep labwc $ cd labwc-0.8.4 $ debuild -uc -us

== Our GitHub organisations

The other place you can find our software in a more standard form is in our GitHub repositories; we have three GitHub organisations we use to publish our sources:

We also publish content related to our books and magazine in the following organisations:

== List of categorised sources

The following is a curated list of repositories that most people are interested in:

=== Main sources

https://github.com/raspberrypi/linux::
This repository contains the source code for the downstream Linux kernel supported and working on all versions of Raspberry Pi from 1 to 5.

https://github.com/raspberrypi/firmware::
This repository contains the closed source firmware, although the following two links are useful:

https://github.com/raspberrypi/rpi-eeprom::
Installation scripts and binaries for the Raspberry Pi 4 and Raspberry Pi 5 bootloader EEPROMs including the https://github.com/raspberrypi/rpi-eeprom/releases[releases] and https://github.com/raspberrypi/rpi-eeprom/blob/master/releases.md[release notes].

=== Libraries and applications

https://github.com/raspberrypi/utils::
A collection of useful utilities such as pinctrl, piolib, and raspinfo, also gpiolib a Raspberry Pi supported method of directly accessing GPIO pins.

https://github.com/raspberrypi/libcamera::
A libcamera library implementation for controlling the Raspberry Pi device's ISP and cameras.

https://github.com/raspberrypi/rpicam-apps::
A C++ library and application suite for image/video processing and encoding with Raspberry Pi cameras using libcamera.

https://github.com/raspberrypi/picamera2::
A Python library for using and controlling the Raspberry Pi cameras.

https://github.com/raspberrypi/drmu::
A library for directly controlling and accessing multimedia interfaces.

=== Desktop

https://github.com/raspberrypi-ui/rpd-metas::
The metapackages used to create the desktop.

https://github.com/raspberrypi-ui/wf-panel-pi::
The taskbar or dock displayed on the screen when running the Wayland-based desktop.

https://github.com/raspberrypi-ui/lxpanel-pi::
The taskbar displayed at the top of the screen when running the legacy X-based desktop.

https://github.com/raspberrypi-ui/pplug-batt::
https://github.com/raspberrypi-ui/pplug-bluetooth::
https://github.com/raspberrypi-ui/pplug-clock::
https://github.com/raspberrypi-ui/pplug-cpu::
https://github.com/raspberrypi-ui/pplug-cputemp::
https://github.com/raspberrypi-ui/pplug-ejecter::
https://github.com/raspberrypi-ui/pplug-gpu::
https://github.com/raspberrypi-ui/pplug-menu::
https://github.com/raspberrypi-ui/pplug-netman::
https://github.com/raspberrypi-ui/pplug-power::
https://github.com/raspberrypi-ui/pplug-updater::
https://github.com/raspberrypi-ui/pplug-volumepulse::
The widgets displayed on the taskbars.

https://github.com/raspberrypi-ui/pcmanfm::
https://github.com/raspberrypi-ui/libfm::
The file manager used by the desktop, which also displays the desktop background.

https://github.com/raspberrypi-ui/rpcc::
The Control Centre application.

https://github.com/raspberrypi-ui/rc_gui::
The Raspberry Pi configuration plugin for Control Centre.

https://github.com/raspberrypi-ui/appset::
The appearance settings plugin for Control Centre.

https://github.com/raspberrypi-ui/rasputin::
The mouse and keyboard settings plugin for Control Centre.

https://github.com/raspberrypi-ui/raindrop::
The screen configuration plugin for Control Centre.

https://github.com/raspberrypi-ui/rpinters::
The printer settings plugin for Control Centre.

=== Applications

https://github.com/raspberrypi-ui/agnostics::
The Diagnostics application used to check SD cards.

https://github.com/raspberrypi-ui/bookshelf::
The code for the Bookshelf application which allows you to download and read e-books and past issues of the Raspberry Pi Official Magazine.

https://github.com/raspberrypi-ui/piclone::
The SD Card Copier application which allows cards and drives to be cloned.

https://github.com/raspberrypi-ui/rp-prefapps::
The Recommended Software application which allows selected programs to be installed or removed.

=== Debug

https://github.com/raspberrypi/rpi-analyse-boot::
A boot analysis service that gathers boot-time metrics from various different sources.

=== Tools

https://github.com/raspberrypi/rpi-imager::
The code for the Raspberry Pi Imager application which flashes an operating system to an SD card.

https://github.com/raspberrypi/rpi-image-gen::
A build system for developing an operating system for an embedded Raspberry Pi system.

https://github.com/raspberrypi/usbboot::
A tool to boot a Raspberry Pi over USB for provisioning Compute Module and Raspberry Pi devices.

https://github.com/raspberrypi/rpi-sb-provisioner::
A tool to mass provision Raspberry Pi devices, including secure boot and encrypted file systems. (Raspberry Pi 5, Compute Module 4, and Compute Module 5 are supported.)

=== Feedback

https://github.com/raspberrypi/trixie-feedback::
A repo specifically reserved for bug-reporting for the current Raspberry Pi OS release.

=== Raspberry Pi Pico

https://marketplace.visualstudio.com/items?itemName=raspberry-pi.raspberry-pi-pico::
This is where you can go to download and install the Microsoft Visual Studio Code extension for the Raspberry Pi Pico SDK.

https://github.com/raspberrypi/pico-setup::
Quick-start installation tool for the Raspberry Pi Pico SDK for command line use.

https://github.com/raspberrypi/pico-sdk::
The Raspberry Pi Pico SDK sources.

https://github.com/raspberrypi/debugprobe::
Sources for the Raspberry Pi Debug Probe, providing both SWD and UART easily.

https://github.com/raspberrypi/openocd::
The Raspberry Pi downstream OpenOCD sources.

https://github.com/raspberrypi/pico-examples::
Examples for Raspberry Pi Pico.

https://github.com/raspberrypi/picotool::
Tool for interacting with RP-series devices in BOOTSEL mode.


Documentation Asciidoc Microcontrollers C Sdk (`documentation/asciidoc/microcontrollers/c_sdk.adoc`)

include::c_sdk/sdk_setup.adoc[]

include::c_sdk/official_sdk.adoc[]

include::c_sdk/your_first_binary.adoc[]

include::c_sdk/quick_start.adoc[]


Documentation Asciidoc Microcontrollers Debug Probe (`documentation/asciidoc/microcontrollers/debug-probe.adoc`)

include::debug-probe/introduction.adoc[]

include::debug-probe/getting-started.adoc[]

include::debug-probe/installing-tools.adoc[]

include::debug-probe/swd-connection.adoc[]

include::debug-probe/uart-connection.adoc[]

include::debug-probe/updating-firmware.adoc[]

include::debug-probe/schematics.adoc[]


Documentation Asciidoc Microcontrollers Microcontroller Chips (`documentation/asciidoc/microcontrollers/microcontroller-chips.adoc`)

Raspberry Pi designs its own microcontrollers, which are standalone silicon chips for small embedded projects that provide real-time hardware control. These chips are used in Raspberry Pi Pico boards and can be used in third-party microcontroller boards. For more information about Raspberry Pi Pico, see xref:../microcontrollers/pico-series.adoc[Pico microcontroller boards].

Raspberry Pi microcontrollers can be programmed using:

  • C or {cpp}, which are performance focussed and provide full control over hardware.
  • MicroPython, which provides simpler scripting for rapid development.

For more information on developing with RP2040 or RP2350, see the xref:c_sdk.adoc#sdk-setup[C/{cpp} SDK] and xref:micropython.adoc#what-is-micropython[MicroPython] documentation.

== Microcontroller overview

Raspberry Pi microcontrollers are silicon chips that handle specific, real-time tasks, like controlling motors or reading sensors, in embedded systems. Raspberry Pi offers two microcontrollers:

  • xref:../microcontrollers/microcontroller-chips.adoc#rp2040[RP2040] is the original, general-purpose, dual-core Raspberry Pi microcontroller: a simple, cost-effective microcontroller unit (MCU).
  • xref:../microcontrollers/microcontroller-chips.adoc#rp2350[RP2350] is a high-performance, dual-core microcontroller for applications with flexible hardware control; it's a more powerful MCU with advanced features, memory, and security. RP2350 has four variants, described in xref:../microcontrollers/microcontroller-chips.adoc#RP2350_variants[RP2350 variants].

=== Key features

Both RP2040 and RP2350 share the following core features:

  • Dual-core processors for parallel processing.
  • On-chip SRAM for real-time workloads.
  • Deterministic bus fabric through a multi-master AHB crossbar that connects the CPUs, DMA, and peripherals to multi-bank SRAM.
  • Built-in USB controller and PHY that allows the microcontroller to act as either a USB device or USB host.
  • Flexible general-purpose I/O (GPIO) that can be configured for digital input/output or assigned to peripheral functions like UART, SPI, I2C, or PWM.
  • Programmable I/O (PIO), a unique feature of Raspberry Pi microcontrollers that provides extended peripheral support.
  • Built-in hardware peripherals for interfaces such as UART, SPI, I2C, PWM, and so on, reducing software overhead and improving efficiency.
  • High performance, low power consumption, and low power leakage as a result of the modern 40 nm manufacturing process for microcontrollers.
  • Low-power modes to support extended-duration operation on battery power.
  • Programming options with C/{cpp} SDK or MicroPython; you can run Python through the MicroPython port and program it using the UF2 bootloader built into ROM for drag-and-drop programming.

=== Feature comparison

The following table provides a comparison between RP2040 and RP2350 microcontrollers. For more details about each microcontroller's features, see the dedicated sections for xref:../microcontrollers/microcontroller-chips.adoc#rp2040[RP2040] and xref:../microcontrollers/microcontroller-chips.adoc#rp2350[RP2350].

.Comparison of Raspberry Pi microcontrollers (RP2040 and RP2350)
[cols="3,3,4",options="header"]
|===
| Feature | RP2040 | RP2350

| Type
| General-purpose MCU
| High-performance MCU

| Processor core
| Dual-core Arm Cortex-M0+
| Dual-core Arm Cortex-M33 (higher performance, TrustZone support) or Hazard3 (RISC-V)

| Clock speed
| Up to 133 MHz
| Up to 150 MHz

| On-chip SRAM
| 264 kB in six independent banks
| 520 kB multi-bank performance

| Flash (non-volatile) memory
| No on-chip flash; support for up to 16 MB of off-chip flash memory through dedicated external (QSPI.XIP) bus.
| Option for on-chip flash depending on variant; support for up to 32 MB of off-chip flash memory through dedicated external (QSPI.XIP) bus. See xref:../microcontrollers/microcontroller-chips.adoc#RP2350_variants[RP2350 variants].

| External volatile working memory (PSRAM)
| Not supported.
| Supported by a QMI memory interface using the QSPI.XIP bus.

| GPIO pins
| 30 GPIO pins, 4 of which can be used as analogue inputs.
| Depending on variant: 30 GPIO pins, 4 of which can be used as analogue inputs; or 48 GPIO pins, 8 of which can be used as analogue inputs. See xref:../microcontrollers/microcontroller-chips.adoc#RP2350_variants[RP2350 variants].

| Programmable Input/Output (PIO)
| Two PIO blocks, each with four state machines (eight in total).
| Three PIO blocks, each with four state machines (twelve in total).

| Peripherals
| See xref:../microcontrollers/microcontroller-chips.adoc#RP2040_features[RP2040 features].
| Expanded set; see xref:../microcontrollers/microcontroller-chips.adoc#RP2350_features[RP2350 features].

| Direct Memory Access (DMA) controller
| 12-channel DMA controller with peripheral pacing and chaining.
| 16-channel DMA with enhanced throughput and flexibility.

| AHB crossbar
| A fully connected, multi-master AHB-Lite crossbar connecting CPUs, DMA, and peripherals to multi-bank SRAM and flash.
| AHB5 crossbar, offering higher-throughput and bandwidth.

| Interpolator
| Dual interpolator blocks for fast integer maths and table lookup.
| Dual interpolator blocks for fast integer maths and table lookup.

| Integer divider
| Separate hardware integer divider accessed through memory-mapped register.
|Not present because the processors support hardware division in the CPU.

| Analogue-to-digital conversion (ADC)
| 4 analogue inputs with internal temperature sensor, 500 kS/s, and 12-bit conversion.
| Depending on variant: 4 or 8 analogue inputs with internal temperature sensor, 500 kS/s, and 12-bit conversion.

| Core regulator architecture
| On-chip, programmable Low-Dropout (LDO) to generate core voltage.
| On-chip buck converter (SMPS) for active operation plus optional low-quiescent-current programmable LDO mode for sleep states.

| On-chip Phase-Locked Loops (PLL)
| Two PLLs for core clock and USB clock generation.
| Two PLLs for core clock and USB clock generation.

| Security features
| None (basic MCU).
| Arm TrustZone; cryptographic accelerators.

| Deployment boards
| Raspberry Pi Pico; third-party RP2040-based boards.
| Raspberry Pi Pico 2; third-party RP2350-based boards.

| Programming
|C/{cpp} SDK, MicroPython
|C/{cpp} SDK, MicroPython
|===

include::microcontroller-chips/rp2040.adoc[]

include::microcontroller-chips/rp2350.adoc[]

== USB identifiers

Many RP2040 and RP2350 chips use a combination of Raspberry Pi USB identifiers (Vendor ID and Product ID). If you make your own, third-party board based on RP2040 or RP2350, you might need a unique USB Product ID (PID) if:

  • You need to provide a custom Windows driver.
  • You want your device to be uniquely identifiable as a separate product.

Raspberry Pi has permission from USB-IF to licence USB PID values for its Vendor ID (0x2E8A) for common silicon components used with RP2040 and RP2350. This means that you can assign unique PIDs under our Vendor ID (0x2E8A). To reserve a USB PID associated with Raspberry Pi's Vendor ID, follow the instructions in the https://github.com/raspberrypi/usb-pid[Raspberry Pi USB PID Git repository].

If you don't need a unique PID, you can still uniquely distinguish devices using any of the following USB text fields: iManufacturer, iProduct, and iSerial.


Documentation Asciidoc Microcontrollers Micropython (`documentation/asciidoc/microcontrollers/micropython.adoc`)

include::micropython/what-is-micropython.adoc[]

include::micropython/drag-and-drop.adoc[]

include::micropython/micropython-documentation.adoc[]

include::micropython/what-board.adoc[]


Documentation Asciidoc Microcontrollers Radio Modules (`documentation/asciidoc/microcontrollers/radio-modules.adoc`)

Raspberry Pi has created two radio modules, only one of which is available to buy as a standalone microcontroller accessory:

  • Raspberry Pi Radio Module 1 (RM1) is built into Raspberry Pi 4 and 5, and Compute Module 4 and 5. It isn't available as a standalone radio module or to purchase separately.
  • Raspberry Pi Radio Module 2 (RM2) is a standalone radio module designed to add wireless connectivity to Raspberry Pi xref:../microcontrollers/microcontroller-chips.adoc[microcontrollers]. For added flexibility, it also provides GPIO expansion options.

include::radio-modules/rm2.adoc[]


Documentation Asciidoc Security Operational Security (`documentation/asciidoc/security/operational-security.adoc`)

Operational security (OpSec) is the practice of protecting your device by reducing opportunities for attackers to gain access or exploit vulnerabilities. This page covers practical ways to improve the operational security of your Raspberry Pi.

== Secure user accounts

To prevent unauthorised access and minimise the impact of accidental or malicious changes to the system, you can protect your Raspberry Pi with the following practices:

  • Require a password from start up.
  • Manage user permissions.
  • Require a password for superuser (sudo) commands (enabled by default during setup).

For instructions, and for more information about user account management, see xref:../computers/configuration.adoc#users[User access and management].

== Update Raspberry Pi OS

To ensure your system has the latest security features, we recommend that you keep your software up to date. For more information, see xref:../computers/os.adoc#update-software[Update your current Raspberry Pi software] in the Raspberry Pi OS page.

Only the most recent major release of Raspberry Pi OS is updated with all the latest security fixes. We therefore recommend that you also upgrade to the most recent major release when it becomes available (for example, from Bookworm to Trixie). For instructions on upgrading your OS, see xref:../computers/os.adoc#upgrade[Upgrade to a new major version].

Upgrading to the most recent major release is different from updating your Raspberry Pi OS:

  • Updating installs the latest packages and security fixes within your current release without changing to a new major version.
  • Upgrading moves your Raspberry Pi to a new major Raspberry Pi OS release.

== Use a firewall

A firewall helps protect your Raspberry Pi by controlling which network connections are allowed or blocked. For most users, we recommend using Uncomplicated Firewall (UFW) to configure firewall rules, restrict access to services, and protect internet-facing systems.

For instructions on installing, configuring, and managing UFW, see xref:../security/ufw.adoc[Firewalls using UFW].

== Improve SSH security

SSH is a common way to remotely access a Raspberry Pi. By default, SSH requires a username and password. To improve SSH security, use key-based authentication. For more information, see xref:../computers/remote-access.adoc#configure-ssh-without-a-password[Configure SSH without a password].

You can also allow or deny specific users by altering the sshd configuration. For more information, see xref:../computers/remote-access.adoc#restrict-which-users-can-connect[Restrict which users can connect].

== Block suspicious activity with Fail2Ban

When using Raspberry Pi as a server, you must create deliberate holes in your firewall to allow server traffic. https://github.com/fail2ban/fail2ban[Fail2Ban] can help secure your server. Fail2Ban examines log files and checks for suspicious activity, like multiple brute-force login attempts. This means that you don't have to manually check log files for intrusion attempts and then update the firewall (through iptables) to prevent them.

To install Fail2Ban, run the following command:

[source,console]

$ sudo apt install fail2ban

On installation, Fail2Ban creates /etc/fail2ban/jail.conf. To enable Fail2Ban, copy jail.conf to jail.local:

[source,console]

$ sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

This configuration file contains a set of default options, together with options for checking specific services for abnormalities. To examine the rules used for ssh, open jail.local in an editor:

[source,console]

$ sudo nano /etc/fail2ban/jail.local

If it doesn't already exist, create the [ssh] section, then add the following lines to the section:

[source,ini]

[ssh] enabled true port ssh filter sshd backend systemd maxretry 6

This enables Fail2Ban checks for suspicious ssh activity, including system log checks, and allows six retries before blocking activity.

The [default] section in this file defines the default banning action, iptables-multiport, which runs the /etc/fail2ban/action.d/iptables-multiport.conf file when the detection threshold is reached:

[source,ini]

Default banning action (for example, iptables, iptables-new,

iptables-multiport, shorewall, etc) It is used to define

action_* variables. Can be overridden globally or per

section within jail.local file

banaction iptables-multiport

Multiport bans all access on all ports. The action.d folder contains alternative action configuration files you can use to customise your server's response to suspicious activity.

For example, to permanently ban an IP address after three failed attempts, change the maxretry value in the [ssh] section to 3 and set the bantime to a negative number:

[source,ini]

[ssh] enabled true port ssh filter sshd backend systemd maxretry 3 bantime -1


Documentation Asciidoc Security Security Architecture (`documentation/asciidoc/security/security-architecture.adoc`)

This page provides a high-level conceptual architecture overview of how Raspberry Pi devices protect themselves during boot and storage access. It summarises:

  • When configured, the chain of trust used in Raspberry Pi's secure (verified) boot process.
  • How disk encryption integrates into the boot process, when enabled along with secure boot.
  • The software components available in Raspberry Pi OS that offer security functionality.

NOTE: To implement secure boot and encryption, we recommend using our Secure Boot Provisioner, which can configure and deploy secure boot and disk encryption on multiple devices. For more information and instructions, see xref:../security/secure-boot-provisioner.adoc[Secure Boot Provisioner].

== Secure boot chain of trust

Like all computers, when a Raspberry Pi starts up, it goes through a boot process: it first runs low-level firmware, then loads the operating system (OS).

Secure boot ensures that only authenticated software runs during this process by establishing a chain of trust. Each stage (link) in the chain cryptographically verifies the next stage before it runs. This ensures that only code signed by a trusted source can run during startup.

We recommend provisioning your devices with secure boot using Raspberry Pi Secure Boot Provisioner, with optional disk encryption enabled. For information and instructions, see xref:../security/secure-boot-provisioner.adoc[Secure Boot Provisioner].

=== Cryptographic components

The secure boot chain starts in immutable hardware and extends to customer software. It consists of the following cryptographic components:

  • Boot ROM public key. The boot ROM is the immutable hardware root of trust that contains a Raspberry Pi public key burned into silicon. This key is used to authenticate Raspberry Pi-signed firmware.
  • Customer-generated RSA key pair. Before provisioning your Raspberry Pi devices, you, the customer, generate your own RSA public-private key pair. The private key signs your OS boot image. Using Raspberry Pi Secure Boot Provisioner, you define which key is trusted for boot by storing the identity (a hash) of the public key in the device OTP.
  • Device-unique disk secret. Secure Boot Provisioner generates a device-unique secret, used to unlock the encrypted root filesystem at boot. The key is stored in OTP and protected by software mechanisms.

[[bootflow]]
=== Bootflow timeline

The secure boot process, configured with the Raspberry Pi xref:../security/secure-boot-provisioner.adoc[Secure Boot Provisioner], establishes a chain of trust that begins in immutable hardware and extends through to the OS. The following sections summarise each stage of this process and how disk encryption integrates into the boot flow when it's enabled.

If all verification steps succeed, the kernel starts to run, and then mounts the root filesystem, decrypting it first if <<disk-encryption, disk encryption>> is also enabled with the Secure Boot Provisioner.

If any verification step fails, the chain of trust is broken and the EEPROM bootloader doesn't continue with the untrusted software; instead the EEPROM bootloader proceeds to your next configured boot method, for example, another partition, image, or recovery mode.

[[first-stage]]
==== First stage: boot ROM root of trust

The first stage is the boot ROM embedded in each Raspberry Pi device's SoC. Because it's permanently burned into silicon, it can't be modified after manufacturing and is trusted by design; it therefore forms the hardware root of trust for the secure boot process.

The boot ROM reads a hash of your RSA 2048-bit public key stored in One-Time Programmable (OTP) memory. On Raspberry Pi devices using the BCM2712 SoC, this key pair is also used to sign the EEPROM bootloader, described in <>. This extends the BCM2711 SoC checks by also requiring a customer key signature to authenticate the EEPROM bootloader.

[[second-stage]]
==== Second stage: EEPROM bootloader verification

The second stage is the EEPROM bootloader, which is stored in the Raspberry Pi device's SPI flash EEPROM and updated by Raspberry Pi Secure Boot Provisioner. The digital signature of this bootloader is verified using Raspberry Pi's public key embedded in the boot ROM. The EEPROM bootloader then checks the customer's public key against the hash stored in OTP, ensuring that only an authorised customer key is trusted for subsequent stages.

[[third-stage]]
==== Third stage: kernel and OS

The third stage is kernel and OS verification and loading. The EEPROM bootloader loads a boot image (boot.img) from local storage or over the network, and verifies its signature (boot.sig) using the customer public key. The verified boot image typically contains the kernel, initramfs, device tree, and, on devices with the BCM2711 SoCs, the GPU firmware (start.elf). If verification succeeds, the bootloader runs the kernel.

The kernel then initialises the hardware and mounts the root filesystem. If disk encryption is enabled, the boot process continues with the process summarised in <>. Otherwise, the kernel mounts the root filesystem and normal OS startup continues.

[[fourth-stage]]
==== Fourth stage: encrypted root filesystem unlock

The fourth stage occurs when disk encryption is enabled as part of Secure Boot Provisioner configuration.

The initramfs retrieves the device-unique secret stored in OTP and uses it to decrypt the root filesystem before mounting it, after which the normal OS startup process continues.

For more detailed information about disk encryption and how the encrypted root filesystem is unlocked, see <>.

[[disk-encryption]]
== Disk encryption boot flow

Disk encryption on Raspberry Pi devices protects the root filesystem by encrypting it with LUKS and binding the disk-specific passphrase to the device using OTP, described in <>.

By default, Raspberry Pi OS doesn't support encrypted root file systems; if you want disk encryption, you must either build your own encrypted storage or use the Raspberry Pi Secure Boot Provisioner tool to enable encryption during provisioning. For information about this tool, see xref:../security/secure-boot-provisioner.adoc[Secure Boot Provisioner].

For operating system images created with rpi-image-gen, the root filesystem and any number of additional partitions can be encrypted. For images created with pi-gen, only the root filesystem can be encrypted. Regardless of the image generation method used, a trusted but unencrypted pre-boot authentication environment is required to allow the device to start and unlock the encrypted storage. This environment includes the Raspberry Pi firmware, Linux kernel, Device Tree files, and a minimal user space, and is authenticated through digital signatures using a customer signing key rather than through encryption.

For Raspberry Pi devices provisioned with disk encryption, the boot process continues from <> in the bootflow timeline and so is essentially the fourth step in establishing a full chain of trust. The bootloader loads the (unencrypted) Linux kernel and initramfs (a temporary root filesystem) from the pre-boot authentication environment into RAM. Because the real root filesystem is still encrypted and can't be accessed yet, the kernel initially runs from initramfs. Early boot scripts in initramfs invoke rpi-fw-crypto to derive the disk-specific passphrase, unlock the LUKS volume, and mount the real root file system. The kernel then switches to this unlocked root filesystem and normal Linux boot continues.

The initramfs must include the kernel modules that implement the encryption ciphers you choose to use. To optimise performance, default cipher recommendations vary depending on the Raspberry Pi SoC or SiP, shown in the following table.

.Default LUKS encryption ciphers by Raspberry Pi SoC
[cols="1,1,3", options="header"]
|===
|Chip |LUKS encryption |Notes

|BCM2712 devices
|AES (aes-xts-plain64)
|The BCM2712 SoC has hardware acceleration for AES encryption, which means there is faster encryption, lower CPU load, and greater storage throughput on devices with the BCM2712 chip.

|BCM2711 devices
|AES (aes-xts-plain64)
|The BCM2711 SoC can also handle AES encryption efficiently.

|BCM2837, BCM2837B0, and RP3A0 devices
|Adiantum (ChaCha20)
|Adiantum is recommended for better performance on older Raspberry Pi models that use the BCM2837 or BCM2837B0 SoCs, or the RP3A0 SiP.
|===

[[software-components]]
== Software components in Raspberry Pi OS

Raspberry Pi OS, a derivative of Debian, offers a range of free and open source security components that you can use to secure your device. Standard Debian packages include:

  • OpenSSL, a secure sockets and cryptography library.
  • PAM, the Pluggable Authentication Module system.
  • LUKS, the Linux Unified Key Setup system for configuring and using storage encryption.
  • AppArmor, a Mandatory Access Control system for constraining programs and users.
  • xref:../security/operational-security.adoc#block-suspicious-activity-with-fail2ban[Fail2Ban], an optional package for monitoring system logs and banning IP addresses that exhibit malicious activity.
  • xref:../security/ufw.adoc[UFW], the Uncomplicated FireWall, for configuring a network firewall.

In addition to the array of components offered from the Debian project, Raspberry Pi OS also offers rpi-fw-crypto, which is a library and program for using the VideoCore co-processor to encrypt and sign data with a device-unique secret.


Documentation Asciidoc Security Security (`documentation/asciidoc/security/security.adoc`)

This page provides an overview with links to more detailed information about securing your Raspberry Pi device.

== Security architecture

Raspberry Pi's security architecture ensures that only authenticated boot code runs on provisioned Raspberry Pi devices, disk encryption keys are protected, and a chain of trust verifies every stage of the boot process.

For more information, see xref:../security/security-architecture.adoc[Security architecture].

== Secure Boot Provisioner

Raspberry Pi have created a provisioning tool for simplifying the process of:

  • Setting up secure (verified) boot to establish a hardware chain of trust that ensures that only authenticated code runs during the device startup sequence.
  • Setting up disk encryption to protect data stored on persistent media, such as microSD cards or USB drives.
  • Provisioning multiple Raspberry Pi devices with a streamlined configuration and deployment process.

For more information and instructions, see xref:../security/secure-boot-provisioner.adoc[Secure Boot Provisioner].

== Operational security

You can configure your Raspberry Pi device to prevent unauthorised access and improve day-to-day security hygiene with:

  • User and access management, including authentication, user accounts, groups, and permissions.
  • Regular operating system and software updates.
  • Secure remote access with SSH hardening.
  • Protection against suspicious activity and brute force attacks.

For more information and instructions, see xref:../security/operational-security.adoc[Operational security].

== Firewalls using UFW

Configuring a packet-filtering firewall using Uncomplicated Firewall (UFW) on a Raspberry Pi device helps to harden the system. It can be used to limit network access to only essential services and mitigate external threats by blocking unwanted or malicious connections.

For more information and instructions, see xref:../security/ufw.adoc[Firewalls using UFW].

== Frontline security disclosure

Raspberry Pi follows a structured vulnerability reporting and management process. As part of this process, we track and incorporate security updates from Debian on a regular schedule.

Raspberry Pi lists official security vulnerability disclosures on our website. For more information, see https://www.raspberrypi.com/security#security-advisories[Security Advisories] and https://raspberrypi.github.io/cve-list/[Raspberry Pi OS — CVE reports]

To report security issues on Raspberry Pi, email mailto:[email protected][[email protected]]. For more information, see https://www.raspberrypi.com/security/#reporting-a-vulnerability[Reporting a vulnerability].

== Software Bill of Materials

A Software Bill of Materials (SBOM) lists all components in a software application and includes metadata for each component, such as its name, version, supplier, license, and unique identifier. This information is provided in an open-standard, machine-readable format.

We provide an SBOM for each edition of Raspberry Pi OS. You can download the SBOM file from the https://www.raspberrypi.com/software/operating-systems/[Raspberry Pi OS downloads page].


Documentation Asciidoc Security Ufw (`documentation/asciidoc/security/ufw.adoc`)

A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on a defined set of security rules. This page introduces Uncomplicated Firewall (UFW), a firewall tool that simplifies firewall configuration on Linux systems using https://www.netfilter.org/projects/iptables/index.html[`iptables`].

There are also some graphical user interface (GUI) frontends available for UFW, such as GUFW, but ufw commands are typically run on the command line. This page provides an overview of, and basic instructions for, the UFW command-line interface.

== Uncomplicated Firewall (UFW)

Network traffic is organised by port numbers, which are numerical labels used to direct data to specific applications. Firewalls control traffic by opening and closing particular ports to allow or block certain types of communication.

On Linux systems, network traffic is filtered through the kernel's firewall subsystem, called netfilter. Netfilter implements packet filtering; it blocks or allows data packets to pass through your system based on things like their source IP address, destination IP address, port number, protocol, and direction.

System administrators configure netfilter using https://www.netfilter.org/projects/iptables/index.html[`iptables`], which is the traditional command-line tool for defining packet-filtering rules. However, iptables can be complex. https://www.linux.com/learn/introduction-uncomplicated-firewall-ufw[UFW (Uncomplicated Firewall)], the firewall tool used by Ubuntu, simplifies firewall configuration and management. It acts as a wrapper for iptables, allowing system administrators to set firewall rules without dealing with the complexity of raw iptables commands.

== UFW commands

UFW is a command-line program used to define firewall access rules. The typical syntax for ufw commands is: sudo ufw [--dry-run] <command> [rule].

  • All ufw commands require superuser privileges, and so must be preceded with sudo.
  • Optionally, you can add --dry-run to simulate the ufw command without making actual changes.
  • The <command> is the main action that you want to perform, such as allow.
  • Depending on the command, you can optionally specify a rule to apply to the command, such as allow 22.

For example, sudo ufw --dry-run allow 22 shows you the predicted outcome of allowing traffic on port 22, including the entire set of rules if the change were made.

== Install and enable UFW

To use UFW, you must first install it on your Raspberry Pi. After installation, UFW is present but disabled, meaning that it doesn't block any traffic yet. This allows you to configure default access rules without locking yourself out. This is especially important if you're connected to your Raspberry Pi device over SSH (or any other remote method); to avoid being locked out, you must allow remote access before enabling UFW.

If you're connected over SSH, the recommended flow of actions is as follows:

[cols="1,7,5", options="header"]
|===
|Step |Description |Command

|1
|Update your package list.
|sudo apt-get update

|2
|Install UFW. Before UFW is enabled, the output says that UFW is inactive.
|sudo apt install ufw

|3
|Verify the installation by checking the status. For information about this command, see <>.
|sudo ufw status

|4
|Optionally (but recommended), configure default policies, such as denying all incoming traffic. Defaults apply globally.
|sudo ufw default deny incoming

|5
|To maintain remote access, allow SSH (before enabling UFW), either by specifying the service name (ssh) or the default port (22/tcp).
|sudo ufw allow ssh +
OR +
sudo ufw allow 22/tcp

|6
|Optionally, if you're running a web server, allow HTTP and HTTPS traffic, either by specifying the service names (http and https) or their default ports (80/tcp and 443/tcp, respectively).
|sudo ufw allow http +
sudo ufw allow https +
OR +
sudo ufw allow 80/tcp +
sudo ufw allow 443/tcp

|7
|Enable UFW to activate the firewall and configure it to start up on boot.
|sudo ufw enable

|8
|Verify the status of the firewall and review the active rules. For information about this command, see <>.
|sudo ufw status verbose
|===

You can disable UFW at any time, which stops it from starting up on boot. Use the following command to disable the UFW firewall:

[source,console]

$ sudo ufw disable

== Use allow and deny rules

This section lists the basic commands for allowing and denying traffic through specified service names and ports. The general ufw syntax for allow and deny commands are as follows:

  • Allow access to a particular port or service: sudo ufw allow [rule]
  • Deny access to a particular port or service: sudo ufw deny [rule]

The following table provides specific examples.

[cols="1,3", options="header"]
|===
|Command |Description

|sudo ufw allow 22
|Allows access to port 22 through the firewall. This opens the port for all protocols (TCP and UDP).

|sudo ufw allow 22/tcp
|Allows TCP only on port 22.

|sudo ufw allow ssh
|Allows the SSH service without specifying the port (SSH is usually port 22/tcp).

|sudo ufw deny 22
|Denies access to port 22 through the firewall. This closes the port for all protocols (TCP and UDP).

|sudo ufw deny 22/tcp
|Denies TCP only on port 22.

|sudo ufw deny ssh
|Denies the SSH service without specifying the port (SSH is usually port 22/tcp).
|===

== Advanced UFW rules

UFW can do more than basic allow and deny rules. It can also:

  • <> from a specific port.
  • <> (incoming and outgoing).
  • <> to help protect against brute-force or DDoS attacks.
  • <> to apply rules specifically to wired or wireless networks.

For more information about these options, run the following command: man ufw. This displays the UFW manual page in your terminal, which includes documentation on UFW syntax, options, rule formatting, and examples.

[[allow-block-ip-addresses]]
=== Allow or block a specific IP address
You can allow or deny access from a specific IP address to a specific port. This is useful if you want to block suspicious hosts or allow trusted hosts only. For example, the following command denies access to port 30 from IP address 192.168.2.1

[source,console]

$ sudo ufw deny from 192.168.2.1 to any port 30

[[traffic-direction]]
=== Specify traffic direction
To control how your system sends or receives network traffic, perhaps to block threats to your system (incoming) or protect system resources (outgoing), you can prevent traffic from coming in one or both directions. Specifically, you can add out (for outgoing traffic) or in (for incoming traffic) to one of the following commands:

  • allow, which allows the traffic to flow in the specified direction.
  • deny, which silently drops the traffic flowing in the specified direction.
  • reject, which actively refuses the traffic flowing in the specified direction.

For example, the following command prevents all outgoing traffic on the SMTP port (usually port 25/TCP):

[source,console]

$ sudo ufw reject out smtp

[[rate-limit]]
=== Rate limit connection attempts
To protect against brute-force and DDoS attacks, the limit command temporarily blocks any IP address that attempts to make too many connections in a short period of time (approximately 6 or more times within 30 seconds). For example, the following command watches how often an IP address attempts to open a new connection to SSH (usually port 22/tcp) and applies the rate limit.

[source,console]

$ sudo ufw limit ssh/tcp

[[specify-network-interfaces]]
=== Specify network interfaces
You can set firewall rules to apply only to a specific network connection (eth0 for wired networks or wlan0 for Wi-Fi). For example, the following command allows incoming TCP traffic on port 80 only on the eth0 network interface:

[source,console]

$ sudo ufw allow in on eth0 to any port 80 proto tcp

[[rule-management]]
== Rule management
UFW processes rules in order, so earlier rules take precedence over later ones. The following table lists useful commands to help you inspect your current firewall configuration and remove rules when necessary.

[cols="1,3", options="header"]
|===
|Command |Description

|sudo ufw status
|Displays whether UFW is active and lists all current settings for the firewall (which ports and services are allowed and denied).

|sudo ufw status verbose
|Displays additional details, such as default policies and logging settings.

|sudo ufw show added
|Displays only user-added rules (excluding internal and system rules). This is useful if you want to review changes or compare configurations across systems.

|sudo ufw status numbered
|Displays rules with their assigned index number. This is useful if you want to delete a specific rule.

|sudo ufw delete <number>
|Deletes the rule that you specify based on its assigned index number. UFW then renumbers the remaining entries. You can rerun sudo ufw status numbered to confirm the rule was removed.
|===


Documentation Asciidoc Services Connect (`documentation/asciidoc/services/connect.adoc`)

include::connect/introduction.adoc[]

include::connect/install.adoc[]

include::connect/access.adoc[]

include::connect/remote-update.adoc[]

include::connect/connect-otamaker.adoc[]

include::connect/ab-boot-update.adoc[]

include::connect/manage.adoc[]

include::connect/troubleshooting.adoc[]

include::connect/security.adoc[]


Documentation Asciidoc Accessories Ai Camera About (`documentation/asciidoc/accessories/ai-camera/about.adoc`)

[[ai-camera]]
== About

The Raspberry Pi AI Camera uses the Sony IMX500 imaging sensor to provide low-latency, high-performance AI capabilities to any camera application. Tight integration with xref:../computers/camera_software.adoc[the Raspberry Pi camera software stack] allows users to deploy their own neural network models with minimal effort.

image::images/ai-camera.jpg[The Raspberry Pi AI Camera]

This section demonstrates how to run either a pre-packaged or custom neural network model on the camera. Additionally, this section includes the steps required to interpret inference data generated by neural networks running on the IMX500 in https://github.com/raspberrypi/rpicam-apps[`rpicam-apps`] and https://github.com/raspberrypi/picamera2[Picamera2].


Documentation Asciidoc Accessories Ai Camera Details (`documentation/asciidoc/accessories/ai-camera/details.adoc`)

== Under the hood

=== Overview

The Raspberry Pi AI Camera works differently from traditional AI-based camera image processing systems, as shown in the diagram below:

image::images/imx500-comparison.svg[Traditional versus IMX500 AI camera systems]

The left side demonstrates the architecture of a traditional AI camera system. In such a system, the camera delivers images to the Raspberry Pi. The Raspberry Pi processes the images and then performs AI inference. Traditional systems can use external AI accelerators (as shown) or rely exclusively on the CPU.

The right side demonstrates the architecture of a system that uses IMX500. The camera module contains a small Image Signal Processor (ISP) which turns the raw camera image data into an input tensor. The camera module sends this tensor directly into the AI accelerator within the camera, which produces output tensors that contain the inferencing results. The AI accelerator sends these tensors to the Raspberry Pi. There is no need for an external accelerator, nor for the Raspberry Pi to run neural network software on the CPU.

To fully understand this system, familiarise yourself with the following concepts:

Input Tensor:: The part of the sensor image passed to the AI engine for inferencing. Produced by a small on-board ISP which also crops and scales the camera image to the dimensions expected by the neural network that has been loaded. The input tensor is not normally made available to applications, though it is possible to access it for debugging purposes.

Region of Interest (ROI):: Specifies exactly which part of the sensor image is cropped out before being rescaled to the size demanded by the neural network. Can be queried and set by an application. The units used are always pixels in the full resolution sensor output. The default ROI setting uses the full image received from the sensor, cropping no data.

Output Tensors:: The results of inferencing performed by the neural network. The precise number and shape of the outputs depend on the neural network. Application code must understand how to handle the tensors.

=== System architecture

The diagram below shows the various camera software components (in green) used during our imaging/inference use case with the Raspberry Pi AI Camera module hardware (in red):

image::images/imx500-block-diagram.svg[IMX500 block diagram]

At startup, the IMX500 sensor module loads firmware to run a particular neural network model. During streaming, the IMX500 generates both an image stream and an inference stream. This inference stream holds the inputs and outputs of the neural network model, also known as input/output tensors.

=== Device drivers

At the lowest level, the the IMX500 sensor kernel driver configures the camera module over the I2C bus. The CSI2 driver (CFE on Raspberry Pi 5, Unicam on all other Raspberry Pi platforms) sets up the receiver to write the image data stream into a frame buffer, together with the embedded data and inference data streams into another buffer in memory.

The firmware files also transfer over the I2C bus wires. On most devices, this uses the standard I2C protocol, but Raspberry Pi 5 uses a custom high speed protocol. The RP2040 SPI driver in the kernel handles firmware file transfer, since the transfer uses the RP2040 microcontroller. The microcontroller bridges the I2C transfers from the kernel to the IMX500 through an SPI bus. Additionally, the RP2040 caches firmware files in on-board storage. This avoids the need to transfer entire firmware blobs over the I2C bus, significantly speeding up firmware loading for firmware you've already used.

=== libcamera

After libcamera dequeues the image and inference data buffers from the kernel, the IMX500 specific cam-helper library (part of the Raspberry Pi IPA within libcamera) parses the inference buffer to access the input/output tensors. These tensors are packaged as Raspberry Pi vendor-specific https://docs.libcamera.org/master/public-api/classlibcamera_1_1ControlList.html[`libcamera` controls]. libcamera returns the following controls:

[%header,cols="a,a"]
|===
| Control
| Description

| CnnOutputTensor
| Floating point array storing the output tensors.

| CnnInputTensor
| Floating point array storing the input tensor.

| CnnOutputTensorInfo
| Network specific parameters describing the output tensors' structure:

[source,c]

struct OutputTensorInfo {
uint32_t tensorDataNum;
uint32_t numDimensions;
uint16_t size[MaxNumDimensions];
};

struct CnnOutputTensorInfo {
char networkName[NetworkNameLen];
uint32_t numTensors;
OutputTensorInfo info[MaxNumTensors];

};

| CnnInputTensorInfo
| Network specific parameters describing the input tensor's structure:

[source,c]

struct CnnInputTensorInfo {
char networkName[NetworkNameLen];
uint32_t width;
uint32_t height;
uint32_t numChannels;

};

|===

=== rpicam-apps

rpicam-apps provides an IMX500 post-processing stage base class that implements helpers for IMX500 post-processing stages: https://github.com/raspberrypi/rpicam-apps/blob/main/post_processing_stages/imx500/imx500_post_processing_stage.hpp[`IMX500PostProcessingStage`]. Use this base class to derive a new post-processing stage for any neural network model running on the IMX500. For an example, see https://github.com/raspberrypi/rpicam-apps/blob/main/post_processing_stages/imx500/imx500_object_detection.cpp[`imx500_object_detection.cpp`]:

[source,cpp]

class ObjectDetection : public IMX500PostProcessingStage
{
public:
ObjectDetection(RPiCamApp *app) : IMX500PostProcessingStage(app) {}

text
char const *Name() const override;

void Read(boost::property_tree::ptree const &params) override;

void Configure() override;

bool Process(CompletedRequestPtr &completed_request) override;

};

For every frame received by the application, the Process() function is called (ObjectDetection::Process() in the above case). In this function, you can extract the output tensor for further processing or analysis:

[source,cpp]

auto output = completed_request->metadata.get(controls::rpi::CnnOutputTensor);
if (!output)
{
LOG_ERROR("No output tensor found in metadata!");
return false;
}

std::vector output_tensor(output->data(), output->data() + output->size());

When completed, the final results can either be visualised or saved in metadata and consumed by either another downstream stage, or the top level application itself. In the object inference case:

[source,cpp]

if (objects.size()) completed_request->post_process_metadata.Set("object_detect.results", objects);

The object_detect_draw_cv post-processing stage running downstream fetches these results from the metadata and draws the bounding boxes onto the image in the ObjectDetectDrawCvStage::Process() function:

[source,cpp]

std::vector detections; completed_request->post_process_metadata.Get("object_detect.results", detections);

The following table contains a full list of helper functions provided by IMX500PostProcessingStage:

[%header,cols="a,a"]
|===
| Function
| Description

| Read()
| Typically called from <Derived Class>::Read(), this function reads the config parameters for input tensor parsing and saving.

This function also reads the neural network model file string ("network_file") and sets up the firmware to be loaded on camera open.

| Process()
| Typically called from <Derived Class>::Process() this function processes and saves the input tensor to a file if required by the JSON config file.

| SetInferenceRoiAbs()
| Sets an absolute region of interest (ROI) crop rectangle on the sensor image to use for inferencing on the IMX500.

| SetInferenceRoiAuto()
| Automatically calculates region of interest (ROI) crop rectangle on the sensor image to preserve the input tensor aspect ratio for a given neural network.

| ShowFwProgressBar()
| Displays a progress bar on the console showing the progress of the neural network firmware upload to the IMX500.

| ConvertInferenceCoordinates()
| Converts from the input tensor coordinate space to the final ISP output image space.

There are a number of scaling/cropping/translation operations occurring from the original sensor image to the fully processed ISP output image. This function converts coordinates provided by the output tensor to the equivalent coordinates after performing these operations.

|===

=== Picamera2

IMX500 integration in Picamera2 is very similar to what is available in rpicam-apps. Picamera2 has an IMX500 helper class that provides the same functionality as the rpicam-apps IMX500PostProcessingStage base class. This can be imported to any Python script with:

[source,python]

from picamera2.devices.imx500 import IMX500

This must be called before instantiation of Picamera2

imx500 = IMX500(model_file)

To retrieve the output tensors, fetch them from the controls. You can then apply additional processing in your Python script.

For example, in an object inference use case such as https://github.com/raspberrypi/picamera2-examples/tree/main/examples/imx500/imx500_object_detection_demo.py[imx500_object_detection_demo.py], the object bounding boxes and confidence values are extracted in parse_detections() and draw the boxes on the image in draw_detections():

[source,python]

class Detection:
def init(self, coords, category, conf, metadata):
"""Create a Detection object, recording the bounding box, category and confidence."""
self.category = category
self.conf = conf
obj_scaled = imx500.convert_inference_coords(coords, metadata, picam2)
self.box = (obj_scaled.x, obj_scaled.y, obj_scaled.width, obj_scaled.height)

def draw_detections(request, detections, stream="main"):
"""Draw the detections for this request onto the ISP output."""
labels = get_labels()
with MappedArray(request, stream) as m:
for detection in detections:
x, y, w, h = detection.box
label = f"{labels[int(detection.category)]} ({detection.conf:.2f})"
cv2.putText(m.array, label, (x + 5, y + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
cv2.rectangle(m.array, (x, y), (x + w, y + h), (0, 0, 255, 0))
if args.preserve_aspect_ratio:
b = imx500.get_roi_scaled(request)
cv2.putText(m.array, "ROI", (b.x + 5, b.y + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
cv2.rectangle(m.array, (b.x, b.y), (b.x + b.width, b.y + b.height), (255, 0, 0, 0))

def parse_detections(request, stream='main'):
"""Parse the output tensor into a number of detected objects, scaled to the ISP output."""
outputs = imx500.get_outputs(request.get_metadata())
boxes, scores, classes = outputs[0][0], outputs[1][0], outputs[2][0]
detections = [ Detection(box, category, score, metadata)
for box, score, category in zip(boxes, scores, classes) if score > threshold]
draw_detections(request, detections, stream)


Unlike the rpicam-apps example, this example applies no additional hysteresis or temporal filtering.

The IMX500 class in Picamera2 provides the following helper functions:

[%header,cols="a,a"]
|===
| Function
| Description

| IMX500.get_full_sensor_resolution()
| Return the full sensor resolution of the IMX500.

| IMX500.config
| Returns a dictionary of the neural network configuration.

| IMX500.convert_inference_coords(coords, metadata, picamera2)
| Converts the coordinates coords from the input tensor coordinate space to the final ISP output image space. Must be passed Picamera2's image metadata for the image, and the Picamera2 object.

There are a number of scaling/cropping/translation operations occurring from the original sensor image to the fully processed ISP output image. This function converts coordinates provided by the output tensor to the equivalent coordinates after performing these operations.

| IMX500.show_network_fw_progress_bar()
| Displays a progress bar on the console showing the progress of the neural network firmware upload to the IMX500.

| IMX500.get_roi_scaled(request)
| Returns the region of interest (ROI) in the ISP output image coordinate space.

| IMX500.get_isp_output_size(picamera2)
| Returns the ISP output image size.

| IMX5000.get_input_size()
| Returns the input tensor size based on the neural network model used.

| IMX500.get_outputs(metadata)
| Returns the output tensors from the Picamera2 image metadata.

| IMX500.get_output_shapes(metadata)
| Returns the shape of the output tensors from the Picamera2 image metadata for the neural network model used.

| IMX500.set_inference_roi_abs(rectangle)
| Sets the region of interest (ROI) crop rectangle, which determines which part of the sensor image is converted to the input tensor that is used for inferencing on the IMX500. Specify the region of interest in units of pixels at the full sensor resolution, as a (x_offset, y_offset, width, height) tuple.

| IMX500.set_inference_aspect_ratio(aspect_ratio)
| Automatically calculates region of interest (ROI) crop rectangle on the sensor image to preserve the given aspect ratio. To make the ROI aspect ratio exactly match the input tensor for this network, use imx500.set_inference_aspect_ratio(imx500.get_input_size()).

| IMX500.get_kpi_info(metadata)
| Returns the frame-level performance indicators logged by the IMX500 for the given image metadata.

|===


Documentation Asciidoc Accessories Ai Camera Getting Started (`documentation/asciidoc/accessories/ai-camera/getting-started.adoc`)

== Getting started

The instructions below describe how to run the pre-packaged MobileNet SSD and PoseNet neural network models on the Raspberry Pi AI Camera.

=== Hardware setup

Attach the camera to your Raspberry Pi 5 board following the instructions at xref:../accessories/camera.adoc#install-a-raspberry-pi-camera[Install a Raspberry Pi Camera].

=== Prerequisites

These instructions assume you are using the AI Camera attached to either a Raspberry Pi 4 Model B or Raspberry Pi 5 board. With minor changes, you can follow these instructions on other Raspberry Pi models with a camera connector, including the Raspberry Pi Zero 2 W and Raspberry Pi 3 Model B+.

First, ensure that your Raspberry Pi runs the latest software. Run the following command to update:

[source,console]

$ sudo apt update && sudo apt full-upgrade

=== Install the IMX500 firmware

The AI camera must download runtime firmware onto the IMX500 sensor during startup. To install these firmware files onto your Raspberry Pi, run the following command:

[source,console]

$ sudo apt install imx500-all

This command:

  • installs the /lib/firmware/imx500_loader.fpk and /lib/firmware/imx500_firmware.fpk firmware files required to operate the IMX500 sensor
  • places a number of neural network model firmware files in /usr/share/imx500-models/
  • installs the IMX500 post-processing software stages in rpicam-apps
  • installs the Sony network model packaging tools

NOTE: The IMX500 kernel device driver loads all the firmware files when the camera starts. This might take several minutes if the neural network model firmware has not been previously cached. The demos below display a progress bar on the console to indicate firmware loading progress.

=== Reboot

Now that you've installed the prerequisites, restart your Raspberry Pi:

[source,console]

$ sudo reboot

== Run example applications

After all the system packages are updated and firmware files installed, we can start running some example applications. As mentioned earlier, the Raspberry Pi AI Camera integrates fully with libcamera, rpicam-apps, and Picamera2.

=== rpicam-apps

The xref:../computers/camera_software.adoc#rpicam-apps[rpicam-apps camera applications] include IMX500 object detection and pose estimation stages that can be run in the post-processing pipeline. For more information about the post-processing pipeline, see xref:../computers/camera_software.adoc#post-process-file[the post-processing documentation].

The examples on this page use post-processing JSON files located in /usr/share/rpi-camera-assets/.

==== Object detection

The MobileNet SSD neural network performs basic object detection, providing bounding boxes and confidence values for each object found. imx500_mobilenet_ssd.json contains the configuration parameters for the IMX500 object detection post-processing stage using the MobileNet SSD neural network.

imx500_mobilenet_ssd.json declares a post-processing pipeline that contains two stages:

. imx500_object_detection, which picks out bounding boxes and confidence values generated by the neural network in the output tensor
. object_detect_draw_cv, which draws bounding boxes and labels on the image

The MobileNet SSD tensor requires no significant post-processing on your Raspberry Pi to generate the final output of bounding boxes. All object detection runs directly on the AI Camera.

The following command runs rpicam-hello with object detection post-processing:

[source,console]

$ rpicam-hello -t 0s --post-process-file /usr/share/rpi-camera-assets/imx500_mobilenet_ssd.json --viewfinder-width 1920 --viewfinder-height 1080 --framerate 30

After running the command, you see a viewfinder that overlays bounding boxes on objects recognised by the neural network:

image::images/imx500-mobilenet.jpg[IMX500 MobileNet]

To record video with object detection overlays, use rpicam-vid instead:

[source,console]

$ rpicam-vid -t 10s -o output.264 --post-process-file /usr/share/rpi-camera-assets/imx500_mobilenet_ssd.json --width 1920 --height 1080 --framerate 30

You can configure the imx500_object_detection stage in many ways.

For example, max_detections defines the maximum number of objects that the pipeline detects at any given time. threshold defines the minimum confidence value required for the pipeline to consider any input as an object.

The raw inference output data of this network can be quite noisy, so this stage also performs some temporal filtering and applies hysteresis. To disable this filtering, remove the temporal_filter config block.

==== Pose estimation

The PoseNet neural network performs pose estimation, labelling key points on the body associated with joints and limbs. imx500_posenet.json contains the configuration parameters for the IMX500 pose estimation post-processing stage using the PoseNet neural network.

imx500_posenet.json declares a post-processing pipeline that contains two stages:

  • imx500_posenet, which fetches the raw output tensor from the PoseNet neural network
  • plot_pose_cv, which draws line overlays on the image

The AI Camera performs basic detection, but the output tensor requires additional post-processing on your host Raspberry Pi to produce final output.

The following command runs rpicam-hello with pose estimation post-processing:

[source,console]

$ rpicam-hello -t 0s --post-process-file /usr/share/rpi-camera-assets/imx500_posenet.json --viewfinder-width 1920 --viewfinder-height 1080 --framerate 30

image::images/imx500-posenet.jpg[IMX500 PoseNet]

You can configure the imx500_posenet stage in many ways.

For example, max_detections defines the maximum number of bodies that the pipeline detects at any given time. threshold defines the minimum confidence value required for the pipeline to consider input as a body.

=== Picamera2

For examples of image classification, object detection, object segmentation, and pose estimation using Picamera2, see https://github.com/raspberrypi/picamera2-examples/blob/main/examples/imx500/[the picamera2-examples GitHub repository].

Most of the examples use OpenCV for some additional processing. To install the dependencies required to run OpenCV, run the following command:

[source,console]

$ sudo apt install python3-opencv python3-munkres

Now download the https://github.com/raspberrypi/picamera2[the picamera2 repository] to your Raspberry Pi to run the examples. You'll find example files in the root directory, with additional information in the README.md file.

Run the following script from the repository to run YOLOv8 object detection:

[source,console]

$ python imx500_object_detection_demo.py --model /usr/share/imx500-models/imx500_network_ssd_mobilenetv2_fpnlite_320x320_pp.rpk

To try pose estimation in Picamera2, run the following script from the repository:

[source,console]

$ python imx500_pose_estimation_higherhrnet_demo.py


Documentation Asciidoc Accessories Ai Camera Model Conversion (`documentation/asciidoc/accessories/ai-camera/model-conversion.adoc`)

== Model deployment

To deploy a new neural network model to the Raspberry Pi AI Camera, complete the following steps:

. Provide a floating-point neural network model (PyTorch or TensorFlow).
. Run the model through Edge-MDT (Edge AI Model Development Toolkit).
.. Quantise and compress the model so that it can run using the resources available on the IMX500 camera module.
.. Convert the compressed model to IMX500 format.
. Package the model into a firmware file that can be loaded at runtime onto the camera.

The first two steps are normally performed on a more powerful computer such as a desktop or server. You must run the final packaging step on a Raspberry Pi.

=== Model creation

The creation of neural network models is beyond the scope of this guide. Existing models can be re-used, or new ones created using popular AI frameworks like TensorFlow or PyTorch.

For more information, see the official https://developer.aitrios.sony-semicon.com/en/raspberrypi-ai-camera[AITRIOS developer website].

=== Model compression and conversion

==== Edge-MDT installation

The Edge-MDT (Model Development Toolkit) software package installs all the tools required to quantise, compress, and convert models to run on your IMX500 device.

The Edge-MDT package takes a parameter to select between installing the PyTorch or TensorFlow version of the tools.

[tabs]

PyTorch:: + [source,console]

$ pip install edge-mdt[pt]

TensorFlow:: + [source,console]

$ pip install edge-mdt[tf]

TIP: Always use the same version of TensorFlow you used to compress your model.

If you need to install both packages, use two separate Python virtual environments. This prevents TensorFlow and PyTorch from causing conflicts with each other.

==== Model Optimization

Models are quantised and compressed using Sony's Model Compression Toolkit (MCT). This tool is automatically installed as part of the Edge-MDT installation step. For more information, see the https://github.com/sony/model_optimization[Sony model optimization GitHub repository].

The Model Compression Toolkit generates a quantised model in the following formats:

  • Keras (TensorFlow)
  • ONNX (PyTorch)

=== Conversion

The converter is a command line application that compiles the quantised model (in .onnx or .keras formats) into a binary file that can be packaged and loaded onto the AI Camera. This tool is automatically installed as part of the Edge-MDT installation step.

To convert a model model:

[tabs]

PyTorch:: + [source,console]

$ imxconv-pt -i -o

TensorFlow:: + [source,console]

$ imxconv-tf -i -o

======

IMPORTANT: For optimal use of the memory available to the accelerator on the IMX500 sensor, add --no-input-persistency to the above commands. However, this disables input tensor generation that can be used for debugging purposes.

Both commands create an output folder that contains a memory usage report and a packerOut.zip file.

For more information on the model conversion process, see the official https://developer.aitrios.sony-semicon.com/en/raspberrypi-ai-camera/documentation/imx500-converter[Sony IMX500 Converter documentation].

=== Packaging

IMPORTANT: You must run this step on a Raspberry Pi.

The final step packages the model into an RPK file. When running the neural network model, we'll upload this file to the AI Camera. Before proceeding, run the following command to install the necessary tools:

[source,console]

$ sudo apt install imx500-tools

To package the model into an RPK file, run the following command:

[source,console]

$ imx500-package -i -o

This command creates a file named network.rpk in the output folder. Pass the name of this file to your IMX500 camera applications.

For a more comprehensive set of instructions and further specifics on the tools used, see the https://developer.aitrios.sony-semicon.com/en/raspberrypi-ai-camera/documentation/imx500-packager[Sony IMX500 Packager documentation].


Documentation Asciidoc Accessories Ai Hat Plus About (`documentation/asciidoc/accessories/ai-hat-plus/about.adoc`)

[[ai-hat-plus]]

AI HATs are add-on boards for Raspberry Pi 5 that come with a built-in AI accelerator chip: the Hailo neural processing unit (NPU). The Hailo NPU allows Raspberry Pi 5 to run hardware-accelerated AI models locally, removing the need to send data to a remote cloud server for processing. This edge AI approach improves performance, reduces latency, and helps to keep data private. For information about how AI HATs integrate with Raspberry Pi 5 to provide hardware-accelerated AI inference, see <>.

AI HATs use the newer Raspberry Pi HAT specification, indicated with a plus sign (+). There are two AI HAT models: AI HAT+ and AI HAT+ 2. For more information, see <>. These AI HATs are available in different performance variants, measured in tera-operations per second (TOPS) of inference performance. AI HAT+ is available in a 13 TOPS or a 26 TOPS variant; AI HAT+ 2 is available in a single 40 TOPS variant. For more information, see <>.

.The 26 tera-operations per second (TOPS) Raspberry Pi AI HAT+
image::images/ai-hat-plus-hero.jpg[width="50%"]

.The 40 tera-operations per second (TOPS) Raspberry Pi AI HAT+ 2
image::images/ai-hat-plus-2-hero.jpg[width="50%"]

[[explanation]]
== How it works

An AI HAT integrates with Raspberry Pi 5 to provide hardware-accelerated AI inference using the on-board Hailo NPU (accelerator chip).

When an AI HAT+ or AI HAT+ 2 is connected to a Raspberry Pi 5, Raspberry Pi OS automatically detects the on-board accelerator and offloads supported AI workloads to it. This includes using our existing camera and vision frameworks to run vision-based neural network models on the NPU. For instructions on connecting an AI HAT+ or AI HAT+ 2 to a Raspberry Pi 5, see <>.

The camera application frameworks, rpicam-apps and Picamera2, which come with Raspberry Pi OS, can automatically use the Hailo NPU for supported AI computing tasks, such as image recognition and object detection. For more information, see xref:../computers/ai.adoc[AI software].

While detection and basic integration are automatic, you must also install other software components and supported AI models to use hardware-accelerated inference. For more information, see xref:../computers/ai.adoc[AI software].

[[AIHAT-models]]
== Models

The following table lists the main capability differences between AI HAT+ and AI HAT+ 2. For information about the specific performance variants of the accelerator chips available for each model, see <>.

NOTE: The AI Kit has the same specifications as the Hailo-8L variant of AI HAT+ and is functionally equivalent. However, the AI Kit is no longer in production and we recommend using one of the AI HATs described in this page.

[cols="1,2,2", options="header"]
|===
| Feature | AI HAT+ | AI HAT+ 2

| Accelerator chip (Hailo NPU)
| Hailo-8L (13 TOPS, INT8) or Hailo-8 (26 TOPS, INT8)
| Hailo-10H (40 TOPS, INT4)

| Memory (RAM)
| Uses the memory on a Raspberry Pi 5
| Has its own 8 GB onboard memory, allowing it to run LLMs and VLMs up to ~6 billion parameters

| Large Language Model (LLM) support
| Not supported
| Supported

| Vision-Language Model (VLM) support
| Not supported
| Supported

| Use cases
| Object detection, camera post-processing, robotics, moderate neural workloads
| Everything available on AI HAT+ plus generative AI workloads, including local LLMs and VLMs
|===

[[AIHAT-TOPS]]
== Performance (TOPS) variants

AI HAT+ is available in the following tera-operations per second (TOPS) inference performance variants:

  • 13 TOPS, built around the Hailo-8L neural network accelerator. This suits moderate workloads, with performance similar to the xref:ai-kit.adoc[AI Kit].
  • 26 TOPS, built around the Hailo-8 neural network accelerator. This supports larger networks, higher throughput, and parallel AI models.

AI HAT+ 2 delivers 40 TOPS inference performance, built around the Hailo-10H neural network inference accelerator. This supports all AI HAT+ workloads and adds local LLM and VLM capabilities, enabling applications such as local chat over documents.

== Physical specifications

The following images depict the physical dimensions of AI HAT+, AI HAT+ 2, and the heatsink that comes with AI HAT+ 2. The size is the same for both AI HAT+ and AI HAT+ 2; the main visual difference is the inclusion of the SDRAM on AI HAT+ 2. For more information about this difference, see <>.

=== AI HAT+ specifications

The following image depicts the approximate physical dimensions of an AI HAT+ in millimetres (mm). AI HAT+ is approximately 66 mm × 56.5 mm. The Hailo NPU has a metal casing around it, making it approximately 17 mm × 17 mm.

.Mechanical diagram of AI HAT+; all measurements are approximate and in millimetres
image::images/aihat-plus-mechanical.png[width="60%"]

=== AI HAT+ 2 and heatsink specifications

The following image depicts the approximate physical dimensions of an AI HAT+ 2 in millimetres (mm). AI HAT+ is approximately 66 mm × 56.5 mm. The Hailo NPU is approximately 15 mm × 15 mm and the SDRAM is approximately 14.5 mm × 10 mm.

.Mechanical diagram of AI HAT+ 2; all measurements are approximate and in millimetres
image::images/aihat-plus-2-mechanical.png[width="60%"]

The following image depicts the approximate physical dimensions of the heatsink for an AI HAT+ 2 in millimetres (mm). Taking into account both corners with the push-pin holes for attaching the heatsink to an AI HAT+ 2, the heatsink is approximately 42.5 mm × 64 mm. With the push pins, an AI HAT+ 2 is approximately 14 mm high; without the push pins, an AI HAT+ 2 is approximately 3.2 mm high.

.Mechanical diagram of the heatsink for an AI HAT+ 2; all measurements are approximate and in millimetres
image::images/aihat-plus-2-heatsink-mechanical.png[width="60%"]

[[ai-hat-plus-installation]]
== Hardware assembly

Check that you have the required hardware and then follow the steps to install an AI HAT+ or AI HAT+ 2 on a Raspberry Pi 5, ensuring that your Raspberry Pi 5 is disconnected from power before you begin.

[[hardware]]
=== Prerequisites

Both AI HAT+ and AI HAT+ 2 come with the following mounting hardware:

  • Four threaded spacers.
  • Four long screws for attaching the spacers to your Raspberry Pi 5.
  • Four short screws for mounting an AI HAT+ or AI HAT+ 2 to the spacers on your Raspberry Pi 5.
  • A GPIO stacking header.
  • A ribbon cable.

.Mounting hardware for an AI HAT
image::images/ai-hat-plus-installation-02.png[width="60%"]

Additionally, you need:

  • A Raspberry Pi 5.
  • A Phillips crosshead screwdriver.
  • Optionally, a Raspberry Pi Active Cooler (recommended). This is an aluminium heatsink with a fan that helps to dissipate heat from your Raspberry Pi 5, keeping it at a safe operating temperature.

AI HAT+ 2 comes with an additional heatsink that you install on top of the HAT. We recommend installing both the Active Cooler (on your Raspberry Pi 5) and the heatsink (on your AI HAT+ 2).

When you have all of the required hardware, complete the following steps.

[[step1]]
=== Step 1. Mount an Active Cooler (recommended)

We recommend that you mount an Active Cooler to your Raspberry Pi 5. If you want to skip this step, or if your Raspberry Pi 5 already has an Active Cooler mounted to it, move on to the next step.

-- image::images/ai-hat-plus-installation-01.png[width="60%"]

First, ensure that your Raspberry Pi 5 is disconnected from power. Then:

. Prepare the cooler. Remove the protective paper from the thermal pads at the bottom of the cooler. This exposes a sticky surface on each of the thermal pads.
. Position the cooler. Align the two white push pins with the two dedicated heatsink holes on your Raspberry Pi 5. In this position, the thermal pads align with the wireless radio, the system-on-chip (SoC), and the power management integrated circuit (PMIC).
. Secure the cooler. Press the cooler gently onto your Raspberry Pi 5. Then, evenly press the two white push pins down into the two dedicated heatsink holes on your Raspberry Pi 5 until they click.
. Connect the fan. Plug the fan's JST connector into the fan socket on your Raspberry Pi 5.

NOTE: Ensure that the push pins are undamaged and securely clipped to the Raspberry Pi 5 before use.

We recommend that you don't remove the cooler after it's fitted to the Raspberry Pi 5. This is because removing the cooler can cause the push pins and thermal pads to degrade, which can lead to product damage.

[[step2]]
=== Step 2. Mount the AI HAT+ 2 heatsink (recommended)

The AI HAT+ 2 comes with an additional heatsink. If you're mounting an AI HAT+ and not an AI HAT+ 2, you can skip this step.

While the heatsink supplied with the AI HAT+ 2 is optional, we recommend mounting it to your AI HAT+ 2, especially if you're running benchmarks or intensive AI workloads. This prevents your AI HAT+ 2 from slowing down due to overheating.

To attach the AI HAT+ 2 heatsink to your AI HAT+ 2 (before mounting it to your Raspberry Pi 5):

. Prepare the heatsink. Remove the protective paper from the thermal pads on the underside of the heatsink. This exposes a sticky surface on each of the thermal pads.
. Position the heatsink. Align the two black push pins on the heatsink to the two dedicated heatsink holes in diagonally opposite corners on your AI HAT+ 2. In this position, the thermal pads align with the power regulator, the Hailo NPU, and the SDRAM chip.
. Secure the heatsink. Evenly press the two black push pins down into the heatsink holes on the AI HAT+ 2 until they click.

NOTE: Ensure that the push pins are undamaged and securely clipped to the AI HAT+ 2 before use.

We recommend that you don't remove the heatsink after it's fitted to the Raspberry Pi AI HAT+ 2. This is because removing the heatsink can cause the push pins and thermal pads to degrade, which can lead to product damage.

[[step3]]
=== Step 3. Mount the AI HAT

The AI HAT+ and AI HAT+ 2 both connect to a Raspberry Pi 5 using its PCIe port, which is a high-speed interface for connecting hardware components.

First, ensure that your Raspberry Pi 5 is disconnected from power, and then:

. Fit the spacers. Using a Phillips crosshead screwdriver, attach the four spacers to the yellow holes on your Raspberry Pi 5 using the four longer screws.
. Connect the GPIO stacking header. Align the GPIO stacking header with the GPIO pins on your Raspberry Pi 5. Press down firmly until the header is fully seated. The orientation of the header doesn't matter so long as all the GPIO pins are correctly aligned and inserted.
. Disconnect the PCIe ribbon cable from your AI HAT. Slide the retaining clips outwards from both sides of the PCIe connector on the AI HAT and then gently pull out the cable.
. Insert the PCIe ribbon cable into your Raspberry Pi. Insert the other end of the ribbon cable into the PCIe connector on your Raspberry Pi 5. To do this, first slide the retaining clip of the PCIe connector on your Raspberry Pi 5 upwards from both sides. Then, insert the ribbon cable into the PCIe connector. Ensure that the metallic contact points are facing inwards (towards the USB ports).
. Secure the PCIe ribbon cable to your Raspberry Pi. While holding the ribbon cable in place, push the retaining clip back into the connector from both sides, ensuring that the cable is evenly inserted.
. Mount the AI HAT. With the main components of your AI HAT facing upwards, align the mounting holes on the AI HAT with the spacers on your Raspberry Pi 5. Use the four remaining (shorter) screws to secure the AI HAT in place.
. Insert the PCIe ribbon cable into your AI HAT. Insert the unconnected end of the ribbon cable into the PCIe connector on your AI HAT. To do this, first slide the retaining clip of the PCIe connector on your AI HAT outwards from both sides. Then, insert the ribbon cable into the PCIe connector.
. Secure the PCIe ribbon cable to your AI HAT. While holding the ribbon cable in place, push the retaining clip back into the connector from both sides, ensuring that the cable is evenly inserted.

== Next steps: Run AI models

AI HATs support both example models provided by Hailo and custom models trained for your specific applications, such as speech-to-text, translation, or visual scene analysis. For a list of available example models, see Hailo's https://hailo.ai/products/hailo-software/model-explorer/generative-ai/[Model Explorer].

To start running AI models on your Raspberry Pi 5, see xref:../computers/ai.adoc[AI software], which provides information and guidance on:

  • Running AI-accelerated visual models on your Raspberry Pi 5.
  • Generative AI models relevant to AI HAT+ 2.

Documentation Asciidoc Accessories Ai Kit About (`documentation/asciidoc/accessories/ai-kit/about.adoc`)

[[ai-kit]]

This page exists for reference purposes only.

The Raspberry Pi AI Kit is no longer in production and we recommend using one of the AI HATs described in xref:../accessories/ai-hat-plus.adoc[AI HATs]. Here, you can also find more information about the AI technology provided by the Hailo NPU used in both the AI Kit and the functionally equivalent Hailo-8L variant of AI HAT+.

.The Raspberry Pi AI Kit
image::images/ai-kit.jpg[width="80%"]

== Hardware

The AI Kit bundles the xref:m2-hat-plus.adoc#m2-hat-plus[Raspberry Pi M.2 HAT+] with a Hailo AI acceleration module for use with Raspberry Pi 5. The kit contains:

  • A Raspberry Pi M.2 HAT+, used to connect the AI module to your Raspberry Pi 5.
  • A Hailo AI module containing a neural processing unit (NPU), pre-installed onto your M.2 HAT+.
  • A thermal pad pre-fitted between the module and the M.2 HAT+.
  • A mounting hardware kit, consisting of a ribbon cable, spacers, and screws.
  • A 16 mm stacking GPIO header.

The Hailo AI module provides:

  • A 13 tera-operations per second (TOPS) neural network inference accelerator built around the Hailo-8L chip.
  • An M.2 2242 form factor.

Additionally, you need:

  • A Raspberry Pi 5.
  • A Phillips crosshead screwdriver.
  • Optionally, a Raspberry Pi Active Cooler (recommended). This is an aluminum heatsink with a fan that helps to dissipate heat from your Raspberry Pi 5, keeping it at a safe operating temperature.

[[step1]]
== Step 1. Mount an Active Cooler (recommended)

We recommend that you mount an Active Cooler to your Raspberry Pi 5. If you want to skip this step, or if your Raspberry Pi 5 already has an Active Cooler mounted to it, move on to the next step.

image::images/ai-kit-installation-01.png[width="60%"]

First, ensure that your Raspberry Pi 5 is disconnected from power. Then:

. Prepare the cooler. Remove the protective paper from the thermal pads at the bottom of the cooler. This exposes a sticky surface on each of the thermal pads.
. Position the cooler. Align the two white push pins with the two dedicated heatsink holes on your Raspberry Pi 5. In this position, the thermal pads align with the wireless radio, the system-on-chip (SoC), and the power management integrated circuit (PMIC).
. Secure the cooler. Press the cooler gently onto your Raspberry Pi 5. Then, evenly press the two white push pins down into the two dedicated heatsink holes on your Raspberry Pi 5 until they click.
. Connect the fan. Plug the fan's JST connector into the fan socket on your Raspberry Pi 5.

NOTE: Ensure that the push pins are undamaged and securely clipped to the Raspberry Pi 5 before use.

We recommend that you don't remove the cooler after it's fitted to the Raspberry Pi 5. This is because removing the cooler can cause the push pins and thermal pads to degrade, which can lead to product damage.

== Step 2. Mount the M.2 HAT+

The M.2 HAT+ connects to a Raspberry Pi 5 using its PCIe port, which is a high-speed interface for connecting hardware components. First, ensure that your Raspberry Pi 5 is disconnected from power, and then:

. *Fit the spacers.* Using a Phillips crosshead screwdriver, attach the four spacers to the yellow holes on your Raspberry Pi 5 using the four screws. . *Connect the GPIO stacking header.* Align the GPIO stacking header with the GPIO pins on your Raspberry Pi 5. Press down firmly until the header is fully seated. The orientation of the header doesn't matter so long as all the GPIO pins are correctly aligned and inserted. . *Disconnect the PCIe ribbon cable from your HAT.* Slide the retaining clips outwards from both sides of the PCIe connector on the HAT and then gently pull out the cable. . *Insert the PCIe ribbon cable into your Raspberry Pi.* Insert the other end of the ribbon cable into the PCIe connector on your Raspberry Pi 5. To do this, first slide the retaining clip of the PCIe connector on your Raspberry Pi 5 upwards from both sides. Then, insert the ribbon cable into the PCIe connector. Ensure that the metallic contact points are facing inwards (towards the USB ports). . *Secure the PCIe ribbon cable to your Raspberry Pi.* While holding the ribbon cable in place, push the retaining clip back into the connector from both sides, ensuring that the cable is evenly inserted. +

image::images/ai-kit-installation-02.png[width="60%"]

. *Mount the HAT.* With the main components of your HAT facing upwards, align the mounting holes on the HAT with the spacers on your Raspberry Pi 5. Use the four remaining (shorter) screws to secure the HAT in place. +

image::images/ai-kit-installation-03.png[width="60%"]

. *Insert the PCIe ribbon cable into your HAT.* Insert the unconnected end of the ribbon cable into the PCIe connector on your HAT. To do this, first slide the retaining clip of the PCIe connector on your HAT outwards from both sides. Then, insert the ribbon cable into the PCIe connector. +

image::images/ai-kit-installation-04.png[width="60%"]

. Secure the PCIe ribbon cable to your HAT. While holding the ribbon cable in place, push the retaining clip back into the connector from both sides, ensuring that the cable is evenly inserted.

WARNING: Always disconnect your Raspberry Pi from power before connecting or disconnecting a device from the M.2 slot.

== Next steps: Run AI models

For a list of available example models, see Hailo's https://hailo.ai/products/hailo-software/model-explorer-vision/[Model Explorer].

To start running AI models on your Raspberry Pi 5, see xref:../computers/ai.adoc[AI software], which provides information and guidance on running AI-accelerated visual models.


Documentation Asciidoc Accessories Audio Codec Zero (`documentation/asciidoc/accessories/audio/codec_zero.adoc`)

=== Raspberry Pi Codec Zero

Raspberry Pi Codec Zero is a Raspberry Pi Zero-sized audio HAT. It delivers bi-directional digital audio signals (I2S) between a Raspberry Pi and the Codec Zero's on-board Dialog Semiconductor DA7212 codec. The Codec Zero supports a range of input and output devices.

  • High performance 24-bit audio codec
  • Supports common audio sample rates between 8-96 kHz
  • Built in micro-electro-mechanical (MEMS) microphone (Mic2)
  • Mono electret microphone (Mic2 left)
  • Automatic MEMS disabling on Mic2 insert detect
  • Supports additional (no fit) mono electret microphone (Mic1 right)
  • Stereo auxiliary input channel (AUX IN) – PHONO/RCA connectors
  • Stereo auxiliary output channel (Headphone/AUX OUT)
  • Flexible analogue and digital mixing paths
  • Digital signal processors (DSP) for automatic level control (ALC)
  • Five-band EQ
  • Mono line-out/mini speaker driver: 1.2 W at 5 V, THD < 10%, R = 8 Ω

image::images/Codec_Zero_Board_Diagram.jpg[width="80%"]

The Codec Zero includes an EEPROM which can be used for auto-configuration of the Linux environment if necessary. It has an integrated MEMS microphone, and can be used with stereo microphone input through a 3.5 mm socket and a mono speaker (1.2W/8Ω).

In addition to the green (GPIO23) and red (GPIO24) LEDs, a tactile programmable button (GPIO27) is also provided.

==== Pinouts

[cols="1,12"]
|===
| P1/2 | Support external PHONO/RCA sockets if needed. P1: AUX IN, P2: AUX OUT.
| P1 | Pin 1 is square.
|===
image::images/CODEC_ZERO_ZOOMED_IN_DIAGRAM.jpg[width="50%"]

Codec Zero is an ideal design starting point for small-scale projects such as walkie-talkies, smart doorbells, vintage radio hacks, or smart speakers.


Documentation Asciidoc Accessories Audio Configuration (`documentation/asciidoc/accessories/audio/configuration.adoc`)

== Attach, connect, and configure

Raspberry Pi audio boards are designed to be plug-and-play with Raspberry Pi devices running xref:../computers/os.adoc[Raspberry Pi OS], as they feature a pre-programmed EEPROM. They belong to a family of devices known as HATs (Hardware Attached on Top).

They can also be used with a xref:../computers/getting-started.adoc#headless-setup[headless (remote) setup].

=== Attach and connect the audio board

Raspberry Pi audio boards attach to the 40-pin GPIO header and are designed to be supported using the supplied circuit board standoffs and screws. All necessary mounting hardware, including spacers, screws, and connectors, is provided.

Soldering isn't required for normal operation, but might be if you want to hard-wire specific connectors (External Line Return connections on the DAC Pro, for example).

To attach the audio board:

. Screw the PCB spacers finger-tight onto your Raspberry Pi device.
. Fit the audio board onto the 40-pin GPIO header.
. From above the board, screw in the remaining screws.

=== Check hardware version

There are multiple versions of Raspberry Pi audio boards. The version determines the actions required for configuration.

Older IQaudIO-branded boards have a black PCB. Newer Raspberry Pi-branded boards have a green PCB. These boards are electrically equivalent, but have different EEPROM contents.

To check the version of your audio board:

. Attach the audio board to your Raspberry Pi and apply power to it. . Check that the power LED on the audio board is illuminated, if it has one. For example, the Codec Zero has an LED marked `PWR`. . On the Raspberry Pi device, use the Terminal to enter the following command: + [source,console]

$ grep -a . /proc/device-tree/hat/*

The Terminal returns one of the following strings:

[tabs]

Raspberry Pi Ltd.::
+
No further action is required (see below for <>).

IQaudIO Limited.::
+
No further action is required (see below for <>).

No such file or directory:: +

The HAT isn't detected. Do the following:

. Power down the device. . Check the physical connections between the HAT and the Raspberry Pi device. . Power on the device, then repeat Step 3 in the preceding section. . If the same string is returned, open xref:../computers/config_txt.adoc[`config.txt`] on your Raspberry Pi device. . Add the following lines to cancel loading the default HAT overlay and apply the correct device tree overlay: + [source,ini]

Suppress the default HAT overlay:

dtoverlay=

Add ONE of the following:

dtoverlay=rpi-codeczero dtoverlay=rpi-dacplus dtoverlay=rpi-dacpro dtoverlay=rpi-digiampplus

. Save and close the file. . Reboot your Raspberry Pi to make the changes take effect.

====

=== Configure the audio board

After you've attached and connected your audio board to your Raspberry Pi device, you can switch between using it and the on-board device for audio playback:

. Right-click the audio settings in the top-right corner of your screen.
. Switch between the on-board audio settings and the HAT audio settings.

image::images/gui.png[]

You can also disable the on-board audio device, which makes the Raspberry Pi audio board the primary audio device in Raspberry Pi OS.

The command-line method described below is useful if you're running a headless setup (or Raspberry Pi OS Lite) and can't control the audio board through the graphical Raspberry Pi OS desktop interface.

To disable the on-board audio device using SSH:

. Connect to your Raspberry Pi device using xref:../computers/remote-access.adoc#ssh[SSH]. . Run the following command to edit the file: + [source,console]

$ sudo nano /boot/firmware/config.txt

. Find the `dtparam=audio=on` line in the file and comment it out by placing a `#` symbol at the start of the line. + The program disregards anything written after the `#` symbol on any given line. Your `/boot/firmware/config.txt` file now includes the following entry: + [source,ini]

#dtparam=audio=on

. Press *Ctrl+X*, then *Y*, then *Enter* to save. . Reboot your Raspberry Pi for the settings to take effect: + [source,console]

$ sudo reboot

=== Extra Codec Zero configuration

Raspberry Pi Codec Zero uses the Dialog Semiconductor DA7212 codec.

This allows the recording of audio from the built-in MEMS microphone, from stereo headers (AUX IN), or from two mono external electret microphones.

Playback is through stereo headers (AUX OUT) or a mono speaker connector.

Each input and output device has its own mixer, allowing audio levels and volume to be adjusted independently. Within the codec itself, other mixers and switches exist to allow the output to be mixed to a single mono channel for single-speaker output. Signals can also be inverted; there's a five-band equaliser to adjust certain frequency bands. You can control these settings interactively using AlsaMixer, or programmatically.

Both AUX IN and AUX OUT are 1 V RMS. You might need to adjust the mixer for AUX IN to ensure the input signal doesn't saturate the ADC. Similarly, adjust the output mixers to get the best possible output.

Preconfigured scripts (loadable ALSA settings) are https://github.com/raspberrypi/Pi-Codec[available on GitHub], offering:

  • Mono MEMS microphone recording, mono speaker playback.
  • Mono MEMS microphone recording, mono AUX OUT playback.
  • Stereo AUX IN recording, stereo AUX OUT playback
  • Stereo MIC1/MIC2 recording, stereo AUX OUT playback

Codec Zero needs to know which of these input and output settings are used each time your Raspberry Pi powers on.

To provide the codec with input and output settings:

. If `git` isn't installed, open the Terminal and run the following command: + [source,console]

$ sudo apt install git

. In a terminal session, run the following command to clone the scripts: + [source,console]

$ git clone https://github.com/raspberrypi/Pi-Codec.git

. Run the following command to set your device to use the on-board MEMS microphone for input and speaker playback for output, replacing `` with your username: + [source,console]

$ sudo alsactl restore -f /home//Pi-Codec/Codec_Zero_OnboardMIC_record_and_SPK_playback.state

This command might result in harmless warnings, including:
+

  • "failed to import hw" or "snd_use_case_mgr_open"
  • "No state is present for card"

In most cases, you can safely ignore these warnings.
+
However, the following warnings can indicate a hardware failure:
+

  • "Remote I/O error"

. To make sure your settings persist the next time you boot the Raspberry Pi device, edit the `/etc/rc.local` file: + [source,console]

$ sudo nano /etc/rc.local

. Add the chosen script command above the `exit 0` line. + The file looks similar to the following: + [source,bash]

#!/bin/sh

rc.local

This script is executed at the end of each multiuser runlevel.

Make sure that the script will "exit 0" on success or any other

value on error.

In order to enable or disable this script just change the execution

bits.

By default this script does nothing.

sudo alsactl restore -f /home//Pi-Codec/Codec_Zero_OnboardMIC_record_and_SPK_playback.state

exit 0

. Press *Ctrl+X*, then *Y*, then *Enter* to save. Reboot for the settings to take effect: + [source,console]

$ sudo reboot

If you're using your Raspberry Pi in a xref:../computers/getting-started.adoc#headless-setup[headless] or command-line environment:

. Create the following file in your home folder: + [source,console]

$ nano ~/.asoundrc

. Add the following lines to the file to route default playback and capture through the ALSA `plug` plugin for automatic format and channel conversions: + [source,alsa]

pcm.!default {
type plug
slave.pcm {
type hw
card Zero
}
}

ctl.!default {
type hw
card Zero

}

. Press *Ctrl+X*, then *Y*, then *Enter* to save. . Reboot again to complete the configuration: + [source,console]

$ sudo reboot

=== Audio frameworks

Like other modern Linux distributions, xref:../computers/os.adoc[Raspberry Pi OS] uses PulseAudio or PipeWire by default for audio control.

These frameworks can mix and switch audio from multiple sources, and provide a high-level API for audio applications. Many audio applications use these frameworks by default.

Only create ~/.asoundrc if an audio application needs to:

  • Communicate directly with ALSA.
  • Run in an environment where PulseAudio or PipeWire isn't present.

This file can interfere with the UI view of underlying audio resources. We don't recommend creating ~/.asoundrc when running the Raspberry Pi OS desktop. The UI might automatically remove this file if it exists.

=== Mute and unmute the DigiAMP{plus}

The mute state on DigiAMP{plus} is toggled using GPIO22. The device tree overlay supports unmuting DigiAMP{plus} using additional parameters.

To apply a one-shot unmute when the kernel module loads:

For Raspberry Pi boards:

[source,ini]

dtoverlay=rpi-digiampplus,unmute_amp

For IQaudIO boards:

[source,ini]

dtoverlay=iqaudio-digiampplus,unmute_amp

To unmute the amplifier when an ALSA device is opened by a client and mute with a five-second delay when closed (reopening within the five-second window cancels the mute):

For Raspberry Pi boards:

[source,ini]

dtoverlay=rpi-digiampplus,auto_mute_amp

For IQaudIO boards:

[source,ini]

dtoverlay=iqaudio-digiampplus,auto_mute_amp

If you don't want to control the mute state through the device tree, you can script your own solution.

The amplifier starts muted.

To unmute the amplifier:

[source,console]

$ pinctrl 22 op dh

To mute the amplifier again:

[source,console]

$ pinctrl 22 dl

=== Controlling the digital volume

If you're using the Raspberry Pi OS desktop environment, you can use the volume slider in the system tray.

To adjust the audio output volume on your audio board in a headless setup, use AlsaMixer:

[source,console]

$ alsamixer

Use the left and right arrow keys to select the volume channel you want to adjust, then use the up and down arrow keys to adjust the volume. Press Esc to exit AlsaMixer.


Documentation Asciidoc Accessories Audio Dac Plus (`documentation/asciidoc/accessories/audio/dac_plus.adoc`)

=== Raspberry Pi DAC{plus}

Raspberry Pi DAC{plus} is a high-resolution audio output HAT that provides 24-bit 192 kHz digital audio output.

image::images/DAC+_Board_Diagram.jpg[width="80%"]

A Texas Instruments PCM5122 is used in the DAC{plus} to deliver analogue audio to the phono connectors of the device. It also supports a dedicated headphone amplifier and is powered by the Raspberry Pi through the GPIO header.

==== Pinouts

[cols="1,12"]
|===
| P1 | Analogue out (0-2V RMS), carries GPIO27, MUTE signal (headphone detect), left and right
audio and left and right ground.
| P6 | Headphone socket signals (pin1: LEFT, 2:GROUND, 3: RIGHT, 4:GROUND, 5:DETECT).
|===


Documentation Asciidoc Accessories Audio Dac Pro (`documentation/asciidoc/accessories/audio/dac_pro.adoc`)

=== Raspberry Pi DAC Pro

The Raspberry Pi DAC Pro HAT is our highest-fidelity digital to analogue converter (DAC).

image::images/DAC_Pro_Board_Diagram.jpg[width="80%"]

With the Texas Instruments PCM5242, the DAC Pro provides outstanding signal-to-noise ratio (SNR)
and supports balanced/differential output in parallel to phono/RCA line-level output. It also includes a
dedicated headphone amplifier. The DAC Pro is powered by a Raspberry Pi through the GPIO header.

As part of the DAC Pro, two three-pin headers (P7/P9) are exposed above the Raspberry Pi device's USB and Ethernet ports for use by the optional XLR board, allowing differential/balanced output.

==== Pinouts

[cols="1,12"]
|===
| P1 | Analogue out (0-2V RMS), carries GPIO27, MUTE signal (headphone detect), left and right
audio and left and right ground.
| P6 | Headphone socket signals (1: LEFT, 2: GROUND, 3: RIGHT, 4: GROUND, 5: DETECT).
| P7/9 | Differential (0-4V RMS) output (P7: LEFT, P9: RIGHT).
| P10 | Alternative 5V input, powering Raspberry Pi in parallel.
|===

==== Optional XLR Board

The Pi-DAC PRO exposes a 6 pin header used by the optional XLR board to provide Differential / Balanced output exposed by XLR sockets above the Raspberry Pi device's USB/Ethernet ports.

image::images/optional_xlr_board.jpg[width="80%"]

An XLR connector is used in Studio and some hi-end hifi systems. It can also be used to drive ACTIVE "monitor" speakers as used at discos or on stage.


Documentation Asciidoc Accessories Audio Digiamp Plus (`documentation/asciidoc/accessories/audio/digiamp_plus.adoc`)

=== Raspberry Pi DigiAMP{plus}

With Raspberry Pi DigiAMP{plus}, you can connect 2 passive stereo speakers up to 35 W with variable output, making it ideal for use in Raspberry Pi-based hi-fi systems.

DigiAMP{plus} uses the Texas Instruments TAS5756M PowerDAC and must be powered from an external supply.

It requires a 12-24V DC power source (the XP Power VEC65US19 power supply is recommended).

NOTE: The DigiAMP{plus} is designed to work with Raspberry Pi 3 and earlier devices. If you use it with a Raspberry Pi 4 or later devices, use an externally-powered USB hub to prevent the USB ports from adding extra load to the device. Failure to do so is likely to result in a low power warning.

image::images/DigiAMP+_Board_Diagram.jpg[alt="A top-down image of the DigiAmp+ board, showing the silk screen and components.",width="80%"]

DigiAMP{plus}'s power in barrel connector is 5.5 mm × 2.5 mm.

At power-on, the amplifier is muted by default (the mute LED is illuminated). Software is responsible for the mute state and LED control (Raspberry Pi GPIO22).

DigiAMP{plus} is designed to provide power to the Raspberry Pi and DigiAMP{plus} together in parallel, delivering 5.1V at 2.5amp to the Raspberry Pi through the GPIO header.

WARNING: Don't apply power to the Raspberry Pi device's own power input when using DigiAMP{plus}.

==== Pinouts
[cols="1,12"]
|===
| P5 | Alternative power input for hard wired installations (polarity must be observed).
| P8 | TAS5756m Internal GPIO1/2/3
|===

==== Speaker Terminal Polarity

Polarity is printed on the silk screen above the speaker terminals.

Looking down at the top of the board, and with the power connector on the left, both terminals have the same polarity: "-" on the left and "+" on the right.


Documentation Asciidoc Accessories Audio Getting Started (`documentation/asciidoc/accessories/audio/getting_started.adoc`)

== Getting started

=== Create a toy chatter box

As an example of what Raspberry Pi Audio Boards can do, let's walk through the creation of a toy chatter box. Its on-board microphone, programmable button and speaker driver make the Codec Zero an ideal choice for this application.

image::images/Chatter_Box.jpg[width="80%"]

A random pre-recorded five-second audio clip will be played when the button is pressed. After holding for ten seconds, a notifying burp sound will be emitted, after which a new five-second clip will be recorded. Holding the button down for more than 20 seconds will play a second burp sound, and then erase all previous recordings.

=== Hardware and wiring

For this project, any small passive speaker is probably sufficient. We're using one available https://shop.pimoroni.com/products/3-speaker-4-3w?variant=380549926[here], which handles 5 W of power at 4 Ω. We have also used an illuminated momentary push button, and a laser-cut box to house all the components; but both are entirely optional. This example will work just using the Codec Zero's on-board button, which is pre-wired to GPIO 27. (Alternatively, you can use any momentary push button, such as those available https://shop.pimoroni.com/products/mini-arcade-buttons?variant=40377171274[here].)

image::images/Chatterbox_Labels.png[width="80%"]

Use a small flat-head screwdriver to attach your speaker to the screw terminals. For the additional push button, solder the button wires directly to the Codec Zero pads as indicated, using GPIO pin 27 and Ground for the switch, and +3.3V and Ground for the LED, if necessary.

=== Set up your Raspberry Pi

In this example, we are using Raspberry Pi OS Lite. Refer to our guide on xref:../computers/getting-started.adoc#install[installing Raspberry Pi OS] for more details.

Make sure that you update your operating system before proceeding and follow the instructions provided for Codec Zero configuration, including the commands to enable the on-board microphone and speaker output.

=== Program your Raspberry Pi

Open a shell — for instance by connecting over SSH — on your Raspberry Pi and run the following to create our Python script:

[source,console]

$ sudo nano chatter_box.py

Add the following to the file, replacing `` with your username:

[source,python]

#!/usr/bin/env python3
from gpiozero import Button
from signal import pause
import time
import random
import os
from datetime import datetime

date = datetime.now().strftime("%d_%m_%Y-%H:%M:%S")
print(f"{date}")

Make sure that the 'sounds' folder exists, and if it does not, create it

path = '/home//sounds'

isExist = os.path.exists(path)

if not isExist:
os.makedirs(path)
print("The new directory is created!")
os.system('chmod 777 -R /home//sounds')

Download a 'burp' sound if it does not already exist

burp = '/home//burp.wav'

isExist = os.path.exists(burp)
if not isExist:
os.system('wget http://rpf.io/burp -O burp.wav')
print("Burp sound downloaded!")

Setup button functions - Pin 27 = Button hold time 10 seconds.

button = Button(27, hold_time=10)

def pressed():
global press_time
press_time = time.time()
print("Pressed at %s" % (press_time));

def released():
release_time = time.time()
pressed_for = release_time - press_time
print("Released at %s after %.2f seconds" % (release_time, pressed_for))
if pressed_for < button.hold_time:
print("This is a short press")
randomfile = random.choice(os.listdir("/home//sounds/"))
file = '/home//sounds/' + randomfile
os.system('aplay ' + file)
elif pressed_for > 20:
os.system('aplay ' + burp)
print("Erasing all recorded sounds")
os.system('rm /home//sounds/*');

def held():
print("This is a long press")
os.system('aplay ' + burp)
os.system('arecord --format S16_LE --duration=5 --rate 48000 -c2 /home//sounds/$(date +"%d_%m_%Y-%H_%M_%S")_voice.m4a');

button.when_pressed = pressed
button.when_released = released
button.when_held = held

pause()


Press Ctrl+X, then the Y key, then Enter to save. To make the script executable, type the following:

[source,console]

$ sudo chmod +x chatter_box.py

Next, we need to create a crontab daemon that will automatically start the script each time the device is powered on. Run the following command to open your crontab for editing:

[source,console]

$ crontab -e

You're asked to select an editor; we recommend you use nano. Select it by entering the corresponding number, and press Enter to continue. Add the following line to the bottom of the file, replacing `` with your username:


@reboot python /home//chatter_box.py

Press Ctrl X, then Y, then Enter to save, then reboot your device with sudo reboot.

=== Use the toy chatter box

The final step is to ensure that everything is operating as expected. Press the button and release it when you hear the burp. The recording will now begin for a period of five seconds. After you release the button, press it briefly again to hear the recording. Repeat this process as many times as you wish, and your sounds will be played at random. You can delete all recordings by pressing and holding the button, keeping the button pressed during the first burp and recording process, and releasing it after at least 20 seconds, at which point you will hear another burp sound confirming that the recordings have been deleted.

video::BjXERzu8nS0[youtube,width=80%,height=400px]

=== Next steps

Upgrades! It is always fun to upgrade a project, so why not add some additional features, such as an LED that will illuminate when recording? This project has all the parts required to make your own version of a https://aiyprojects.withgoogle.com/[Google intelligent speaker system], or you might want to consider building a second device that can be used to create a pair of walkie-talkies that are capable of transferring audio files over a network by using SSH.


Documentation Asciidoc Accessories Audio Hardware Info (`documentation/asciidoc/accessories/audio/hardware-info.adoc`)

== Hardware information

Hardware information:

  • PCB screws are all M2.5.
  • PCB standoffs (for case) are 5 mm male/female.
  • PCB standoffs (for Raspberry Pi to audio boards) are 9 mm female/female.
  • PCB standoffs (for XLR to DAC PRO) are 8 mm female/male.
  • PCB standoffs (for the official Raspberry Pi 7-inch display) are 5 mm male/female.
  • The rotary encoders we have used and tested are the Alpha three-pin rotary encoder
    RE160F-40E3-20A-24P, the ALPS EC12E2430804 (RS: 729-5848), and the Bourns ECW0JB24-AC0006L (RS: 263-2839).
  • The barrel connector used for powering the DigiAMP{plus} is 2.5 mm ID, 5.5 mm OD, 11 mm.
  • The DigiAMP{plus} is designed to operate with a 12V to 24V, 3A supply such as the XPPower
    VEC65US19 or similar.
  • The DigiAMP{plus} uses CamdenBoss two-part connectors. Those fitted to the PCB are
    CTBP9350/2AO.
  • The speaker terminal used on the Codec Zero will accept wires of between 14~26 AWG
    (wire of max 1.6 mm in diameter).

=== GPIO usage

Raspberry Pi audio boards take advantage of a number of pins on the GPIO header in
order to operate successfully. Some of these pins are solely for the use of the board, and
some can be shared with other peripherals, sensors, etc.

The following Raspberry Pi GPIO pins will be used by the audio boards:

  • All power pins
  • All ground pins
  • GPIO 2/3 (I2C)
  • GPIO 18/19/20/21 (I2S)

If appropriate then the following are also used:

  • GPIO 22 (DigiAMP+ mute/unmute support)
  • GPIO 23/24 for rotary encoder (physical volume control) or status LED (Codec Zero)
  • GPIO 25 for the IR Sensor
  • GPIO 27 for the rotary encoder push switch/Codec Zero switch

=== DAC PRO, DAC{plus}, DigiAMP{plus}, Codec Zero

image::images/all_audio_boards_gpio_pinouts.png[width="80%"]

The DAC PRO, DAC{plus} and DigiAMP{plus} re-expose the Raspberry Pi signals, allowing additional sensors and peripherals to be added easily. Some signals are for exclusive use (I2S and EEPROM) by some of our boards; others, such as I2C, can be shared across multiple boards.

image::images/pin_out_new.png[width="80%"]

=== Saving AlsaMixer settings

To store the AlsaMixer settings, add the following at the command line:

[source,console]

$ sudo alsactl store

You can save the current state to a file, then reload that state at startup.

To save, run the following command, replacing `` with your username:

[source,console]

$ sudo alsactl store -f /home//usecase.state

To restore a saved file, run the following command, replacing `` with your username:

[source,console]

$ sudo alsactl restore -f /home//usecase.state

=== MPD-based audio with volume control

To allow Music Player Daemon (MPD)-based audio software to control the audio board's built in volume, you might need to change the file /etc/mpd.conf to support the correct AlsaMixer name.

This can be achieved by ensuring the 'Audio output' section of /etc/mpd.conf has the 'mixer_control'
line. Below is an example for the Texas Instruments-based boards (DAC
PRO/DAC{plus}/DigiAMP{plus}):


audio_output {
type "alsa"
name "ALSA Device"
mixer_control "Digital"

}


Documentation Asciidoc Accessories Audio Introduction (`documentation/asciidoc/accessories/audio/introduction.adoc`)

== Overview

Raspberry Pi Audio Boards bring high quality audio to your existing hi-fi or Raspberry Pi-based equipment and projects. We offer four different Hardware Attached on Top (HAT) options that will fit any Raspberry Pi using the 40-pin GPIO header.

Each board has a specific purpose and set of features. The highest audio quality playback is available from our DAC PRO, DAC{plus} and DigiAMP{plus} boards, which support up to full HD audio (192 kHz); while the Codec Zero supports up to HD audio (96 kHz) and includes a built-in microphone, making it ideal for compact projects.

=== Features at a glance

[cols="2,1,1,1,1,1,1,1,1,1"]
|===
| | Line out | Balanced out | Stereo speakers | Mono speaker | Headphones | Aux in | Aux out | Ext mic | Built-in mic

| DAC Pro ^| ✓ ^| ✓ | | ^| ✓ | | | |
| DAC{plus} ^| ✓ | | | ^| ✓ | | | |
| DigiAmp{plus} | | ^| ✓ | | | | | |
| Codec Zero | | | ^| ✓ | ^| ✓ ^| ✓ ^| ✓ ^| ✓
|===

Line out:: A double phono/RCA connector, normally red and white in colour. This output is a variable
analogue signal (0-2V RMS) and can connect to your existing hi-fi (pre-amp or amplifier), or can be used
to drive active speakers which have their own amplifier built in.
Balanced out:: An XLR connector, normally a three-pin male connector. This is used in a studio set-up, and in some
high-end hi-fi systems. It can also be used to drive active monitor speakers like those used at clubs or on
stage directed towards the DJ or performers.
Stereo speakers:: Two sets of screw terminals for 2 × 25 W speakers. These are for traditional hi-fi speakers without built-in amplification. These are known as passive speakers.
Mono speaker:: A screw terminal for a single 1.2 W speaker, as found in a transistor radio or similar.
Headphones:: A 3.5 mm jack socket delivering stereo audio for a set of headphones. The headphone amplifiers on the Raspberry Pi DAC boards can drive up to 80/90 Ω impedance headphones.
Aux in:: A double Phono/RCA connector or 3.5 mm socket. Accepts analogue audio in up to 1V RMS. This can be used to record audio from a variable analogue source such as a mobile phone, MP3 player or similar.
Aux out:: A double Phono/RCA connector or 3.5 mm socket. Delivers analogue audio out up to 1V RMS. This can be used to feed audio into an amplifier at a reduced volume compared to Line out.
Ext mic:: A 3.5 mm socket for use with an external electret microphone. The built-in MEMS microphone on the Codec Zero is automatically disabled when the external Mic in connector is used.


Documentation Asciidoc Accessories Audio Update Firmware (`documentation/asciidoc/accessories/audio/update-firmware.adoc`)

== Updating your firmware

Raspberry Pi Audio Boards use an EEPROM that contains information that is used by the host Raspberry Pi device to select the appropriate driver at boot time. This information is programmed into the EEPROM during manufacture. There are some circumstances where the end user might want to update the EEPROM contents: this can be done from the command line.

IMPORTANT: Before proceeding, update the version of Raspberry Pi OS running on your Raspberry Pi to the latest version.

=== The EEPROM write-protect link

During the programming process you will need to connect the two pads shown in the red box with a wire to pull down the EEPROM write-protect link.

image::images/write_protect_tabs.jpg[width="80%"]

NOTE: In some cases, the two pads might already have a 0 Ω resistor fitted to bridge the write-protect link, as illustrated in the picture of the Codec Zero board.

=== Program the EEPROM

When the write-protect line has been pulled down, the EEPROM can be programmed.

First install the utilities and then run the programmer. Open up a terminal window and type the following:

[source,console]

$ sudo apt update $ sudo apt install rpi-audio-utils $ sudo rpi-audio-flash

After starting, you will see a warning screen.

image::images/firmware-update/warning.png[]

Select Yes to proceed. You see a menu where you can select your hardware.

image::images/firmware-update/select.png[]

NOTE: If no HAT is present, or if the connected HAT is not a Raspberry Pi Audio board, you will be presented with an error screen. If the firmware has already been updated on the board, a message will be displayed informing you that you do not have to continue.

After selecting the hardware, a screen will display while the new firmware is flashed to the HAT.

image::images/firmware-update/flashing.png[]

Afterwards a screen will display telling you that the new firmware has installed.

image::images/firmware-update/flashed.png[]

NOTE: If the firmware fails to install correctly, you will see an error screen. Try removing and reseating the HAT, then flash the firmware again.


Documentation Asciidoc Accessories Build Hat Compat (`documentation/asciidoc/accessories/build-hat/compat.adoc`)

== Device Compatibility

The Build HAT library supports all the LEGO® Technic™ devices included in the SPIKE™ Portfolio, along with those from the LEGO® Mindstorms Robot Inventor kit and other devices that use a PoweredUp connector.

IMPORTANT: The product code for the SPIKE™ Prime Expansion Set that includes the Maker Plate is 45681. The original Expansion Set is 45680 and does not include the Maker Plate.

[cols="2,2,1,1,1,1,1,3,1,1,1,1", width="100%", options="header"]
|===
| Description | Colour | LEGO Item Number | Supported in FW | Supported in Python | Alt Number | BrickLink | Available In | Set Numbers | Class | Type | Device ID

| Large Angular Motor | White/Cyan | 45602 | Yes | Yes | 45602 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=54675c01[Link] | SPIKE Prime Set, SPIKE Prime Expansion Set | 45678, 45680 | Motor | Active | 31

| Medium Angular Motor | White/Cyan | 45603 | Yes | Yes | 45603 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=54696c01[Link] | SPIKE Prime Set | 45678 | Motor | Active | 30

| Medium Angular Motor | White/Grey | 6299646, 6359216, 6386708 | Yes | Yes | 436655 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=54696c01[Link] | Mindstorms Robot Inventor | 51515 | Motor | Active | 4B

| Small Angular Motor | White/Cyan | 45607, 6296520 | Yes | Yes | | https://www.bricklink.com/v2/catalog/catalogitem.page?P=68488c01[Link] | SPIKE Essentials Set | | Motor | Active | 41

| Light/Colour sensor | White/Black | 6217705 | Yes | Yes | | https://www.bricklink.com/v2/catalog/catalogitem.page?P=37308c01[Link] | SPIKE Prime Set, SPIKE Prime Expansion Set, Mindstorms Robot Inventor, SPIKE Essentials | 45678, 45680, 51515 | ColorSensor | Active | 3D

| Distance Sensor | White/Black | 6302968 | Yes | Yes | | https://www.bricklink.com/v2/catalog/catalogitem.page?P=37316c01[Link] | SPIKE Prime Set, Mindstorms Robot Inventor | 45678, 51515 | DistanceSensor | Active | 3E

| System medium motor | White/Grey | 45303, 6138854, 6290182, 6127110 | Yes | Yes | | https://www.bricklink.com/v2/catalog/catalogitem.page?P=21980[Link] | Wedo 2.0, LEGO Ideas Piano, App controlled Batmobile | 76112 | | Passive | 1

| Force Sensor | White/Black | 6254354 | Yes | Yes | 45606 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=37312c01[Link] | SPIKE Prime Set | 45678 | ForceSensor | Active | 3F

| 3×3 LED | White/Cyan | 45608, 6297023 | Yes | Yes | | https://www.bricklink.com/v2/catalog/catalogitem.page?P=47592c01[Link] | SPIKE Essentials | | Matrix | Active | 40

| System train motor | Black | 88011 | Yes | Yes | 28740, 88011-1 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0896c01[Link] | Cargo Train, Disney Train and Station, Passenger Train | | | Passive | 2

| PoweredUp LED lights | Black | 88005 | Yes | | | https://www.bricklink.com/v2/catalog/catalogitem.page?P=22168c01[Link] | | | | Passive | 8

| Medium linear motor | White/Grey | 88008 | Yes | Yes | 26913, 88008-1 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0893c01[Link] | Boost, Droid Commander | | Motor | Active | 26

| Technic large motor | Grey/Grey | 88013 | Yes | Yes | 22169 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0959c01[Link] | | | | Active | 2E

| Technic XL motor | Grey/Grey | 88014 | Yes | Yes | 22172, 88014 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0960c01[Link] | | | | Active | 2F

| Colour + distance sensor | White/Grey | 88007 | Partial | ? | 26912 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0891c01[Link] | | | | Active | 25

| WeDo 2.0 Motion sensor | White/Grey | 45304, 6138855 | | | 5003423-1 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=43718[Link] | | | | Active | 35

| WeDo 2.0 Tilt sensor | White/Grey | 45305, 6138856 | | | 5003423-1 | https://www.bricklink.com/v2/catalog/catalogitem.page?P=14618[Link] | | | | Active | 34

|===


Documentation Asciidoc Accessories Build Hat Introduction (`documentation/asciidoc/accessories/build-hat/introduction.adoc`)

[[about-build-hat]]
== About

The https://raspberrypi.com/products/build-hat[Raspberry Pi Build HAT] is an add-on board that connects to the 40-pin GPIO header of your Raspberry Pi, which was designed in collaboration with LEGO® Education to make it easy to control LEGO® Technic™ motors and sensors with Raspberry Pi computers.

WARNING: The Raspberry Pi Build HAT is not yet supported by Raspberry Pi OS Trixie. To use the Build HAT, install or stay on Raspberry Pi OS Bookworm for now.

image::images/build-hat.jpg[width="80%"]

NOTE: A full list of supported devices can be found in the xref:build-hat.adoc#device-compatibility[Device Compatibility] section.

It provides four connectors for LEGO® Technic™ motors and sensors from the SPIKE™ Portfolio. The available sensors include a distance sensor, a colour sensor, and a versatile force sensor. The angular motors come in a range of sizes and include integrated encoders that can be queried to find their position.

The Build HAT fits all Raspberry Pi computers with a 40-pin GPIO header, including, with the addition of a ribbon cable or other extension device, Keyboard-series devices. Connected LEGO® Technic™ devices can easily be controlled in Python, alongside standard Raspberry Pi accessories such as a camera module.

The Raspberry Pi Build HAT power supply (PSU), which is https://raspberrypi.com/products/build-hat-power-supply[available separately], is designed to power both the Build HAT and Raspberry Pi computer along with all connected LEGO® Technic™ devices.

image::images/psu.jpg[width="80%"]

The LEGO® Education SPIKE™ Prime Set 45678 and SPIKE™ Prime Expansion Set 45681, available separately from LEGO® Education resellers, include a collection of useful elements supported by the Build HAT.

NOTE: The HAT works with all 40-pin GPIO Raspberry Pi boards, including Zero-series devices. With the addition of a ribbon cable or other extension device, it can also be used with Keyboard-series devices.

  • Controls up to 4 LEGO® Technic™ motors and sensors included in the SPIKE™ Portfolio
  • Easy-to-use https://buildhat.readthedocs.io/[Python library] to control your LEGO® Technic™ devices
  • Fits onto any Raspberry Pi computer with a 40-pin GPIO header
  • On-board xref:../microcontrollers/microcontroller-chips.adoc[RP2040] microcontroller manages low-level control of LEGO® Technic™ devices
  • External 8V PSU https://raspberrypi.com/products/build-hat-power-supply[available separately] to power both Build HAT and Raspberry Pi

[NOTE]

The Build HAT cannot power Keyboard-series devices, since they do not support power supply over the GPIO headers.


== Further Resources

You can download documentation on the,

and full details of the Python Library documentation can also be found https://buildhat.readthedocs.io/[on ReadTheDocs]. You can find more information on the .NET library in the https://github.com/dotnet/iot/tree/main/src/devices/BuildHat[.NET IoT] Github repository.

You can also follow along with projects from the Raspberry Pi Foundation,


Documentation Asciidoc Accessories Build Hat Mech (`documentation/asciidoc/accessories/build-hat/mech.adoc`)

== Mechanical Drawings

Mechanical drawing of the Raspberry Pi Build HAT.

image::images/mech-build-hat.png[width="80%"]


Documentation Asciidoc Accessories Build Hat Net Brick (`documentation/asciidoc/accessories/build-hat/net-brick.adoc`)

=== Use the Build HAT from .NET

The Raspberry Pi Built HAT is referred to "Brick" in LEGO® parlance and you can talk directly to it from .NET using the https://pip.raspberrypi.com/documents/RP-008140-DS[Build HAT Serial Protocol].

You can create a brick object as below,

[source,csharp]

Brick brick = new("/dev/serial0");

but you need to remember to dispose of the brick at the end of your code.

[source,csharp]

brick.Dispose();

WARNING: If you don't call brick.Dispose() your program will not terminate.

If you want to avoid calling brick.Dispose at the end, then create your brick with the using statement:

[source,csharp]

using Brick brick = new("/dev/serial0");

In this case, when reaching the end of the program, your brick will be automatically disposed.

==== Display Build HAT information

You can gather the various software versions, the signature, and the input voltage:

[source,csharp]

var info = brick.BuildHatInformation; Console.WriteLine($"version: {info.Version}, firmware date: {info.FirmwareDate}, signature:"); Console.WriteLine($"{BitConverter.ToString(info.Signature)}"); Console.WriteLine($"Vin = {brick.InputVoltage.Volts} V");

NOTE: The input voltage is read only once at boot time and is not read again afterwards.

==== Getting sensors and motors details

The functions GetSensorType, GetSensor will allow you to retrieve any information on connected sensor.

[source,csharp]

SensorType sensor = brick.GetSensorType((SensorPort)i); Console.Write($"Port: {i} {(Brick.IsMotor(sensor) ? "Sensor" : "Motor")} type: {sensor} Connected: ");

In this example, you can as well use the IsMotor static function to check if the connected element is a sensor or a motor.

[source,csharp]

if (Brick.IsActiveSensor(sensor))
{
ActiveSensor activeSensor = brick.GetActiveSensor((SensorPort)i);
}
else
{
var passive = (Sensor)brick.GetSensor((SensorPort)i);
Console.WriteLine(passive.IsConnected);

}

ActiveSensor have a collection of advanced properties and functions allowing to understand every element of the sensor. It is also possible to call the primitive functions from the brick from them. This will allow you to select specific modes and do advance scenarios. While this is possible, motor and sensor classes have been created to make your life easier.

==== Events

Most sensors implements events on their special properties. You can simply subscribe to PropertyChanged and PropertyUpdated. The changed one will be fired when the value is changing while the updated one when there is a success update to the property. Depending on the modes used, some properties might be updated in the background all the time while some others occasionally.

You might be interested only when a colour is changing or the position of the motor is changing, using it as a tachometer. In this case, the PropertyChanged is what you need!

[source,csharp]

Console.WriteLine("Move motor on Port A to more than position 100 to stop this test.");
brick.WaitForSensorToConnect(SensorPort.PortA);
var active = (ActiveMotor)brick.GetMotor(SensorPort.PortA);
bool continueToRun = true;
active.PropertyChanged += MotorPropertyEvent;
while (continueToRun)
{
Thread.Sleep(50);
}

active.PropertyChanged -= MotorPropertyEvent;
Console.WriteLine($"Current position: {active.Position}, eventing stopped.");

void MotorPropertyEvent(object? sender, PropertyChangedEventArgs e)
{
Console.WriteLine($"Property changed: {e.PropertyName}");
if (e.PropertyName == nameof(ActiveMotor.Position))
{
if (((ActiveMotor)brick.GetMotor(SensorPort.PortA)).Position > 100)
{
continueToRun = false;
}
}

}

==== Wait for initialisation

The brick can take a long time before it initialises. A wait for a sensor to be connected has been implemented.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortB);

It does also take a CancellationToken if you want to implement advance features like warning the user after some time and retrying.


Documentation Asciidoc Accessories Build Hat Net Installing Software (`documentation/asciidoc/accessories/build-hat/net-installing-software.adoc`)

== Use the Build HAT from .NET

=== Install the .NET Framework

The .NET framework from Microsoft is not available through apt on Raspberry Pi. However, you can follow the https://docs.microsoft.com/en-us/dotnet/iot/deployment[official instructions] from Microsoft to install the .NET framework. Alternatively, there is a simplified https://www.petecodes.co.uk/install-and-use-microsoft-dot-net-5-with-the-raspberry-pi/[third party route] to get the .NET toolchain on to your Raspberry Pi.

WARNING: The installation script is run as root. Before running it, read it and make sure you understand what it is doing. If you're at all unsure, follow the https://docs.microsoft.com/en-us/dotnet/iot/deployment[official instructions] manually.

[source,console]

$ wget -O - https://raw.githubusercontent.com/pjgpetecodes/dotnet5pi/master/install.sh | sudo bash

After installing the .NET framework you can create your project:

[source,console]

$ dotnet new console --name buildhat

This creates a default program in the buildhat subdirectory, and we need to be in that directory in order to continue:

[source,console]

$ cd buildhat

You will now need to install the following nuget packages:

[source,console]

$ dotnet add package System.Device.Gpio --version 2.1.0 $ dotnet add package Iot.Device.Bindings --version 2.1.0

=== Run C# Code

You can run the program with the dotnet run command. Let's try it now to make sure everything works. It prints "Hello World!"

[source,console]

$ dotnet run Hello World!

(When instructed to "run the program" in the instructions that follow, rerun dotnet run)

=== Edit C# Code

In the instructions below, you will be editing the file buildhat/Program.cs, the C# program which was generated when you ran the above commands.

Any text editor will work to edit C# code, including Geany, the IDE/Text Editor that comes pre-installed. https://code.visualstudio.com/docs/setup/raspberry-pi/[Visual Studio Code] (often called "VS Code") is also a popular alternative.


Documentation Asciidoc Accessories Build Hat Net Motors (`documentation/asciidoc/accessories/build-hat/net-motors.adoc`)

=== Use Motors from .NET

There are two types of motors, the passive ones and the active ones. Active motors will provide detailed position, absolute position and speed while passive motors can only be controlled with speed.

A common set of functions to control the speed of the motors are available. There are 2 important ones: SetPowerLimit and SetBias:

[source,csharp]

train.SetPowerLimit(1.0); train.SetBias(0.2);

The accepted values are only from 0.0 to 1.0. The power limit is a convenient ay to reduce in proportion the maximum power.

The bias value sets for the current port which is added to positive motor drive values and subtracted from negative motor drive values. This can be used to compensate for the fact that most DC motors require a certain amount of drive before they will turn at all.

The default values when a motor is created is 0.7 for the power limit and 0.3 for the bias.

==== Passive Motors

.Train motor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0896c01[Image from Bricklink]
image::images/train-motor.png[Train motor,width="60%"]

The typical passive motor is a train and older Powered Up motors. The Speed property can be set and read. It is the target and the measured speed at the same time as those sensors do not have a way to measure them. The value is from -100 to +100.

Functions to control Start, Stop and SetSpeed are also available. Here is an example of how to use it:

[source,csharp]

Console.WriteLine("This will run the motor for 20 seconds incrementing the PWM");
train.SetPowerLimit(1.0);
train.Start();
for (int i = 0; i < 100; i++)
{
train.SetSpeed(i);
Thread.Sleep(250);
}

Console.WriteLine("Stop the train for 2 seconds"); train.Stop(); Thread.Sleep(2000); Console.WriteLine("Full speed backward for 2 seconds"); train.Start(-100); Thread.Sleep(2000); Console.WriteLine("Full speed forward for 2 seconds"); train.Start(100); Thread.Sleep(2000); Console.WriteLine("Stop the train"); train.Stop();

NOTE: When the train is started, you can adjust the speed and the motor adjusts accordingly.

==== Active Motors

.Active motor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0960c01[Image from Bricklink]
image::images/active-motor.png[Active motor,width="60%"]

Active motors have Speed, AbsolutePosition, Position and TargetSpeed as special properties. They are read continuously even when the motor is stopped.

The code snippet shows how to get the motors, start them and read the properties:

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA);
brick.WaitForSensorToConnect(SensorPort.PortD);
var active = (ActiveMotor)brick.GetMotor(SensorPort.PortA);
var active2 = (ActiveMotor)brick.GetMotor(SensorPort.PortD);
active.Start(50);
active2.Start(50);
// Make sure you have an active motor plug in the port A and D
while (!Console.KeyAvailable)
{
Console.CursorTop = 1;
Console.CursorLeft = 0;
Console.WriteLine($"Absolute: {active.AbsolutePosition} ");
Console.WriteLine($"Position: {active.Position} ");
Console.WriteLine($"Speed: {active.Speed} ");
Console.WriteLine();
Console.WriteLine($"Absolute: {active2.AbsolutePosition} ");
Console.WriteLine($"Position: {active2.Position} ");
Console.WriteLine($"Speed: {active2.Speed} ");
}

active.Stop(); active2.Stop();

NOTE: Don't forget to start and stop your motors when needed.

Advance features are available for active motors. You can request to move for seconds, to a specific position, a specific absolute position. Here are couple of examples:

[source,csharp]

// From the previous example, this will turn the motors back to their initial position: active.TargetSpeed = 100; active2.TargetSpeed = 100; // First this motor and will block the thread active.MoveToPosition(0, true); // Then this one and will also block the thread active2.MoveToPosition(0, true);

Each function allow you to block or not the thread for the time the operation will be performed. Note that for absolute and relative position moves, there is a tolerance of few degrees.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA); var active = (ActiveMotor)brick.GetMotor(SensorPort.PortA); active.TargetSpeed = 70; Console.WriteLine("Moving motor to position 0"); active.MoveToPosition(0, true); Console.WriteLine("Moving motor to position 3600 (10 turns)"); active.MoveToPosition(3600, true); Console.WriteLine("Moving motor to position -3600 (so 20 turns the other way"); active.MoveToPosition(-3600, true); Console.WriteLine("Moving motor to absolute position 0, should rotate by 90°"); active.MoveToAbsolutePosition(0, PositionWay.Shortest, true); Console.WriteLine("Moving motor to position 90"); active.MoveToAbsolutePosition(90, PositionWay.Shortest, true); Console.WriteLine("Moving motor to position 179"); active.MoveToAbsolutePosition(179, PositionWay.Shortest, true); Console.WriteLine("Moving motor to position -180"); active.MoveToAbsolutePosition(-180, PositionWay.Shortest, true); active.Float();

You can place the motor in a float position, meaning, there are no more constraints on it. This is a mode that you can use when using the motor as a tachometer, moving it and reading the position. If you still have constraints on the motors, you might not be able to move it.


Documentation Asciidoc Accessories Build Hat Net Sensors (`documentation/asciidoc/accessories/build-hat/net-sensors.adoc`)

=== Use Sensors from .NET

Like for motors, you have active and passive sensors. Most recent sensors are active. The passive one are lights and simple buttons. Active ones are distance or colour sensors, as well as small 3×3 pixel displays.

==== Button/Touch Passive Sensor

The button/touch passive sensor have one specific property IsPressed. The property is set to true when the button is pressed. Here is a complete example with events:

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA);
var button = (ButtonSensor)brick.GetSensor(SensorPort.PortA);
bool continueToRun = true;
button.PropertyChanged += ButtonPropertyEvent;
while (continueToRun)
{
// You can do many other things here
Thread.Sleep(50);
}

button.PropertyChanged -= ButtonPropertyEvent;
Console.WriteLine($"Button has been pressed, we're stopping the program.");
brick.Dispose();

void ButtonPropertyEvent(object? sender, PropertyChangedEventArgs e)
{
Console.WriteLine($"Property changed: {e.PropertyName}");
if (e.PropertyName == nameof(ButtonSensor.IsPressed))
{
continueToRun = false;
}

}

==== Passive Light

.Passive light, https://www.bricklink.com/v2/catalog/catalogitem.page?P=22168c01[Image from Bricklink]
image::images/passive-light.png[Passive light, width="60%"]

The passive light are the train lights. They can be switched on and you can controlled their brightness.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA); var light = (PassiveLight)brick.GetSensor(SensorPort.PortA); // Brightness 50% light.On(50); Thread.Sleep(2000); // 70% Brightness light.Brightness = 70; Thread.Sleep(2000); // Switch light off light.Off()

==== Active Sensor

The active sensor class is a generic one that all the active sensor inherit including active motors. They contains a set of properties regarding how they are connected to the Build HAT, the modes, the detailed Combi modes, the hardware, software versions and a specific property called ValueAsString. The value as string contains the last measurement as a collection of strings. A measurement arrives like P0C0: +23 -42 0, the enumeration will contains P0C0:, +23, -42 and 0. This is made so if you are using advance modes and managing yourself the Combi modes and commands, you'll be able to get the measurements.

All active sensor can run a specific measurement mode or a Combi mode. You can setup one through the advance mode using the SelectModeAndRead and SelectCombiModesAndRead functions with the specific mode(s) you'd like to continuously have. It is important to understand that changing the mode or setting up a new mode will stop the previous mode.

The modes that can be combined in the Combi mode are listed in the CombiModes property. Al the properties of the sensors will be updated automatically when you'll setup one of those modes.

==== WeDo Tilt Sensor

.WeDo Tilt sensor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=20841[Image from Bricklink]
image::images/wedo-tilt.png[WeDo Tilt sensor, width="60%"]

WeDo Tilt Sensor has a special Tilt property. The type is a point with X is the X tilt and Y is the Y tilt. The values goes from -45 to + 45, they are caped to those values and represent degrees.

You can set a continuous measurement for this sensor using the ContinuousMeasurement property.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA);
var tilt = (WeDoTiltSensor)brick.GetSensor(SensorPort.PortA);
tilt.ContinuousMeasurement = true;
Point tiltValue;
while(!console.KeyAvailable)
{
tiltValue = tilt.Tilt;
console.WriteLine($"Tilt X: {tiltValue.X}, Tilt Y: {tiltValue.Y}");
Thread.Sleep(200);

}

==== WeDoDistance Sensor

.WeDo Distance sensor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=20844[Image from Bricklink]
image::images/wedo-distance.png[WeDo Distance sensor, width="60%"]

WeDo Distance Sensor gives you a distance in millimetres with the Distance property.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA);
var distance = (WeDoDistanceSensor)brick.GetSensor(SensorPort.PortA);
distance.ContinuousMeasurement = true;
while(!console.KeyAvailable)
{
console.WriteLine($"Distance: {distance.Distance} mm");
Thread.Sleep(200);

}

==== SPIKE Prime Force Sensor

.Spike Force Sensor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=37312c01[Image from Bricklink]
image::images/spike-force.png[spike force sensor, width="60%"]

This force sensor measure the pressure applies on it and if it is pressed. The two properties can be access through Force and IsPressed properties.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA);
var force = (ForceSensor)brick.GetSensor(SensorPort.PortA);
force.ContinuousMeasurement = true;
while(!force.IsPressed)
{
console.WriteLine($"Force: {force.Force} N");
Thread.Sleep(200);

}

==== SPIKE Essential 3×3 Colour Light Matrix

.Spike 3×3 matrix, https://www.bricklink.com/v2/catalog/catalogitem.page?P=47592c01[Image from Bricklink]
image::images/3x3matrix.png[spike 3×3 matrix, width="60%"]

This is a small 3×3 display with 9 different LEDs that can be controlled individually. The class exposes functions to be able to control the screen. Here is an example using them:

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA);
var matrix = (ColorLightMatrix)brick.GetSensor(SensorPort.PortA);
for(byte i = 0; i < 10; i++)
{
// Will light every led one after the other like a progress bar
matrix.DisplayProgressBar(i);
Thread.Sleep(1000);
}

for(byte i = 0; i < 11; i++)
{
// Will display the matrix with the same color and go through all of them
matrix.DisplayColor((LedColor)i);
Thread.Sleep(1000);
}

Span brg = stackalloc byte[9] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Span col = stackalloc LedColor[9] { LedColor.White, LedColor.White, LedColor.White, LedColor.White, LedColor.White, LedColor.White, LedColor.White, LedColor.White, LedColor.White }; // Shades of grey matrix.DisplayColorPerPixel(brg, col);

==== SPIKE Prime Colour Sensor and Colour and Distance Sensor

SPIKE colour sensor:

.Spike colour sensor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=37308c01[Image from Bricklink]
image::images/spike-color.png[spike color sensor, width="60%"]

Colour and distance sensor:

.Color distance sensor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=bb0891c01[Image from Bricklink]
image::images/color-distance.png[Colour distance sensor, width="60%"]

Those colour sensor has multiple properties and functions. You can get the Color, the ReflectedLight and the AmbiantLight.

On top of this, the Colour and Distance sensor can measure the Distance and has an object Counter. It will count automatically the number of objects which will go in and out of the range. This does allow to count objects passing in front of the sensor. The distance is limited from 0 to 10 centimetres.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortC);

var colorSensor = (ColorAndDistanceSensor)brick.GetActiveSensor(SensorPort.PortC);
while (!Console.KeyAvailable)
{
var colorRead = colorSensor.GetColor();
Console.WriteLine($"Color: {colorRead}");
var reflected = colorSensor.GetReflectedLight();
Console.WriteLine($"Reflected: {reflected}");
var ambiant = colorSensor.GetAmbiantLight();
Console.WriteLine($"Ambiant: {ambiant}");
var distance = colorSensor.GetDistance();
Console.WriteLine($"Distance: {distance}");
var counter = colorSensor.GetCounter();
Console.WriteLine($"Counter: {counter}");
Thread.Sleep(200);

}

NOTE: For better measurement, it is not recommended to change the measurement mode in a very fast way, the colour integration might not be done in a proper way. This example gives you the full spectrum of what you can do with the sensor. Also, this class do not implement a continuous measurement mode. You can setup one through the advance mode using the SelectModeAndRead function with the specific mode you'd like to continuously have. It is important to understand that changing the mode or setting up a new mode will stop the previous mode.

==== SPIKE Prime Ultrasonic Distance Sensor

.Spike distance sensor, https://www.bricklink.com/v2/catalog/catalogitem.page?P=37316c01[Image from Bricklink]
image::images/spike-distance.png[Spike distance sensor, width="60%"]

This is a distance sensor and it does implement a Distance property that will give the distance in millimetre. A ContinuousMeasurement mode is also available on this one.

[source,csharp]

brick.WaitForSensorToConnect(SensorPort.PortA);
var distance = (UltrasonicDistanceSensor)brick.GetSensor(SensorPort.PortA);
distance.ContinuousMeasurement = true;
while(!console.KeyAvailable)
{
console.WriteLine($"Distance: {distance.Distance} mm");
Thread.Sleep(200);

}


Documentation Asciidoc Accessories Build Hat Preparing Build Hat (`documentation/asciidoc/accessories/build-hat/preparing-build-hat.adoc`)

== Prepare your Build HAT

NOTE: Before starting to work with your Raspberry Pi Build HAT, xref:../computers/getting-started.adoc#desktop-setup[set up] your Raspberry Pi and xref:../computers/getting-started.adoc#install[install] the latest version of the operating system using https://www.raspberrypi.com/downloads/[Raspberry Pi Imager].

Attach 9 mm spacers to the bottom of the board. Seat the Raspberry Pi Build HAT onto your Raspberry Pi. Make sure you put it on the right way up. Unlike other HATs, all the components are on the bottom, leaving room for a breadboard or LEGO® elements on top.

video::images/fitting-build-hat.webm[width="80%"]

=== Access the GPIO Pins

If you want to access the GPIO pins of the Raspberry Pi, you can add an optional tall header and use 15 mm spacers.

image::images/tall-headers.jpg[width="80%"]

The following pins are used by the Build HAT itself; don't connect anything to them.

[[table_passive_ids]]
[cols="^1,^1,^1", width="75%", options="header"]
|===
| GPIO| Use | Status
| GPIO0/1 | ID prom |
| GPIO4| Reset |
| GPIO14| Tx |
| GPIO15| Rx |
| GPIO16 | RTS | unused
| GPIO17 | CTS | unused
|===

=== Set up your Raspberry Pi

After the Raspberry Pi has booted, open the Control Centre tool by selecting the Raspberry Menu button and then selecting Preferences > Control Centre.

Select the Interfaces tab and adjust the serial settings as shown in the following image:

image::images/setting-up.png["The Interfaces tab. SSH, VNC, and Serial Port are enabled. The rest of the options are not enabled.", width="50%"]

==== Use your Raspberry Pi headless

If you are running your Raspberry Pi headless and using raspi-config, select "Interface Options" from the first menu.

image::images/raspi-config-1.png[width="70%"]

Then "P6 Serial Port".

image::images/raspi-config-2.png[width="70%"]

Disable the serial console:

image::images/raspi-config-3.png[width="70%"]

And enable the serial port hardware.

image::images/raspi-config-4.png[width="70%"]

The final settings look like this.

image::images/raspi-config-5.png[width="70%"]

You will need to reboot at this point if you have made any changes.

=== Power the Build HAT

Connect an external power supply. We recommend the https://raspberrypi.com/products/build-hat-power-supply[official Raspberry Pi Build HAT power supply]. However, any reliable +8V±10% power supply capable of supplying 48 W through a DC 5521 centre positive barrel connector (5.5 mm × 2.1 mm × 11 mm) can power the Build HAT. You don't need to connect an additional USB power supply to the Raspberry Pi unless you are using a Keyboard-series device.

[NOTE]

The Build HAT cannot power Keyboard-series devices, since they do not support power supply over the GPIO headers.

video::images/powering-build-hat.webm[width="80%"]

[NOTE]

The LEGO® Technic™ motors are very powerful; so to drive them you'll need an external 8V power supply. If you want to read from motor encoders and the SPIKE™ force sensor, you can power your Raspberry Pi and Build HAT the usual way, through your Raspberry Pi device's USB power socket. The SPIKE™ colour and distance sensors, like the motors, require an https://raspberrypi.com/products/build-hat-power-supply[external power supply].

You have the choice to use Build HAT with Python or .NET.


Documentation Asciidoc Accessories Build Hat Py Installing Software (`documentation/asciidoc/accessories/build-hat/py-installing-software.adoc`)

== Use the Build HAT from Python

=== Install the Build HAT Python Library

To install the Build HAT Python library, open a terminal window and run the following command:

[source,console]

$ sudo apt install python3-build-hat

For more information about the Build HAT Python Library see https://buildhat.readthedocs.io/[ReadTheDocs].


Documentation Asciidoc Accessories Build Hat Py Motors (`documentation/asciidoc/accessories/build-hat/py-motors.adoc`)

=== Use Motors from Python

There are xref:build-hat.adoc#device-compatibility[a number of motors] that work with the Build HAT.

==== Connect a Motor

Connect a motor to port A on the Build HAT. The LPF2 connectors need to be inserted the correct way up. If the connector doesn't slide in easily, rotate by 180 degrees and try again.

video::images/connect-motor.webm[width="80%"]

==== Work with Motors

Start the https://thonny.org/[Thonny IDE]. Add the program code below:

[source,python]

from buildhat import Motor

motor_a = Motor('A')

motor_a.run_for_seconds(5)

Run the program by clicking the play/run button. If this is the first time you're running a Build HAT program since the Raspberry Pi has booted, there is a few seconds pause while the firmware is copied across to the board. The red LED extinguishes and the green LED illuminates. Subsequent executions of a Python program don't require this pause.

video::images/blinking-light.webm[width="80%"]

Your motor turns clockwise for 5 seconds.

video::images/turning-motor.webm[width="80%"]

Change the final line of your program and re-run.

[source,python]

motor_a.run_for_seconds(5, speed=50)

The motor now turns faster. Make another change:

[source,python]

motor_a.run_for_seconds(5, speed=-50)

The motor turns in the opposite (anti-clockwise) direction

Create a new program by clicking on the plus button in Thonny. Add the code below:

[source,python]

from buildhat import Motor

motor_a = Motor('A')

while True:
print("Position: ", motor_a.get_aposition())


Run the program. Grab the motor and turn the shaft. The numbers printed in the Thonny REPL change.


Documentation Asciidoc Accessories Build Hat Py Sensors (`documentation/asciidoc/accessories/build-hat/py-sensors.adoc`)

=== Use Sensors from Python

There is a xref:build-hat.adoc#device-compatibility[large range of sensors] that work with the Build HAT.

==== Work with Sensors

Connect a Colour sensor to port B on the Build HAT, and a Force sensor to port C.

NOTE: If you're not intending to drive a motor, then you don't need an external power supply and you can use a standard USB power supply for your Raspberry Pi.

Create another new program:

[source,python]

from signal import pause
from buildhat import ForceSensor, ColorSensor

button = ForceSensor('C')
cs = ColorSensor('B')

def handle_pressed(force):
cs.on()
print(cs.get_color())

def handle_released(force):
cs.off()

button.when_pressed = handle_pressed button.when_released = handle_released pause()

Run it and hold a coloured object (LEGO® elements are ideal) in front of the colour sensor and press the Force sensor plunger. The sensor's LED switches on and the Thonny REPL displays the name of the closest colour.


Documentation Asciidoc Accessories Bumper About (`documentation/asciidoc/accessories/bumper/about.adoc`)

== About

.The Raspberry Pi Bumper for Raspberry Pi 5
image::images/bumper.jpg[width="80%"]

The Raspberry Pi Bumper for Raspberry Pi 5 is a snap-on silicone cover that protects
the bottom and edges of the board. When attached, the mounting holes of the Raspberry Pi remain accessible through the bumper.

The Bumper is only compatible with Raspberry Pi 5.

== Assembly instructions

.Assembling the bumper
image::images/assembly.png[width="80%"]

To attach the Raspberry Pi Bumper to your Raspberry Pi:

. Turn off your Raspberry Pi and disconnect the power cable.
. Remove the SD card from the SD card slot of your Raspberry Pi.
. Align the bumper with the board.
. Press the board gently but firmly into the bumper, taking care to avoid contact between the bumper and any of the board’s components.
. Insert your SD card back into the SD card slot of your Raspberry Pi.
. Reconnect your Raspberry Pi to power.

To remove the Raspberry Pi Bumper from your Raspberry Pi:

. Turn off your Raspberry Pi and disconnect the power cable.
. Remove the SD card from the SD card slot of your Raspberry Pi.
. Gently but firmly peel the bumper away from the board, taking care to avoid contact between the bumper and any of the board’s components.
. Insert your SD card back into the SD card slot of your Raspberry Pi.
. Reconnect your Raspberry Pi to power.


Documentation Asciidoc Accessories Camera Advanced (`documentation/asciidoc/accessories/camera/advanced.adoc`)

:figure-caption!:
== Advanced information

This section provides information for advanced users.

=== Mechanical drawings and schematics

Mechanical drawings and schematics are available on the Product Information Portal at the following locations:

NOTE: Board dimensions and mounting-hole positions for Camera Module 3 are identical to Camera Module 2. However, due to changes in the size and position of the sensor module, it isn't mechanically compatible with the camera lid for the Raspberry Pi Zero case.

In addition, the following figure shows the schematic for the Raspberry Pi CSI camera connector.

=== Pinout information

Use the information in this section to understand the function of the pins in the camera connectors.

==== Locating pin 1

The location of pin 1 on an FPC connector depends on the hardware.

The following descriptions assume you're holding your Raspberry Pi board with the chip and connectors facing up and the Raspberry Pi logo in the correct orientation. For Raspberry Pi Zero boards without the logo on the top side, orient the board with the GPIO along the edge furthest away from you.

** On Raspberry Pi flagship models and Raspberry Pi Zero devices, pin 1 is the pin furthest from you and closest to the GPIO header.
** On Raspberry Pi Compute Module IO boards, pin 1 is marked with a small circle or dot depending on the model.

When holding the Raspberry Pi camera board with the lens facing down and the connector facing to your right, pin 1 is the pin closest to you.

==== Camera connector pinout (15-Pin)

This is the pinout of the 15-pin Camera Serial Interface (CSI) connector used on flagship Raspberry Pi models prior to Raspberry Pi 5.
The connector is compatible with Amphenol SFW15R-2STE1LF.

Signal direction is specified from the perspective of the Raspberry Pi board.
The I2C lines (SCL and SDA) are pulled up to 3.3 V on the Raspberry Pi board.

The function and direction of the GPIO lines depend on the specific Camera Module in use. Typically, CAM_IO0 is used as an active-high power enable. Some products don't include CAM_IO1.

|===
| Pin | Name | Description | Direction / Type

| 1 | GND | - | Ground
| 2 | CAM_DN0 | D-PHY lane 0 (negative) | Input, D-PHY
| 3 | CAM_DP0 | D-PHY lane 0 (positive) | Input, D-PHY
| 4 | GND | - | Ground
| 5 | CAM_DN1 | D-PHY lane 1 (negative) | Input, D-PHY
| 6 | CAM_DP1 | D-PHY lane 1 (positive) | Input, D-PHY
| 7 | GND | - | Ground
| 8 | CAM_CN | D-PHY Clock (negative) | Input, D-PHY
| 9 | CAM_CP | D-PHY Clock (positive) | Input, D-PHY
|10 | GND | - | Ground
|11 | CAM_IO0 | GPIO (for example, Power-Enable) | Bidirectional, 3.3 V
|12 | CAM_IO1 | GPIO (for example, Clock, LED) | Bidirectional, 3.3 V
|13 | SCL | I2C Clock | Bidirectional, 3.3 V
|14 | SDA | I2C Data | Bidirectional, 3.3 V
|15 | 3V3 | 3.3 V Supply | Output
|===

.Schematic of the Raspberry Pi CSI camera connector.
image:images/RPi-S5-conn.png[camera connector, width="65%"]

==== Camera connector pinout (22-Pin)

This is the pinout of the 22-pin Camera Serial Interface (CSI) connector used on the Raspberry Pi Zero series, the Compute Module IO boards, and flagship models since Raspberry Pi 5.
The connector is compatible with Amphenol F32Q-1A7H1-11022.

Signal direction is specified from the perspective of the Raspberry Pi board.
The I2C lines (SCL and SDA) are pulled up to 3.3 V on the Raspberry Pi board.

The function and direction of the GPIO lines depend on the specific Camera Module in use. Typically, CAM_IO0 is used as an active-high power enable. Some products don't include CAM_IO1.

|===
| Pin | Name | Description | Direction / Type

| 1 | GND | - | Ground
| 2 | CAM_DN0 | D-PHY lane 0 (negative) | Input, D-PHY
| 3 | CAM_DP0 | D-PHY lane 0 (positive) | Input, D-PHY
| 4 | GND | - | Ground
| 5 | CAM_DN1 | D-PHY lane 1 (negative) | Input, D-PHY
| 6 | CAM_DP1 | D-PHY lane 1 (positive) | Input, D-PHY
| 7 | GND | - | Ground
| 8 | CAM_CN | D-PHY Clock (negative) | Input, D-PHY
| 9 | CAM_CP | D-PHY Clock (positive) | Input, D-PHY
|10 | GND | - | Ground
|11 | CAM_DN2 | D-PHY lane 2 (negative) | Input, D-PHY
|12 | CAM_DP2 | D-PHY lane 2 (positive) | Input, D-PHY
|13 | GND | - | Ground
|14 | CAM_DN3 | D-PHY lane 3 (negative) | Input, D-PHY
|15 | CAM_DP3 | D-PHY lane 3 (positive) | Input, D-PHY
|16 | GND | - | Ground
|17 | CAM_IO0 | GPIO (for example, Power-Enable) | Bidirectional, 3.3 V
|18 | CAM_IO1 | GPIO (for example, Clock, LED) | Bidirectional, 3.3 V
|19 | GND | - | Ground
|20 | SCL | I2C Clock | Bidirectional, 3.3 V
|21 | SDA | I2C Data | Bidirectional, 3.3 V
|22 | 3V3 | 3.3 V Supply | Output
|===


Documentation Asciidoc Accessories Camera Cm2 (`documentation/asciidoc/accessories/camera/cm2.adoc`)

[[camera-module-2]]
== Camera Module 2

This 8-megapixel camera is built around the Sony IMX219 sensor with a resolution of 3280 × 2464 pixels. It has adjustable focus and can record an exposure time of up to 11.76 seconds.

Camera Module 2 comes in the following variants:

For detailed information about the hardware characteristics and capabilities of this camera, see the xref:../accessories/camera.adoc#hardware-specification[hardware specifications].


Documentation Asciidoc Accessories Camera Cm3 (`documentation/asciidoc/accessories/camera/cm3.adoc`)

[[camera-module-3]]
== Camera Module 3

This https://www.raspberrypi.com/products/camera-module-3/[12-megapixel camera] is built around the Sony IMX708 sensor with a resolution of 4608 × 2592 pixels. It has https://www.raspberrypi.com/news/new-autofocus-camera-modules/[powered autofocus] and can record an exposure time of up to 112 seconds.

Camera Module 3 comes in the following variants:

  • Standard, normal field of view (FoV)
  • Standard, wide FoV
  • NoIR, normal FoV
  • NoIR, wide FoV

The standard variants capture visible light only; infrared light is filtered out. The NoIR variants don't have an infrared filter; they capture both visible light and infrared light. Use a NoIR camera with infrared lighting to see in the dark or use it with the included square of blue gel to monitor the health of green plants.

All of these variants are also available for the standalone https://www.raspberrypi.com/products/camera-module-3-sensor-assembly/[Camera Module 3 sensor assembly].

.Camera Module 3 (left) and Camera Module 3 Wide (right)
image::images/cm3.jpg[Camera Module 3 normal and wide angle]

.Camera Module 3 NoIR (left) and Camera Module 3 NoIR Wide (right)
image::images/cm3_noir.jpg[Camera Module 3 NoIR normal and wide angle]

For detailed information about the hardware characteristics and capabilities of this camera, see the xref:../accessories/camera.adoc#hardware-specification[hardware specifications].

NOTE: There is https://github.com/raspberrypi/libcamera/issues/43[some evidence] to suggest that the Camera Module 3 might emit RFI at a harmonic of the CSI clock rate. This RFI is in a range to interfere with GPS L1 frequencies (1575 MHz). For details and proposed workarounds, see the https://github.com/raspberrypi/libcamera/issues/43[thread on Github].

=== Transmission characteristics

The IMX708 sensor in Camera Module 3 has the following spectral sensitivity characteristics.

image::images/cm3-filter.png[Camera Module 3 Transmission Graph, width="65%"]

// Do we need another one of these for the NoIR characteristics?


Documentation Asciidoc Accessories Camera External Trigger (`documentation/asciidoc/accessories/camera/external_trigger.adoc`)

[[external-trigger]]
== External Trigger on the Global Shutter Camera

The Global Shutter (GS) camera can be triggered externally by pulsing the external trigger connection on the board (denoted on the board as XTR). Multiple cameras can be connected to the same pulse, allowing for an alternative way to synchronise two cameras.

The exposure time is equal to the low pulse-width time plus an additional 14.26 {sym-mu}s. For example, a low pulse of 10000 {sym-mu}s leads to an exposure time of 10014.26 {sym-mu}s. Framerate is directly controlled by how often you pulse the pin. A PWM frequency of 30 Hz leads to a framerate of 30 frames per second.

image::images/external_trigger.jpg[alt="Image showing pulse format",width="80%"]

=== Preparation

WARNING: This modification includes removing an SMD soldered part. Don't attempt this modification unless you feel you are competent to complete it. When soldering to the Camera board, remove the plastic back cover to avoid damaging it.

If your board has transistor Q2 fitted (shown in blue on the image below), then you will need to remove R11 from the board (shown in red). This connects GP1 to XTR and without removing R11, the camera will not operate in external trigger mode.
The location of the components is displayed below.

image::images/resistor.jpg[alt="Image showing resistor to be removed",width="80%"]

Next, solder a wire to the touchpoints of XTR and GND on the GS Camera board. Note that XTR is a 1.8 V input, so you might need a level shifter or potential divider.

We can use a Raspberry Pi Pico to provide the trigger. Connect any Pico GPIO pin (GP28 is used in this example) to XTR through a 1.5 kΩ resistor. Also connect a 1.8 kΩ resistor between XTR and GND to reduce the high logic level to 1.8 V. A wiring diagram is shown below.

image::images/pico_wiring.jpg[alt="Image showing Raspberry Pi Pico wiring",width="50%"]

==== Raspberry Pi Pico MicroPython Code

[source,python]

from machine import Pin, PWM

from time import sleep

pwm = PWM(Pin(28))

framerate = 30
shutter = 6000 # In microseconds

frame_length = 1000000 / framerate
pwm.freq(framerate)

pwm.duty_u16(int((1 - (shutter - 14) / frame_length) * 65535))

The low pulse width is equal to the shutter time, and the frequency of the PWM equals the framerate.

NOTE: In this example, Pin 28 connects to the XTR touchpoint on the GS camera board.

=== Camera driver configuration

This step is only necessary if you have more than one camera with XTR wired in parallel.

Edit /boot/firmware/config.txt. Change camera_auto_detect=1 to camera_auto_detect=0.

Append this line: [source]

dtoverlay=imx296,always-on

When using the CAM0 port on a Raspberry Pi 5, CM4 or CM5, append ,cam0 to that line without a space. If both cameras are on the same Raspberry Pi you will need two dtoverlay lines, only one of them ending with ,cam0.

If the external trigger will not be started right away, you also need to increase the libcamera timeout xref:camera.adoc#libcamera-configuration[as above].

=== Starting the camera

Enable external triggering:

[source,console]

$ echo 1 | sudo tee /sys/module/imx296/parameters/trigger_mode

Run the code on the Pico, then set the camera running:

[source,console]

$ rpicam-hello -t 0 --qt-preview --shutter 3000

Every time the Pico pulses the pin, it attempts to capture a frame. However, if --gain and --awbgains are not set, some frames are dropped to allow AGC and AWB algorithms to settle.

NOTE: When running rpicam-apps, always specify a fixed shutter duration, to ensure the AGC does not try to adjust the camera's shutter speed. The value is not important, since it is actually controlled by the external trigger pulse.


Documentation Asciidoc Accessories Camera Filters (`documentation/asciidoc/accessories/camera/filters.adoc`)

[[ir-filter]]
== IR Filter

Both the High Quality Camera and Global Shutter Camera contain an IR filter to reduce the camera's sensitivity to infrared light and help outdoor photos look more natural. However, you can remove the filter to:

  • Enhance colours in certain types of photography, such as images of plants, water, and the sky
  • Provide night vision in a location that is illuminated with infrared light

=== Filter Removal

WARNING: This procedure cannot be reversed: the adhesive that attaches the filter will not survive being lifted and replaced, and while the IR filter is about 1.1 mm thick, it might crack when it is removed. Removing it will void the warranty on the product.

You can remove the filter from both the HQ and GS cameras. The HQ camera is shown in the demonstration below.

image:images/FILTER_ON_small.jpg[width="65%"]

IMPORTANT: To protect the sensor when exposed to the air, ensure that you're working in a clean and dust-free environment.

. Unscrew the two 1.5 mm hex lock keys on the underside of the main circuit board. Be careful not to let the washers roll away.
+
image:images/SCREW_REMOVED_small.jpg[width="65%"]
. There's a gasket of slightly sticky material between the housing and PCB that requires some force to separate. You can also try some ways to weaken the adhesive, such as a little isopropyl alcohol or heat (~20-30°C).
. When the adhesive is loose, lift up the board and place it down on a very clean surface. Make sure the sensor doesn't touch the surface.
+
image:images/FLATLAY_small.jpg[width="65%"]
. Face the lens upwards and place the mount on a flat surface.
+
image:images/SOLVENT_small.jpg[width="65%"]
. To minimise the risk of breaking the filter, use a pen top or similar soft plastic item to push down on the filter only at the very edges where the glass attaches to the aluminium. The glue will break and the filter will detach from the lens mount.
+
image:images/REMOVE_FILTER_small.jpg[width="65%"]
. Given that changing lenses exposes the sensor, at this point you can affix a clear filter (for example, OHP plastic) to minimise the chance of dust entering the sensor cavity.
. Replace the main housing over the circuit board. Be sure to realign the housing with the gasket, which remains on the circuit board.
. Apply the nylon washer first to prevent damage to the circuit board.
. Next, fit the steel washer, which prevents damage to the nylon washer. Screw down the two hex lock keys. As long as the washers have been fitted in the correct order, they do not need to be screwed very tightly.
+
image:images/FILTER_OFF_small.jpg[width="65%"]

NOTE: It is likely to be difficult or impossible to glue the filter back in place and return the device to functioning as a normal optical camera.


Documentation Asciidoc Accessories Camera Gs (`documentation/asciidoc/accessories/camera/gs.adoc`)

[[gs-camera]]
== Global Shutter Camera

The 1.6-megapixel https://www.raspberrypi.com/products/raspberry-pi-global-shutter-camera/[Global Shutter Camera] captures fast-moving subjects and minimises distortion. It's built around the Sony IMX296 sensor with a resolution of 1456 × 1088 pixels.

The camera comes with a C/CS-mount for compatibility with a broad variety of lenses. For more information, see xref:../accessories/camera.adoc#lenses[Lenses].

You can trigger the Global Shutter (GS) camera by pulsing the external trigger connection on the board. This feature enables you to synchronise multiple Global Shutter Cameras. For more information, see xref:../accessories/camera.adoc#external-trigger[External Trigger on the Global Shutter Camera].

.Global Shutter Camera
image::images/gs-camera.jpg[GS Camera]

For detailed information about the hardware characteristics and capabilities of this camera, see the xref:../accessories/camera.adoc#hardware-specification[hardware specifications].

=== Rolling or Global shutter?

Most digital cameras, including our other Camera Modules, use a rolling shutter: they scan the image they're capturing line-by-line, then output the results. This can cause distortion effects in some settings. For example, a photo of rotating propeller blades can make the image look as though it's shimmering rather than like an object that's rotating. This is because the propeller blades have had enough time to change position in the tiny moment that the camera has taken to scan across and observe the scene.

A global shutter, like the one on our Global Shutter Camera Module, doesn't do this. It captures the light from every pixel in the scene at once, so a photograph of something like propeller blades doesn't result in the same distortion.

This is useful because it makes fast-moving objects, like propeller blades, easy to capture; we can also synchronise several cameras to take a photo at precisely the same moment in time. Benefits include minimising distortion when capturing stereo images; the human brain is confused if any movement that appears in the left eye hasn't yet appeared in the right eye. The Raspberry Pi Global Shutter Camera can also operate with shorter exposure times – down to 30 µs, given enough light – than a rolling shutter camera, which makes it useful for high-speed photography.

NOTE: The Global Shutter Camera's image sensor has a 6.3 mm diagonal active sensing area, which is similar in size to Raspberry Pi HQ Camera. However, the pixels are larger and can collect more light. Large pixel size and low pixel count are valuable in machine-vision applications; the more pixels a sensor produces, the harder it is to process the image in real time. To get around this, many applications downsize and crop images. This is unnecessary with the Global Shutter Camera and the appropriate lens magnification, where the lower resolution and large pixel size mean an image can be captured natively.

=== Transmission characteristics

The Global Shutter Camera uses a Hoya CM500 infrared filter. Its transmission characteristics are as represented in the following graph.

image::images/hoyacm500.png[CM500 Transmission Graph,width="65%"]

If you want to enhance the Global Shutter Camera's sensitivity to infrared light, you can remove the infrared filter. This action is permanent and voids the warranty. For more information, see xref:../accessories/camera.adoc#ir-filter[IR filter].

Without its filter, Raspberry Pi Global Shutter Camera has the following transmission characteristics:

image::images/gs.png[GS Camera Transmission Graph without IR-Cut filter,width="65%"]


Documentation Asciidoc Accessories Camera Hardware Specification (`documentation/asciidoc/accessories/camera/hardware_specification.adoc`)

[[hardware-specification]]
== Hardware specifications

The following table compares the features and capabilities of the Raspberry Pi camera hardware.

|===
| | Camera Module 1 | Camera Module 2 | Camera Module 3 | Camera Module 3 Wide | HQ Camera | AI Camera | GS Camera

| Size
| Around 25 × 24 × 9 mm
| Around 25 × 24 × 9 mm
| Around 25 × 24 × 11.5 mm
| Around 25 × 24 × 12.4 mm
| 38 × 38 × 18.4 mm (excluding lens)
| 25 × 24 × 11.9 mm
| 38 × 38 × 19.8 mm (29.5 mm with adaptor and dust cap)

| Weight
| 3 g
| 3 g
| 4 g
| 4 g
| 30.4 g
| 6 g
| 34 g (41 g with adaptor and dust cap)

| Still resolution
| 5 megapixels
| 8 megapixels
| 11.9 megapixels
| 11.9 megapixels
| 12.3 megapixels
| 12.3 megapixels
| 1.58 megapixels

| Video modes
| 1080p30, 720p60 and 640 × 480p60/90
| 1080p47, 1640 × 1232p41 and 640 × 480p206
| 2304 × 1296p56, 2304 × 1296p30 HDR, 1536 × 864p120
| 2304 × 1296p56, 2304 × 1296p30 HDR, 1536 × 864p120
| 2028 × 1080p50, 2028 × 1520p40 and 1332 × 990p120
| 2028 × 1520p30, 4056 × 3040p10
| 1456 × 1088p60

| Sensor
| OmniVision OV5647
| Sony IMX219
| Sony IMX708
| Sony IMX708
| Sony IMX477
| Sony IMX500
| Sony IMX296

| Sensor resolution
| 2592 × 1944 pixels
| 3280 × 2464 pixels
| 4608 × 2592 pixels
| 4608 × 2592 pixels
| 4056 × 3040 pixels
| 4056 × 3040 pixels
| 1456 × 1088 pixels

| Sensor image area
| 3.76 × 2.74 mm
| 3.68 × 2.76 mm (4.6 mm diagonal)
| 6.45 × 3.63 mm (7.4 mm diagonal)
| 6.45 × 3.63 mm (7.4 mm diagonal)
| 6.287 × 4.712 mm (7.9 mm diagonal)
| 6.287 × 4.712 mm (7.9 mm diagonal)
| 6.3 mm diagonal

| Pixel size
| 1.4 µm × 1.4 µm
| 1.12 µm × 1.12 µm
| 1.4 µm × 1.4 µm
| 1.4 µm × 1.4 µm
| 1.55 µm × 1.55 µm
| 1.55 µm × 1.55 µm
| 3.45 µm × 3.45 µm

| Optical size
| 1/4"
| 1/4"
| 1/2.43"
| 1/2.43"
| 1/2.3"
| 1/2.3"
| 1/2.9"

| Focus
| Fixed
| Adjustable
| Motorised
| Motorised
| Adjustable
| Adjustable
| Adjustable

| Focus range
| Approx 1 m to ∞
| Approx 10 cm to ∞
| Approx 10 cm to ∞
| Approx 5 cm to ∞
| Depends on lens
| Approx 20 cm to ∞
| Depends on lens

| Focal length
| 3.60 mm ± 0.01
| 3.04 mm
| 4.74 mm
| 2.75 mm
| Depends on lens
| 4.74 mm
| Depends on lens

| Horizontal Field of View (FoV)
| 53.50 ± 0.13 degrees
| 62.2 degrees
| 66 degrees
| 102 degrees
| Depends on lens
| 66 ± 3 degrees
| Depends on lens

| Vertical Field of View (FoV)
| 41.41 ± 0.11 degrees
| 48.8 degrees
| 41 degrees
| 67 degrees
| Depends on lens
| 52.3 ± 3 degrees
| Depends on lens

| Focal ratio (F-Stop)
| F2.9
| F2.0
| F1.8
| F2.2
| Depends on lens
| F1.79
| Depends on lens

| Maximum exposure time (seconds)
| 3.28
| 11.76
| 112
| 112
| 670.74
| 112
| 15.5

| Lens Mount
| N/A
| N/A
| N/A
| N/A
| C/CS- or M12-mount
| N/A
| C/CS

| NoIR version available?
| Yes
| Yes
| Yes
| Yes
| No
| No
| No
|===


Documentation Asciidoc Accessories Camera Hq (`documentation/asciidoc/accessories/camera/hq.adoc`)

[[hq-camera]]
== High Quality Camera

The 12-megapixel https://www.raspberrypi.com/products/raspberry-pi-high-quality-camera/[High Quality Camera] comes with either an M12-mount or a C/CS-mount for compatibility with a broad variety of lenses. For more information, see xref:../accessories/camera.adoc#lenses[Lenses]. The camera is built around the Sony IMX477 sensor with a resolution of 4056 × 3040 pixels. It can record an exposure time of up to 670.74 seconds.

You can trigger the High Quality Camera by pulsing the external trigger. This feature enables you to synchronise multiple High Quality Cameras. For more information, see xref:../accessories/camera.adoc#synchronous-captures[Synchronous Captures].

.High Quality Camera, M12-mount (left) and C/CS-mount (right)
image::images/hq.jpg[M12- and C/CS-mount versions of the HQ Camera]

For detailed information about the hardware characteristics and capabilities of this camera, see the xref:../accessories/camera.adoc#hardware-specification[hardware specifications].

=== Transmission characteristics

The High Quality Camera uses a Hoya CM500 infrared filter. Its transmission characteristics are as represented in the following graph.

image::images/hoyacm500.png[CM500 Transmission Graph,width="65%"]

If you want to enhance the High Quality Camera's sensitivity to infrared light, you can remove the infrared filter. This action is permanent and voids the warranty. For more information, see xref:../accessories/camera.adoc#ir-filter[IR filter].

Without its filter, Raspberry Pi High Quality Camera has the following transmission characteristics:

image::images/hq.png[High Quality Camera Transmission Graph without IR-Cut filter,width="65%"]


Documentation Asciidoc Accessories Camera Install (`documentation/asciidoc/accessories/camera/install.adoc`)

:figure-caption!:
== Install a Raspberry Pi camera

////
TODO: Get a new video with more current products.

The following video shows how to connect the original camera on the original Raspberry Pi:

video::GImeVqHQzsE[youtube,width=80%,height=400px]
////

The process for installing a Raspberry Pi camera is broadly the same for all combinations of camera and board. There are some differences in the connectors; these differences are noted in the following steps.

=== Step 1. Prepare

WARNING: Cameras are sensitive to static. Earth yourself prior to handling the PCB. If you don't have an earthing strap, you can touch a sink tap or similar to earth yourself.

To complete this procedure, you need the following items:

  • A Raspberry Pi board with a camera connector.
  • A Raspberry Pi camera.

Some cameras might come with a small piece of translucent blue plastic film covering the lens. This is only present to protect the lens during shipping. To remove it, gently peel it off.

  • The appropriate cable to connect the camera and board.
    ** All Raspberry Pi cameras use the standard, 15-pin connector.
    ** Raspberry Pi flagship models up to and including Raspberry Pi 4 use the standard, 15-pin connector. For these boards, use the Standard-Standard camera cable provided with your camera.
    ** Raspberry Pi 5, all Raspberry Pi Zero models, and Compute Module IO boards use the mini, 22-pin connector. For these boards, use the https://www.raspberrypi.com/products/camera-cable/[Standard-Mini camera cable].
    ** Some Compute Module Development Kits come with a Compute Module Camera and Display Adaptor (CMCDA) board, which converts the mini, 22-pin connector on the IO board into a standard, 15-pin connector.

// Note: maybe do this as a table/matrix when the camera with the mini 22-pin is released

=== Step 2. Connect the cable to your Raspberry Pi

NOTE: If you intend to use the Active Cooler with Raspberry Pi 5, consider connecting the cable to the camera connector on your Raspberry Pi device before installing the Active Cooler. With the Active Cooler in place, accessing the camera connectors can be awkward.

. Shut down your Raspberry Pi and disconnect it from power.
. Locate the camera connector on your Raspberry Pi board.
+
The following descriptions assume that you're holding your Raspberry Pi board with the chip and connectors facing up and the Raspberry Pi logo and board name in the correct orientation. For Raspberry Pi Zero boards without the logo on the top side, orient the board with the GPIO header along the edge furthest away from you.
+
** On Raspberry Pi Zero devices, the camera connector is on the short edge to the right, opposite the SD card slot.
** On Raspberry Pi flagship models prior to Raspberry Pi 4, the camera connector is by the edge closest to you between the HDMI connector and the audio jack. It's labelled CAMERA.
** On Raspberry Pi 4, the camera connector is by the edge closest to you between the micro HDMI connector and the audio jack. It's labelled CAMERA.
** On Raspberry Pi 5, the two camera and display connectors are by the edge closest to you between the micro HDMI connector and the Ethernet port. They're labelled CAM/DISP0 and CAM/DISP1. You can use either of these connectors for your camera.
** On Raspberry Pi Compute Module 1/3/3+ IO board, the two camera connectors are on the left edge (the edge closest to the logo on the IO board) at the end closest to you. They're labelled CAM0 and CAM1. You can use either of these connectors for your camera.
** On Raspberry Pi Compute Module 4 IO board, the two camera connectors are by the far left corner. They are labelled CAM0 and CAM1. You can use either of these connectors for your camera.
** On Raspberry Pi Compute Module 5 IO board, the two camera connectors are at the left end of the furthest edge. They are labelled CAM/DISP0 and CAM/DISP1. You can use either of these connectors for your camera.
. Open the flap on the connector.
.. If there is a strip of film holding the connector flap closed, remove it.
.. Gently pull the flap out from the connector until you feel it stop. There is now some freedom of movement in the flap.
.. Tilt the flap slightly away from the connector opening.
. Insert the end of your camera cable with the metallic contacts facing away from the flap.
+
Ensure the camera cable is inserted firmly into the connector and is seated straight to correctly align all contacts. Take care not to bend the flexible cable at a sharp angle.
. Close the connector flap by tilting it back towards the cable and pushing it down into the connector until you feel it click into place.
+
The flap holds the cable in place and ensures good contact between the connector pins and the metallic contacts of the cable.

You can remove a cable from the connector by reversing these steps.

=== Step 3. Connect the cable to the camera

Our cameras come with the Standard-Standard cable already attached. If you have removed this cable or want to switch to using a different cable, complete the following steps.

The camera connector is on the opposite side of the board to the camera lens. Hold the camera with the lens facing down or away from you.

. Open the flap on the connector.
.. Gently pull the flap out from the connector until you feel it stop. There is now some freedom of movement in the flap.
.. Tilt the flap slightly away from the connector opening.
. Insert the end of your camera cable with the metallic contacts facing away from the flap and towards the camera board.
+
Ensure the camera cable is inserted firmly into the connector and is seated straight to correctly align all contacts. Take care not to bend the flexible cable at a sharp angle.
. Close the connector flap by tilting it back towards the cable and pushing it down into the connector until you feel it click into place.
+
The flap holds the cable in place and ensures good contact between the connector pins and the metallic contacts of the cable.

You can remove a cable from the connector by reversing these steps.

=== Step 4. Prepare the software

. Reconnect your Raspberry Pi device to power and turn it on.
. Ensure that your kernel and applications are all up to date by following the instructions on xref:../computers/os.adoc#update-software[keeping your operating system up to date].
. Follow the setup instructions for xref:../computers/camera_software.adoc#rpicam-apps[rpicam-apps].
. (Optional) If you want to use the Picamera2 Python library, follow the setup instructions for https://pip.raspberrypi.com/documents/RP-008156-DS[Picamera2 Python library].

// TODO should the picamera2 manual info be in the HTML docs instead/as well? Also. Camera software stuff could follow in here rather than being in computers section?


Documentation Asciidoc Accessories Camera Intro (`documentation/asciidoc/accessories/camera/intro.adoc`)

:figure-caption!:
== About the Camera Modules

There are several official Raspberry Pi camera modules.

  • Camera Module 1. A 5-megapixel camera that came in standard (visible light) and NoIR (visible light plus infrared) versions with a standard field of view (FoV). This device is no longer available from Raspberry Pi.
  • xref:../accessories/camera.adoc#camera-module-2[Camera Module 2.] A 8-megapixel camera available in standard and NoIR versions with a standard FoV.
  • xref:../accessories/camera.adoc#camera-module-3[Camera Module 3.] A 12-megapixel camera available in standard and NoIR versions. Both the standard and NoIR versions come with standard and wide FoV for a total of four different variants.

The Camera Module 3 sensor assembly is also available separately to enable you to fit these capabilities into smaller devices.

  • xref:../accessories/camera.adoc#hq-camera[High Quality Camera.] A 12-megapixel camera that comes with CS- or M12-mount variants for use with external lenses. This model is unavailable as a NoIR version.
  • xref:../accessories/ai-camera.adoc[AI Camera.] A 12-megapixel camera that provides low-latency and high-performance AI capabilities to any camera application. Tight integration with xref:../computers/camera_software.adoc[the Raspberry Pi camera software stack] enables users to deploy their own neural network models with minimal effort. This model is unavailable as a NoIR version.
  • xref:../accessories/camera.adoc#gs-camera[Global Shutter Camera.] A 1.5-megapixel camera that uses a global shutter mechanism. It captures light from every pixel in the scene at once and is ideal for fast-motion photography. It comes with a CS-mount for use with external lenses. This model is unavailable as a NoIR version.

To compare the hardware characteristics of these cameras, see the xref:../accessories/camera.adoc#hardware-specification[hardware specifications].

NOTE: Raspberry Pi Camera Modules are compatible with all Raspberry Pi computers with CSI connectors.

For information about the camera software, see the xref:../computers/camera_software.adoc[camera software documentation].


Documentation Asciidoc Accessories Camera Lens (`documentation/asciidoc/accessories/camera/lens.adoc`)

[[lenses]]
== Recommended Lenses

The following lenses are recommended for use with our HQ and GS cameras.

NOTE: While the HQ Camera is available in both C/CS- and M12-mount versions, the GS Camera is available only with a C/CS-mount.

=== C/CS Lenses

We recommend two lenses, a 6 mm wide angle lens and a 16 mm telephoto lens manufactured by CGL Electronics Co. Ltd. These lenses are available from your nearest https://www.raspberrypi.com/products/raspberry-pi-high-quality-camera/[Authorised Reseller].

[cols="1,1,1,1"]
|===
2+| | 16 mm telephoto | 6 mm wide angle

2+| Resolution | 10 MP | 3 MP
2+| Image format | 1" | 1/2"
2+| Aperture | F1.4 to F16 | F1.2
2+| Mount | C | CS
.2+| Field of View H°×V° (D°)
| HQ | 22.2°×16.7° (27.8°)| 55°×45° (71°)
| GS| 17.8°×13.4° (22.3) | 45°×34° (56°)
2+| Back focal length | 17.53 mm | 7.53 mm
2+| M.O.D. | 0.2m | 0.2m
2+| Dimensions | φ39×50 mm | φ30×34 mm
|===

=== M12 Lenses

image::images/m12-lens.jpg[]

We recommend three lenses manufactured by https://www.gaojiaoptotech.com/[Gaojia Optotech]. These lenses are available from your nearest https://www.raspberrypi.com/products/raspberry-pi-high-quality-camera/[Authorised Reseller].

[cols="1,1,1,1,1"]
|===
2+| | 8 mm | 25 mm | Fish Eye

2+| Resolution | 12 MP | 5 MP | 15 MP
2+| Image format | 1/1.7" | 1/2" | 1/2.3"
2+| Aperture | F1.8 | F2.4 | F2.5
2+| Mount 3+| M12
2+| HQ Field of View H°×V° (D°) | 49°×36° (62°) | 14.4°×10.9° (17.9)° | 140°×102.6° (184.6°)
|===


Documentation Asciidoc Accessories Camera Synchronous Cameras (`documentation/asciidoc/accessories/camera/synchronous_cameras.adoc`)

[[synchronous-captures]]
== Synchronous Captures

The High Quality (HQ) Camera supports synchronous captures.
One camera (the "source") can be configured to generate a pulse on its XVS (Vertical Sync) pin when a frame capture is initiated.
Other ("sink") cameras can listen for this pulse, and capture a frame at the same time as the source camera.

This method is largely superseded by xref:../computers/camera_software.adoc#software-camera-synchronisation[software camera synchronisation] which can operate over long distances without additional wires and has sub-millisecond accuracy. But when cameras are physically close, you can use wired synchronisation.

NOTE: You can also operate Global Shutter (GS) Cameras in synchronous mode. However, the source camera records one extra frame. Instead, for GS Cameras we recommend using an xref:camera.adoc#external-trigger[external trigger source]. You can't synchronise a GS Camera and an HQ Camera.

=== Connecting the cameras

Solder a wire to the XVS test point of each camera, and connect them together.

Solder a wire to the GND test point of each camera, and connect them together.

For GS Cameras only, you must also connect the XHS (Horizontal Sync) test point of each camera together. On any GS Camera that you wish to act as a sink, bridge the two halves of the MAS pad with solder.

NOTE: An earlier version of this document recommended an external pull-up for XVS. This is no longer recommended. Instead, ensure you have the latest version of Raspberry Pi OS and set the always-on property for all connected cameras.

=== Driver configuration

Configure the camera drivers to keep their 1.8 V power supplies on when not streaming, and optionally to select the source and sink roles.

==== For the HQ Camera

Edit /boot/firmware/config.txt. Change camera_auto_detect=1 to camera_auto_detect=0.

Append this line for a source camera: [source]

dtoverlay=imx477,always-on,sync-source

Or for a sink: [source]

dtoverlay=imx477,always-on,sync-sink

When using the CAM0 port on a Raspberry Pi 5, CM4 or CM5, append ,cam0 to that line without a space. If two cameras are on the same Raspberry Pi, you need two dtoverlay lines, only one of them ending with ,cam0.

Alternatively, if you wish to swap the cameras' roles at runtime (and they are not both connected to the same Raspberry Pi), omit ,sync-source or ,sync-sink above. Instead you can set a module parameter before starting each camera:

For the Raspberry Pi with the source camera: [source,console]

$ echo 1 | sudo tee /sys/module/imx477/parameters/trigger_mode

For the Raspberry Pi with the sink camera: [source,console]

$ echo 2 | sudo tee /sys/module/imx477/parameters/trigger_mode

Do this every time the system is booted.

==== For the GS Camera

Edit /boot/firmware/config.txt. Change camera_auto_detect=1 to camera_auto_detect=0.

For either a source or a sink, append this line: [source]

dtoverlay=imx296,always-on

When using the CAM0 port on a Raspberry Pi 5, CM4 or CM5, append ,cam0 to that line without a space. If two cameras are on the same Raspberry Pi, you need two dtoverlay lines, only one of them ending with ,cam0.

On the GS Camera, the sink role is enabled by the MAS pin and can't be configured by software ("trigger_mode" and "sync-sink" relate to the xref:camera.adoc#external-trigger[external trigger method], and mustn't be set for this method).

=== Libcamera configuration

If the cameras don't all start within 1 second, the rpicam applications can time out. To prevent this, edit a configuration file on any Raspberry Pi with sink cameras.

On Raspberry Pi 5 or CM5: [source,console]

$ cp /usr/share/libcamera/pipeline/rpi/pisp/example.yaml timeout.yaml

On other Raspberry Pi models: [source,console]

$ cp /usr/share/libcamera/pipeline/rpi/vc4/rpi_apps.yaml timeout.yaml

Now edit the copy. In both cases, delete the # (comment) from the "camera_timeout_value_ms": line, and change the number to 60000 (60 seconds).

=== Starting the cameras

Run the following commands to start the sink:

[source,console]

$ export LIBCAMERA_RPI_CONFIG_FILE=timeout.yaml $ rpicam-vid --frames 300 --qt-preview -o sink.h264

Wait a few seconds, then run the following command to start the source:

[source,console]

$ rpicam-vid --frames 300 --qt-preview -o source.h264

Frames must be synchronised. Use --frames to ensure the same number of frames are captured, and that the recordings are exactly the same length.
Running the sink first ensures that no frames are missed.

NOTE: When using the GS camera in synchronous mode, the sink doesn't record exactly the same number of frames as the source. The source records one extra frame before the sink starts recording. Because of this, you need to specify that the sink records one less frame with the --frames option.


Documentation Asciidoc Accessories Cm5 Programming Jig About (`documentation/asciidoc/accessories/cm5-programming-jig/about.adoc`)

The https://www.raspberrypi.com/products/cm5-programming-jig[Compute Module 5 Programming Jig] is a provisioning system that programs one Compute Module 5 (CM5) at a time with an operating system (OS) and security configuration. The jig connects directly with each CM5, eliminating the need for a separate IO board during provisioning.

The jig runs xref:../security/secure-boot-provisioner.adoc[Secure Boot Provisioner (rpi-sb-provisioner)] to automate the provisioning workflow. When you insert and secure a CM5 into the jig, the jig automatically performs all configuration steps, including secure boot implementation, full-disk encryption, and operating system installation.

.The Compute Module 5 Programming Jig
image::images/hero.jpg[alt="The Compute Module 5 Programming Jig.",width="100%"]

== Specifications

This section describes the physical characteristics and capabilities of the Compute Module 5 Programming Jig, including specifications, features, and hardware.

.General specifications
[cols="1,2", options="header"]
|===
| Specification
| Description

| Compatible devices
| Raspberry Pi Compute Module 5 (CM5)

| Provisioning capacity
| Single-device provisioning; the jig configures one CM5 at a time

| Jig network interface (JIG ETH)
| Ethernet (10/100/1000) or Wi-Fi (2.4 GHz and 5.0 GHz IEEE 802.11 b/g/n/ac).

| CM5 network interface (DUT ETH)
| Ethernet (10/100/1000)

| Dimensions (including antenna)
| 170 × 181.5 × 153 mm

| Weight
| 1800 g

|===

=== Features

  • Mechanical clamping. The jig secures the CM5 in place during programming.
  • Carrier board-free provisioning. The jig uses spring-loaded pogo pins to interface directly with a CM5, eliminating the need for a carrier (IO) board and reducing wear on the high-density pin connectors.
  • LED status indicators. The jig displays its current state and provisioning progress through dedicated LEDs. For more information about these LEDs, see <<led-indicators, LED behaviour>>
  • Dual network connectivity. The jig connects to the provisioning network by Ethernet (JIG ETH) or Wi-Fi®, with a second Ethernet port (DUT ETH) providing accelerated software transfer to the CM5 being programmed.
  • Automated provisioning. The jig automates the provisioning workflow, including OS installation, full-disk encryption, and secure boot configuration (depending on the level of security you choose).
  • Three levels of security. You have the option to configure the jig to program a CM5 with one of three levels of security: full security (secure-boot), encrypted storage and device-unique keys (fde-only), and OS-only (naked). For more information, see xref:../security/secure-boot-provisioner.adoc#security-levels[Levels of security].
  • User serviceable. The jig comes with tweezers and replacement pogo pins to enable you to remove and replace any pogo pins that become damaged. For more information, see <>.

WARNING: Don't touch the pogo pins because they're sharp and can carry charge; you might damage the pins, the jig, or yourself.

=== Hardware

The Compute Module 5 Programming Jig box contains the following parts:

  • A Compute Module 5 Programming Jig.
  • A global power supply with 110 V to 240 V AC input and 12 V at 2 A (24 W) DC output.
  • A Wi-Fi antenna.
  • Two RJ45 cables.
  • Five spare pogo pins.
  • A pair of tweezers.

During usage, you interact with the Compute Module 5 Programming Jig connectors and module bay. There's also a safety button that you don't interact with directly.

==== Connectors

.The connectors on the back of the CM5 Programming Jig
image::images/back.jpg[alt="The Wi-Fi antenna connector, LEDs for the DUT and JIG, and the following input ports: 12 V power supply, USB-C, DUT Ethernet, and JIG Ethernet.",width="100%"]

The back of the Compute Module 5 Programming Jig provides the following external connectors:

.External connectors on the back of the Compute Module 5 Programming Jig
[cols="1,2", options="header"]
|===
| Label
| Description

| WiFI/BT
| The attachment point for the included antenna.

| 12 V IN
| A barrel power jack that accepts 12 V at 2 A (24 W) DC input from the supplied power supply.

| USB BOOT
| A USB-C port used to connect your jig to a computer when using Raspberry Pi Imager to write the jig's operating system (see <>).

| JIG ETH
| An RJ45 Ethernet port for connecting the jig to the provisioning network for configuration, management, and software updates.

| DUT ETH
| An RJ45 Ethernet port for connecting an inserted CM5 to the provisioning network for accelerated data transfer during provisioning.
|===

As an alternative to the JIG ETH port, you can connect the jig to the provisioning network wirelessly using Wi-Fi.

==== Module bay

The module bay on top of the Compute Module 5 Programming Jig holds the CM5 that's being programmed.

The CM5 fits snugly within the module bay with the Raspberry Pi logo on the CM5 facing up and in the same orientation as the Raspberry Pi logo on the jig. The metal latch at the front of the module bay holds it closed.

==== Safety button

An unmarked safety button is located on top of the jig, at the back of the module bay. The provisioning software uses this button to detect when the jig is closed.

WARNING: Don't manually press this button because doing so can interrupt a provisioning operation.

[[set-up-the-jig]]
== Set up the jig

To set up the jig for the first time, you need the following:

[[setup-step-configure-imager]]
=== Step 1: Configure Raspberry Pi Imager

You must first configure Raspberry Pi Imager to use the Compute Module 5 Programming Jig manifest and enable RPIBOOT support.

==== Configure the manifest

You can configure the Compute Module 5 Programming Jig manifest automatically or manually.

[tabs]

Automatic configuration::
+
To open Raspberry Pi Imager with the custom repository configured, enter the following URL into your web browser: rpi-imager://open?repo=https://downloads.raspberrypi.com/cm5-jig/cm5-jig.rpi-imager-manifest.

Manual configuration:: + To configure the repository manually, open Raspberry Pi Imager and complete the following steps: + . Select *App Options* from the bottom left. . Next to *Content Repository*, select *Edit*. The *Content Repository* window opens. . Select *Use custom URL*. . In the displayed field, enter the manifest URL (`https://downloads.raspberrypi.com/cm5-jig/cm5-jig.rpi-imager-manifest`). . Select *Apply & Restart*.

==== Enable RPIBOOT support

To configure Raspberry Pi Imager to support RPIBOOT, complete the following steps:

. Open Debug Options:
** On Windows or Linux, type Ctrl + Alt + S.
** On macOS, type Cmd + Option + S.
. Scroll to Advanced Features.
. Use the toggle to select Enable Rpiboot/Fastboot Support.
. Select Apply to save your changes and exit the Debug Options dialog.

If you're using Raspberry Pi Imager to set up multiple jigs, you need to enable RPIBOOT support only once; Imager saves this settings for subsequent writes.

[[setup-step-write-os]]
=== Step 2: Write the operating system to the jig

With Imager configured to use the custom content repository, you can now write the OS to the jig.

. Connect the USB-C cable from your computer to the jig's USB BOOT port.

. Connect power to the jig.
+
The jig boots into USB mass-storage mode. Your computer detects the jig's internal storage as a removable drive.

. Open Raspberry Pi Imager on your computer.

. On the Device tab, select Raspberry Pi Compute Module 5 Programming Jig. Select Next.

. On the OS tab, select Compute Module 5 Programming Jig as the operating system image. Select Next.

. On the Storage tab, select the jig's internal storage as the target. This is listed as Raspberry Pi Compute Module 5 Lite. Select Next.

. On the Customisation tabs that follow, configure the operating system:
+
.. Set a hostname for the jig.
.. Select your capital city to set the localisation settings.
.. When creating a username, you must specify the username jig. You can set a password of your choice for this account.
.. Optional: If you plan to connect the jig by Wi-Fi, configure your wireless network credentials.
.. Optional: Enable SSH for remote access.
.. Associate the jig with your Raspberry Pi Connect account for remote management.

. On the Writing tab, check your settings and, if these are correct, select Write.

. After Raspberry Pi Imager has finished writing, disconnect the USB-C cable and power cycle the jig by removing and reinserting the power cable.

[[setup-step-connect-network]]
=== Step 3: Connect to the provisioning network

Connect the jig to your provisioning network using one of the following methods:

  • (Recommended) <<setup-step-ethernet, Ethernet>>
  • <<setup-step-wifi, Wi-Fi>>

The jig uses the connection to the provisioning network to:

  • Provide Raspberry Pi Connect screen sharing and SSH access.
  • Download software updates.
  • Transfer OS images to the jig.

WARNING: The provisioning network always has direct access to the jig. If you also connect the DUT ETH port to the provisioning network (see <>), the network has direct access to devices during programming. Consider the design of this network as part of your threat model. Ensure that only authorised systems and personnel have access to the provisioning network.

[[setup-step-ethernet]]
==== Connect using Ethernet (recommended)

To connect the jig to your provisioning network over Ethernet:

. Ensure the jig is powered off by unplugging the power cable.
. Connect an Ethernet cable from your provisioning network to the jig's JIG ETH port.
. Power on the jig by plugging in the power cable.

The jig obtains a network address automatically using DHCP.

[[setup-step-wifi]]
==== Connect using Wi-Fi

If you configured Wi-Fi credentials in Raspberry Pi Imager, the jig connects to your wireless network automatically on boot.

. Ensure the jig is powered off by unplugging the power cable.
. Ensure the Wi-Fi antenna is attached to your the back of your jig.
. If your jig has an Ethernet cable connected to the JIG ETH port, disconnect this cable from the jig.
. Power on the jig by plugging in the power cable.

The jig connects to the configured wireless network.

[[setup-step-connect-dut]]
=== Step 4: Connect the DUT ETH port (optional)

For accelerated data transfer during provisioning, connect an Ethernet cable from the provisioning network to the jig's DUT ETH port. This provides a direct Ethernet interface to the CM5 being programmed.

[[setup-step-use-provisioner]]
=== Step 5: Access the Secure Boot Provisioner web interface

The Secure Boot Provisioner (rpi-sb-provisioner) web interface is only available on http://localhost:3142[`localhost`]. This is a security measure that enforces authentication against the jig. To access the web interface, use Raspberry Pi Connect screen sharing to access the jig's desktop remotely.

. Sign in to https://connect.raspberrypi.com[Raspberry Pi Connect].
. Select your jig from the device list.
. Start a screen sharing session by selecting the Connect button and choosing Screen Sharing.

If the Secure Boot Provisioner web interface isn't already open on the jig's desktop, open Chromium on the jig's desktop and go to http://localhost:3142.

[[setup-step-wormhole]]
=== Step 6: Transfer the client OS image to the jig

Before you can configure provisioning, you must transfer the OS image that you want to install on your CM5 devices to the jig.

The image must be an uncompressed .img file created with https://github.com/raspberrypi/rpi-image-gen[`rpi-image-gen`].

We recommend using Magic-Wormhole to transfer the image from your computer to the jig. magic-wormhole provides a secure, one-time file transfer between two computers. To use this method, both computers must have access to the internet.

. On your computer, install `magic-wormhole`. For more information, see https://magic-wormhole.readthedocs.io/en/latest/[Magic-Wormhole]. . On your computer, use the following command to send the image file: + [source,bash]

wormhole send

magic-wormhole displays a receive code. Note this code for use on the jig.

. Connect to the jig over SSH, or use a terminal in the Raspberry Pi Connect screen sharing session. . On the jig, use the following command to install `magic-wormhole`: + [source,bash]

sudo apt install -y magic-wormhole

. On the jig, use the following command to receive the image file, replacing `` with the receive code you obtained when you sent the image file from your computer: + [source,bash]

wormhole receive

[[setup-step-configure-provisioner]]
=== Step 7: Configure the Secure Boot Provisioner

. Open the Secure Boot Provisioner web interface as described in <>.
. On the Options tab, configure the following options:
.. In the OS Image section, select Upload New Image and select or browse to the operating system image that you transferred to the jig.
.. In the Device & Firmware section, for Device family, choose Raspberry Pi 5.
.. In the Device & Firmware section, for Storage Type, choose eMMC.
.. In the Security Configuration section, for Provisioning Style choose the level of security. For more information, see xref:../security/secure-boot-provisioner.adoc#security-levels[Levels of security]
.. Signing key: For secure-boot mode, provide a signing key. The web interface guides you through creating one.

For more information about configuration options, see the https://github.com/raspberrypi/rpi-sb-provisioner/blob/main/docs/config_vars.md[Secure Boot Provisioner configuration reference].

[[program-cm5]]
== Program a Compute Module 5

Use the Compute Module 5 Programming Jig to provision a Compute Module 5 (CM5) with an operating system image.

Before you begin, ensure that the jig is:

  • Powered on, with the JIG and STATUS LEDs showing green.
  • Connected to the provisioning network. For more information, see <> in the Set up the jig instructions.
  • Configured with an operating system image and provisioning options. For more information, see <> in the Set up the jig instructions.

[[program-step-load]]
=== Step 1: Insert the CM5 into the jig

. Press the top of the latch backwards to release the clamping mechanism, allow the lid to slide up, and then pivot the lid back until it stops.
+
image::images/latch-open.jpg[alt="The metal latch on the front of the clamping mechanism holds it shut.",width="80%"]

. Place the Compute Module 5 into the module bay with the Raspberry Pi logo on the CM5 facing up and in the same orientation as the Raspberry Pi logo on the jig. Align the holes on the corners of the Compute Module 5 with the through-hole studs on the corners of the module recess. The studs thread through the holes on the CM5.
+
image::images/open-tray-cm.jpg[alt="The Compute Module sits within the module recess.",width="80%"]

. Close the clamping mechanism by pivoting the lid forwards until it is parallel with the CM5 and pressing the lid so it slides down. When it reaches the bottom, the latch engages and secures the CM5 in place.

WARNING: Ensure that the through-hole studs pass through all four corner holes on the CM5 before closing the lid. Incorrect alignment can result in a failed provisioning attempt or damage to the pogo pins.

[[program-step-monitor]]
=== Step 2: Monitor provisioning progress

After the CM5 is clamped in place, the jig begins provisioning automatically. If provisioning doesn't start automatically, see <>.

Typical provisioning time is approximately 1.5 minutes for each CM5 with a 2.6 GB OS image installed using the naked provisioning style. Actual time varies depending on OS image size, storage type, level of security, and network speed.

WARNING: Don't remove the CM5 from the jig while provisioning is in progress. Don't press the unmarked button on the jig. Either of these actions can render the CM5 unusable.

Monitor the STATUS LED on the jig to track progress through the provisioning phases:

.Status indications during provisioning
[cols="1,1,2", options="header"]
|===
| Status LED
| Phase
| Description

| Flashing blue
| Provisioning
| The jig detects the CM5 and loads a temporary Linux environment. In secure-boot mode, the signing key hash is programmed into the device OTP memory (this is a permanent operation).

The jig selects the appropriate provisioning service based on the level of security you chose in <>.

The jig creates encryption keys (if applicable), formats storage, and installs the operating system.

| Green
| Success
| Provisioning is complete. The CM5 can be removed.

| Flashing red
| Provisioning failed
| The provisioning process failed. For more information, see <>.

|===

For more detailed progress information, you can also use the Secure Boot Provisioner web interface. Access http://localhost:3142 as described in <>, then:

. Select the Devices tab to see provisioning progress.
. Select a device to view detailed logs about it.

=== Step 3: Remove the CM5

When the STATUS LED turns green, provisioning is complete. You can remove the CM5.

. Open the clamping mechanism. Press the top of the latch backwards to release it, allow the lid to slide up, and then pivot the lid back until it stops.
. Remove the CM5 from the module bay.

The CM5 is now ready for deployment.

== Update the jig

To get the latest security features, we recommend that you keep your jig software up to date.

To update the jig's operating system and all installed software, including Secure Boot Provisioner, connect to the jig over SSH or use a terminal in the Raspberry Pi Connect screen sharing session and then run:

[source,bash]

sudo apt update && sudo apt full-upgrade -y

[[replace-pogo-pins]]
== Replace pogo pins

The Compute Module 5 Programming Jig is constructed to enable you to replace any pogo pins that become damaged.

To complete this procedure, you need the following items:

  • Replacement pogo pins
  • Tweezers
  • 3 mm Allen key

During this procedure, avoid touching the pogo pins with your bare hands; doing so might transfer grease and dirt to them.

To replace one or more pogo pins, complete the following steps:

. Ensure the jig is disconnected from the power.
. Press the top of the latch backwards to release the clamping mechanism, allow the lid to slide up, and then pivot the lid back until it stops.
. Use the Allen key to unfasten the bolts in the middle of each of the two short edges of the module bay. Retain these bolts to use for reassembly.
. Lift the module bay straight upwards and away from the pogo pins in the jig. The four guideposts at the corners ensure that you can do this without fouling the pogo pins. Retain the module bay to use for reassembly.
. Use the tweezers to grip a pogo pin that you want to replace and pull it straight upwards and out of the collar.
. Use the tweezers to insert the replacement pogo pin into the collar. Ensure that the larger diameter end with a hole in it goes into the collar first and that the smaller diameter end points upwards.
. Use the flat of the tweezers to gently press down on the pogo pin and ensure it's flush with the collar when compressed.
. After you have replaced all the pogo pins that you want to, replace the module bay.
.. Position it with the Raspberry Pi logo and text facing upwards and with the text on the edge closest to the front of the jig.
.. Line up the guideposts in the four corners of the module bay with the corresponding holes in the jig.
.. Slide the module bay down and into position. The guideposts ensure that this operation doesn't foul the pogo pins.
. Secure the module bay by reinserting the two bolts you removed earlier and tightening them with the Allen key. Don't over-tighten these bolts.

[[led-indicators]]
== LED behaviour

The jig uses LED indicators to communicate its current state. The following table describes each LED and its meaning.

There are two LED indicators on the back of the jig, JIG and DUT, and one LED on the top, STATUS.

.LED indicators on the Compute Module 5 Programming Jig
[cols="1,1,4", options="header"]
|===
| LED
| State
| Meaning

| JIG
| Off
| The jig isn't powered. Plug in the power cable to bring the jig online.

| JIG
| Solid green
| The jig is powered on.

| JIG
| Flashing green
| The jig is active; data transfer is in progress.

| JIG
| Solid red
| The jig powered on but the CPU isn't running.

| DUT
| Off
| The jig isn't powered or no CM5 is inserted.

| DUT
| Solid green
| The CM5 is detected and powered.

| DUT
| Flashing green
| The CM5 is active; data transfer is in progress.

| DUT
| Solid red
| This can indicate that the CM5 is damaged. If this light remains red with multiple different modules, it might indicate a problem with the jig. For more information, see <>.

| STATUS
| Off
| The jig is powered off. Plug in the power cable to bring the jig online.

| STATUS
| Solid red
| The jig is powered, but not yet ready to provision a CM5.

| STATUS
| Flashing blue
| Provisioning in progress. Don't remove the CM5 during this phase.

| STATUS
| Solid green
| If there isn't a CM5 in the jig, the jig is ready to begin provisioning.

If there is a CM5 in the jig, provisioning completed successfully and the CM5 can be removed.

| STATUS
| Flashing red
| Provisioning failed.
|===

== Troubleshooting

If you experience issues with the Compute Module 5 Programming Jig, use the following information to diagnose the issue.

  • If provisioning doesn't start when the CM5 is clamped in the jig, attempt the steps in <> to resolve the issue.
  • For other issues, see the xref:../security/secure-boot-provisioner.adoc#troubleshooting[Secure Boot Provisioner troubleshooting information].

[[device-not-detected]]
=== Device not detected

If the CM5 is clamped in the jig, but provisioning doesn't start, try the following:

. Ensure that the jig is powered on and connected to the network.
.. If the JIG LED indicator isn't lit, ensure that the power cable is plugged in.
.. Verify the network by connecting to the jig from another computer.

. Ensure that the CM5 is correctly seated and aligned with the pogo pins.
.. Open the clamp.
.. Reposition the CM5, ensuring that the Raspberry Pi logo is facing up and in the same orientation as the logo on the jig, and that the through-hole studs on the jig pass through all four corner holes on the CM5.
.. Ensure that the Compute Module is well-seated into the module bay recess and has no play in any horizontal direction.
.. Close the clamp again.

. Check whether the pogo pins are dirty or damaged.
.. Inspect the pogo pins for debris or damage.
.. If the pogo pins are dirty, gently clean them with a cotton swab dipped in isopropyl alcohol or a specialist cleaning fluid.

== Safety warnings

  • Disconnect the jig from the power supply before performing any maintenance.
  • Don't touch the metallic pogo pins in the module bay. They are sharp and can carry charge; you might damage the pins, the jig, or yourself.
  • Ensure that the CM5 is correctly seated in the module bay as described in <>. Seating it incorrectly can damage the pogo pins.
  • Don't remove the CM5 from the jig while the provisioning process is in progress (STATUS LED is flashing blue); this can render the CM5 unusable.
  • Don't press the unmarked button on the jig; this can interrupt provisioning and render the CM5 unusable.
  • Don't insert a Compute Module 4 into the Compute Module 5 Programming Jig.

Documentation Asciidoc Accessories Display Display Intro (`documentation/asciidoc/accessories/display/display_intro.adoc`)

== Raspberry Pi Touch Display

https://www.raspberrypi.com/products/raspberry-pi-touch-display/[Raspberry Pi Touch Display] is a 7-inch touchscreen LCD intended for interactive projects like tablets, entertainment systems, and information dashboards.

.The Raspberry Pi 7-inch Touch Display
image::images/display.png[The Raspberry Pi 7-inch Touch Display, width="70%"]

The display features a metal-framed back and comes with a Raspberry Pi display conversion board and metal stand-offs pre-installed. Download a mechanical drawing of the Touch Display https://pip.raspberrypi.com/documents/RP-008246-DS[here].

WARNING: The display must be mounted in a suitable enclosure. The enclosure, including any gaps provided for ventilation or cable entry, must ensure all parts of the circuit board are inaccessible during operation.

== Compatibility

Touch Display is compatible with Raspberry Pi B+ and later.

It isn't compatible with either Raspberry Pi Zero series or Raspberry Pi Keyboard computers, because these don't have DSI connectors.

Raspberry Pi 5 uses a different-sized DSI connector, but you can connect it to the Touch Display using a https://www.raspberrypi.com/products/display-cable/[A 22-way to 15-way flat flexible cable] (sold separately).

Raspberry Pi 5 and Raspberry Pi Compute Modules natively support connecting up to two Touch Displays.

You can mount any Raspberry Pi B+ and later to the back of the Touch Display. However, to mount Raspberry Pi B and earlier, additional mounting hardware is required to fit stand-offs to the display PCB.

== Autodetection

Raspberry Pi B+ and later devices auto-detect Touch Display.

Raspberry Pi A and B can auto-detect the display, but the capability is turned off by default and you must therefore enable it.

Raspberry Pi Compute Modules don't auto-detect DSI displays because they are intended for industrial applications where the integrator can use any and all GPIOs and interfaces for their own purposes.

== Specifications

This section describes the characteristics and capabilities of Touch Display.

=== Features

Touch Display has the following features:

  • 800 × 480px RGB LCD display
  • 24-bit RGB display capable of showing over 16 million colours
  • Multitouch supports up to ten simultaneous touch points
  • On-screen keyboard. Supports an on-screen keyboard in place of a physical keyboard
  • Integrated power. Powered directly by the host Raspberry Pi device, requiring no separate power supply
  • Backlight lifetime. 20,000 hours

=== Viewing performance

  • Industrial quality. 140 degree viewing angle horizontal, 120 degree viewing angle vertical
  • PWM backlight control and power control over I2C interface
  • Contrast ratio 500
  • Average brightness 250 cd/m^2^
  • Viewable area 154.08 × 85.92 mm
  • Viewing angle (degrees):
    ** Top - 50
    ** Bottom - 70
    ** Left - 70
    ** Right - 70

=== Power

  • Power draw 200mA at 5 V typical, at maximum brightness.

=== Dimensions and environmentals

  • Operating temperature -20 to +70 degrees centigrade
  • Storage temperature -30 to +80 degrees centigrade
  • Outer dimensions 192.96 × 110.76 mm

=== Hardware
The Touch Display box contains the following:

  • A Touch Display
  • Four standoffs and four M2.5 screws (pre-installed but removable)
  • A 15-way to 15-way flat flexible cable
  • Four jumper wires

=== Connections
Touch Display connects to a Raspberry Pi device using:

  • A DSI connector. Attach the appropriate flat flexible cable (FFC) to this to carry video and touch data.
  • The GPIO header. The supplied jumper wires carry power from the GPIO header on the Raspberry Pi to the display.

== Connect to a Raspberry Pi device

Follow the appropriate procedures for your device.

No special tools are required to connect your device to the display, but you must have the correct FFC cable ready. You also need your device, its boot media, and its power supply.

To attach your device to the display, use a Phillips/cross-head screwdriver that fits the M2.5 screws included with the display. If you don't want to attach your device to the display, you might need a longer FFC cable.

[tabs]

Raspberry Pi B+ and later:: +

[discrete]
=== Raspberry Pi B+ and later

WARNING: Disconnect your Raspberry Pi from power before starting Step 1.

[discrete]
==== Step 1. Connect the FFC to the Touch Display

Before you start, check that you have the correct flat flexible cable for your Raspberry Pi model:

  • For Raspberry Pi 5, use a 22-way to 15-way FFC.
  • For all other Raspberry Pi models, use the supplied 15-way to 15-way FFC.

To connect the FFC:

. Slide the retaining clip outwards from both sides of the FFC connector on the Touch Display.
. Insert the FFC into the Touch Display FFC connector, then slide the retaining clip back into place to secure the cable.
+
Position the metal contacts facing upwards, away from the Touch Display.
+
If connecting to a Raspberry Pi 5, and therefore using a 22-way to 15-way FFC, the 22-way end is the smaller end of the cable. Insert the larger end of the cable into the Touch Display FFC connector.

[discrete]
==== Step 2. (Optional) Mount the Raspberry Pi to the Touch Display

You can mount any Raspberry Pi B+ and later to the back of the Touch Display.

.A Raspberry Pi connected to the Touch Display
image::images/GPIO_power-500x333.jpg[Image of Raspberry Pi connected to the Touch Display, width="100%"]

To mount the device to the display:

. Align the four corner stand-offs of your Raspberry Pi with the four mounting points on the back of the Touch Display.
. Insert the M2.5 screws (included) into the four corner stand-offs and tighten until the Raspberry Pi is secure.

[discrete]
==== Step 3. Connect the FFC to the Raspberry Pi

CAUTION: Take care not to pinch the FFC in this step.

. Slide the retaining clip upwards from both sides of the FFC connector on the Raspberry Pi. This is labelled DISPLAY on Raspberry Pi 4B and earlier.
. Connect the other end of the FFC to the port on the Raspberry Pi, then slide the retaining clip back into place to secure the cable.
+
The metal contacts must face towards the Ethernet and USB-A ports.

[discrete]
==== Step 4. Connect power to the display, then power it on

WARNING: Before applying power, the display must be mounted in an enclosure that ensures all parts of the circuit board are inaccessible.

We recommend using your xref:../computers/raspberry-pi.adoc#gpio[Raspberry Pi device's GPIO header] to provide power to the Touch Display.

Alternatively, you can power the display directly with a separate micro USB power supply.

[discrete]
===== Connect to the GPIO header:

. Connect jumper wires between the 5 V and GND pins on the xref:../computers/raspberry-pi.adoc#gpio[Raspberry Pi device's GPIO] and the 5 V and GND pins on the display.
+
.The location of the Raspberry Pi headers
image::images/pi_plugs.png[Illustration of Raspberry Pi headers, width="40%"]
+
. Connect one end of the black jumper wire to pin six (GND) on the Raspberry Pi.
. Connect one end of the red jumper wire to pin four (5 V).
+
If pin six isn't available, use any other GND pin to connect the black wire.
+
If pin four isn't available, use the other 5 V pin (pin two) to connect the red wire.
+
.The location of the display's 5 V and GND pins
image::images/display_plugs.png[Illustration of display pins, width="40%"]
+
. Connect the other end of the black wire to the GND pin on the display.
. Connect the other end of the red wire to the 5 V pin on the display.
. Connect your Raspberry Pi to a power source, then turn it on. The Touch Display turns on.

[discrete]
===== Connect using a micro USB supply

If you don't want to use a Raspberry Pi to provide power to the Touch Display, you can use a micro USB power supply instead. We recommend using the https://www.raspberrypi.com/products/micro-usb-power-supply/[Raspberry Pi 12.5 W power supply] to make sure the display runs as advertised.

CAUTION: Don't connect the GPIO pins on your Raspberry Pi to the display if you choose to use micro USB for power.

. Plug in the micro USB power cable.

[discrete]
===== Power on the Raspberry Pi

. Connect your boot media to the Raspberry Pi. . Connect the Raspberry Pi to your power supply. + The Touch Display turns on when the device boots, but it can take up to one minute for Raspberry Pi OS to start displaying output on the screen.

Raspberry Pi Compute Module:: +

[discrete]
[[connect-to-cm]]
=== Raspberry Pi Compute Module

This section assumes that you're familiar with your Compute Module. For more information, see xref:../computers/compute-module.adoc[Raspberry Pi Compute Module].

You can connect a Touch Display to a Raspberry Pi Compute Module that is attached to an IO Board. A Raspberry Pi Standard-Mini FFC (sold separately) is required to do this.

Before you begin, update your Compute Module's system software and firmware to the latest version.

[discrete]
==== Step 1. Specify the display in config.txt

Raspberry Pi Compute Modules don't automatically detect Touch Displays.

Configure the Compute Module for the device it is connecting to by adding an overlay entry in config.txt. The default connection is port 1, but you can also use port 0.

To complete this step, either connect the Compute Module to a monitor, or use a remote method such as SSH or Raspberry Pi Connect's screen sharing or remote shell.

NOTE: If you're using a Raspberry Pi Compute Module that has eMMC memory, make sure you edit the configuration file that is used to boot the device: either the one stored on the eMMC or one on external boot media if you've reconfigured the boot order. For more information, see xref:../computers/compute-module.adoc#flash-compute-module-emmc[rpiboot].

To enable Touch Display:

. Boot your Compute Module, then open xref:../computers/config_txt.adoc#what-is-config-txt[/boot/firmware/config.txt].
+

  • To connect the display to DISP1/DSI1, add dtoverlay=vc4-kms-dsi-7inch to the end of the file.
  • To connect the display to DISP0/DSI0, add dtoverlay=vc4-kms-dsi-7inch,dsi0 to the end of the file.
    . Remove the display_auto_detect line, if it exists.
    . Shut down the device.

[discrete]
==== Step 2. Connect the Touch Display to the Compute Module IO Board

IMPORTANT: Disconnect the IO Board from power before continuing.

Connect the Touch Display to whichever IO Board port chosen in Step 1 (either DISP1/DSI1 or DISP0/DSI0). Once you've connected the FFC, set the appropriate jumpers, then connect the power cables between the display and the board.

To connect to the Touch Display:

. Slide the retaining clip outwards from both sides of the FFC connector on the Touch Display.
. Insert one end of the FFC into the Touch Display FFC connector, then slide the retaining clip back into place to secure the cable.
. Insert the other end of the FFC into the port chosen in Step 1, then slide the retaining clip back into place.
. Reference the table below and set the jumpers that correspond to the overlay entry you created in Step 1.
+
[cols="1,2,2"]
|===
|Display |Board |Action

|DISP1/DSI1
|CM1, CM3, CM3+, or CM4S on the CMIO1 or CMIO3 Boards.
|Connect GPIO 0 to CD1_SDA and 1 to CD1_SCL with jumper cables.

|DISP1/DSI1
|CM4 on the CM4IO Board.
|No additional jumpers are required.

|DISP1/DSI1
|CM5 on the CM5IO Board.
|Add jumpers to J6, as indicated on the silkscreen.

|DISP0/DSI0
|CM1, CM3, CM3+, or CM4S on the CMIO1 or CMIO3 Boards.
|Connect GPIO 28 to CD0_SDA and 29 to CD0_SCL with jumper cables.

|DISP0/DSI0
|CM4 on the CM4IO Board.
|Add jumpers to J6, as indicated on the silkscreen.

|DISP0/DSI0
|CM5 on the CM5IO Board.
|No additional jumpers are required.
|===
+
. Connect one end of the black jumper wire to pin six (GND) of the GPIO header on the IO Board.
. Connect one end of the red jumper wire to pin four, 5 V, of the GPIO header on the IO Board.
+
.The location of the Raspberry Pi GPIO headers on an CM4IO Board.
image::images/cmio4pins.png[Illustration of Raspberry Pi GPIO header on a CM4IO board, width="40%"]
+
. Connect the other end of the black wire to the GND pin on the display.
. Connect the other end of the red wire to the 5 V pin on the display.
+
.The location of the display's 5 V and GND pins
image::images/display_plugs.png[Illustration of display pins, width="40%"]

[discrete]
==== Step 3. Power on the Compute Module

WARNING: Before applying power, the display must be mounted in an enclosure that ensures all parts of the circuit board are inaccessible.

To power on the Compute Module:

. Connect the boot media to the Compute Module – skip this if you're booting from eMMC. . Connect the Raspberry Pi device to the power supply. . If the IO Board has one, press and release the *Power Button*. + The Touch Display turns on when the device boots, but it can take up to one minute for Raspberry Pi OS to start displaying output on the screen.

======

== Troubleshooting

Your display is now ready to use, but if it's not turning on or not displaying anything, check the following:

  • DSI connections. Check the FFC cable is seated properly at both ends, that the metal strips point towards the connections correctly, and that it is connected to the correct DSI connector.
  • Power. Check your device is powered on and has boot media attached (if required). If you're using a Compute Module with a power switch, check that it has been pressed.
  • GPIO connections. If the display is powered by your device, check that the power cables are seated properly, and connected to the correct pins on the display and the GPIO header.
  • Micro USB connection. If the display is powered by micro USB, check the connection and the power supply.
  • config.txt. If you're using a Compute Module, check the syntax of the overlay you added to config.txt in Step 1. Check also that you've specified the correct display port and that you removed any display_auto_detect line in the file.
  • EEPROM boot order. If you're using a Compute Module with onboard boot media, or you have multiple drives attached to your Compute Module, make sure the config.txt file you edited in Step 1 is on the boot media you're booting from.

If none of these things help, visit the https://forums.raspberrypi.com/viewforum.php?f=108[Raspberry Pi forums] to get further assistance.

== On-screen keyboard

Raspberry Pi OS Bookworm and later include the Squeekboard on-screen keyboard.

With Touch Display, this keyboard automatically appears when you can enter text. It automatically disappears when you can't.

For applications that don't support text entry detection, you can manually show or hide the keyboard by selecting the keyboard icon at the top-right of the taskbar.

To always show, or to always disable, the on-screen keyboard using the Raspberry Pi graphical interface:

. From the Raspberry Pi menu, go to Preferences > Control Centre > Display.
. Select Enabled always or Disabled, as required.

To permanently show, or to disable, the on-screen keyboard using the command line:

. Open a terminal, and enter sudo raspi-config.
. Navigate to the Display section of raspi-config, then choose your keyboard setting.

== Disable display

NOTE: To reverse this action, use an SSH connection (such as Raspberry Pi Connect's remote access), an HDMI display, or a separate computer with the Raspberry Pi device's boot media attached.

To disable the display when connected to a Raspberry Pi:

. Open /boot/firmware/config.txt
. Add the following line ignore_lcd=1
. Reboot by typing sudo reboot in the command line.

== Disable touchscreen

You can disable the touchscreen and continue to use the Touch Display as a standard screen.

To disable the touchscreen:

. Open /boot/firmware/config.txt
. Add the following line disable_touchscreen=1
. Reboot by typing sudo reboot into the command line.

== Change display orientation

If you're using Raspberry Pi OS with a desktop environment, you can change the orientation of Touch Display with the Raspberry Pi Control Centre application. This allows you to independently change the orientation of multiple connected displays.

If you're using Raspberry Pi OS Lite (which has no desktop environment), you can change the orientation of Touch Display by editing /boot/firmware/cmdline.txt. However, if you have multiple displays connected, this method changes the orientation of them all.

There are four orientations to choose from:

  • Normal (default). Portrait format.
  • Left. Display rotated 90 degrees clockwise.
  • Inverted. Display rotated 180 degrees.
  • Right. Display rotated 270 degrees clockwise.

=== With the desktop

To change the display orientation using the Raspberry Pi desktop:

. Go to Preferences > Control Centre > Screens.
. Right-click the rectangle in the layout editor that represents your Touch Display (likely labelled DSI-1).
. Select Orientation.
. Choose between Normal, Left, Inverted, or Right, to rotate the display.
. Select Apply, then select OK to keep your change or Cancel to discard it.

=== With the kernel command line

NOTE: It's not possible to rotate the DSI display separately from the HDMI display with cmdline.txt. When DSI and HDMI connections are used simultaneously, they share the same rotation value.

To change the display orientation in console mode by editing the kernel command line:

. Open the `/boot/firmware/cmdline.txt` file, which contains parameters that Raspberry Pi OS reads when it boots. . Add the following to the end of the file, replacing `` with the number of degrees clockwise to rotate by (`0`, `90`, `180`, or `270`): + [source,ini]

video=DSI-1:800x480@60,rotate=

The rotate= setting only rotates the text-mode console. For applications that write directly to DRM, such as cvlc or the libcamera apps, use the rotation options that come with them (if available).

== Change display brightness

. Go to Preferences > Control Centre > Screens.
. Right-click the rectangle in the layout editor that represents your Touch Display (likely labelled DSI-1).
. Select Brightness.
. Choose a brightness level.
+
The brightness level changes immediately.

== Customise touchscreen settings

NOTE: These settings are only required when rotating the display and using touch inputs in a non-desktop environment.

Use the Device Tree overlay to tell Raspberry Pi OS how to configure the Touch Display at boot. The overlay is called vc4-kms-dsi-7inch.

To modify the Device Tree overlay in the boot configuration:

. Open /boot/firmware/config.txt.
. Add the required Device Tree parameters to a dtoverlay line, separated by commas. See the Device Tree options table for details.

=== Device Tree options

The vc4-kms-dsi-7inch overlay supports the following options:

[cols="1,2", options="header"]

|===
| DT parameter | Action

| sizex
| Sets X touch resolution (default 800)

| sizey
| Sets Y touch resolution (default 480)

| invx
| Invert X coordinates

| invy
| Invert Y coordinates

| swapxy
| Swap X and Y coordinates

| `disable_touch` | Disables the touch overlay |===

  • Booleans (invx, invy, swapxy, and disable_touch) default to true if present, but you can set them to false using the suffix =0.
  • Integers (`sizex` and `sizey`) require a number, for example, `sizey=240`.

Example

In the following example the X touch resolution is set to 400 pixels, and both X and Y coordinates are inverted:

[source,ini]

dtoverlay=vc4-kms-dsi-7inch,sizex=400,invx,invy

=== Rotate touch input

WARNING: Rotating touch input using the device tree can cause conflicts with your input library. When possible, configure touch event rotation in your input library or desktop.

Rotation of touch input is independent of the orientation of the display itself.

To change touch input orientation:

. Open xref:../computers/config_txt.adoc[/boot/firmware/config.txt].
. Add dtoverlay at the end of file.
. Reboot using sudo reboot from the command line.

[source,ini]

dtoverlay=vc4-kms-dsi-7inch,invx,invy

Then, disable automatic display detection by removing the following line from config.txt, if it exists:

[source,ini]

display_auto_detect=1


Documentation Asciidoc Accessories Keyboard And Mouse Connecting Things (`documentation/asciidoc/accessories/keyboard-and-mouse/connecting-things.adoc`)

== Connecting it all Together

This is the configuration we recommend for using your Raspberry Pi, official keyboard and hub, and official mouse together. The hub on the keyboard ensures easy access to USB drives, and the mouse's cable is tidy, while being long enough to allow you to use the mouse left- or right-handed.

image::images/everything.png[width="80%"]

NOTE: It is important that the power supply is connected to the Raspberry Pi and the keyboard is connected to the Raspberry Pi. If the power supply is connected to the keyboard, with the Raspberry Pi powered by the keyboard, the keyboard doesn't operate correctly.


Documentation Asciidoc Accessories Keyboard And Mouse Getting Started Keyboard (`documentation/asciidoc/accessories/keyboard-and-mouse/getting-started-keyboard.adoc`)

== Getting Started with your Keyboard

Our official keyboard includes three host USB ports for connecting external devices, such as USB mice, USB drives, and other USB- controlled devices.

The product's micro USB port is for connection to the Raspberry Pi. Via the USB hub built into the keyboard, the Raspberry Pi controls, and provides power to, the three USB Type A ports.

image::images/back-of-keyboard.png[width="80%"]

=== Keyboard Features

The Raspberry Pi keyboard has three lock keys: Num Lock, Caps Lock, and Scroll Lock. There are three LEDs in the top right-hand corner that indicate which locks are enabled.

image::images/num-cap-scroll.png[width="80%"]

Num Lock:: Allows use of the red number keys on the letter keys, effectively creating a numeric keypad. This mode is enabled and disabled by pressing the Num Lock key.

Caps Lock:: Allows typing capital letters; press the Shift key to type lower-case letters in this mode. This mode is enabled and disabled by pressing the Caps Lock key.

Scroll Lock (ScrLk):: Allows use of the cursor keys for browsing web pages and spreadsheets without the mouse. This mode is enabled and disabled by pressing the ScrLk key while holding the Fn key.


Documentation Asciidoc Accessories Keyboard And Mouse Getting Started Mouse (`documentation/asciidoc/accessories/keyboard-and-mouse/getting-started-mouse.adoc`)

== Getting Started with your Mouse

Our official mouse has three buttons, which activate high-quality micro-switches. The wheel is for quick scrolling when browsing documents and web pages.

image::images/the-mouse.png[width="80%"]

Always place the mouse on a flat, stable surface while using it. The mouse optically detects movement on the surface on which it is placed. On featureless surfaces, for example, PVC or acrylic table tops, the mouse cannot detect movement. When you are working on such a surface, place the mouse on a mouse mat.


Documentation Asciidoc Accessories M2 Hat Plus About (`documentation/asciidoc/accessories/m2-hat-plus/about.adoc`)

[[m2-hat-plus]]
== About

[.clearfix]

[.left] .The Raspberry Pi M.2 HAT+ image::images/m2-hat-plus.jpg[width="100%"] [.left] .The Raspberry Pi M.2 HAT+ Compact in the Raspberry Pi Case image::images/m2-hat-plus-compact-with-case.jpg[width="100%"]

The Raspberry Pi M.2 HAT+ M Key and M.2 HAT+ Compact M Key enable you to connect M.2 peripherals such as NVMe drives and other PCIe accessories to Raspberry Pi 5's PCIe interface.

The M.2 HAT+ and M.2 HAT+ Compact adapter boards convert between the PCIe connector on Raspberry Pi 5 and a single M.2 M key edge connector. The M.2 HAT+ supports any device that uses the 2230 or 2242 form factor; the M.2 HAT+ Compact supports any device that uses the 2230 form factor.

The M.2 HAT+ is available in standard and Compact forms, each serving different use cases.

Both the M.2 HAT+ and M.2 HAT+ Compact conform to the https://pip.raspberrypi.com/documents/RP-008281-DS[Raspberry Pi HAT+ specification], which allows Raspberry Pi OS to automatically detect the HAT+ and any connected devices.

== Features

The M.2 HAT+ and M.2 HAT+ Compact both have the following features:

  • Single-lane PCIe 2.0 interface (500 MB/s peak transfer rate)
  • Support for devices that use the M.2 M key edge connector
  • Up to 3 A supply to connected M.2 devices
  • Power and activity LEDs

The M.2 HAT+ and M.2 HAT+ Compact differ in the following ways:

  • M.2 HAT+ supports devices with the 2230 or 2242 form factor; M.2 HAT+ Compact only supports the 2230 form factor.

=== Hardware

The Raspberry Pi M.2 HAT+ or M.2 HAT+ Compact box contains the following parts:

  • Ribbon cable
  • Threaded spacers
  • Screws
  • 1 knurled double-flanged drive attachment screw to secure and support the M.2 peripheral

The M.2 HAT+ also includes a 16 mm GPIO stacking header; M.2 HAT+ Compact doesn't include this component.

To use the M.2 HAT+ or M.2 HAT+ Compact, you also need:

  • A Raspberry Pi 5

[[m2-hat-plus-installation]]
== Prepare your Raspberry Pi

. Ensure that your Raspberry Pi runs the latest software. Run the following command to update: + [source,console]

$ sudo apt update && sudo apt full-upgrade

. xref:../computers/raspberry-pi.adoc#update-the-bootloader-configuration[Ensure that your Raspberry Pi firmware is up-to-date]. Run the following command to see what firmware you're running: + [source,console]

$ sudo rpi-eeprom-update

If you see December 6, 2023 or a later date, proceed to the next step. If you see a date earlier than December 6, 2023, run the following command to open the Raspberry Pi Configuration CLI: + [source,console]

$ sudo raspi-config

Under `Advanced Options` > `Bootloader Version`, choose `Latest`. Then, exit `raspi-config` with `Finish` or the *Escape* key. + Run the following command to update your firmware to the latest version: + [source,console]

$ sudo rpi-eeprom-update -a

Then, reboot with sudo reboot.

. Disconnect the Raspberry Pi from power before beginning installation.

[[standard-installation]]
== Install the M.2 HAT+

Follow these steps to install the M.2 HAT+. To install the M.2 HAT+ Compact go to <> instead.

=== (Optional) Install the Active Cooler

. The M.2 HAT+ is compatible with the Raspberry Pi 5 Active Cooler. If you have an Active Cooler, install it before installing the M.2 HAT+. +

image::images/m2-hat-plus-installation-01.png[width="60%"]

=== Install the mounting hardware

. Install the spacers using the provided screws.
. Firmly press the GPIO stacking header on top of the Raspberry Pi GPIO pins. The orientation doesn't matter, but the pins must all fit into place.
. Lift the ribbon cable holder gently from both sides on the M.2 HAT+ before disconnecting the ribbon cable.
. Lift the ribbon cable holder on the PCIe port of your Raspberry Pi from both sides, then insert the cable with the metal contact points facing towards the USB ports.
. With the ribbon cable fully and evenly inserted into the PCIe port, push the cable holder down from both sides to secure the ribbon cable firmly in place.

-- image::images/m2-hat-plus-installation-02.png[width="60%"]

=== Install the board

. Set the M.2 HAT+ on top of the spacers and use the remaining screws to secure it in place. +

image::images/m2-hat-plus-installation-03.png[width="60%"]

. Insert the ribbon cable into the slot on the M.2 HAT+. + Lift the ribbon cable holder from both sides, then insert the cable with the copper contact points facing up. With the ribbon cable fully and evenly inserted into the port, push the cable holder down from both sides to secure the ribbon cable firmly in place. +

image::images/m2-hat-plus-installation-04.png[width="60%"]

=== Install your M.2 drive

. Remove the drive attachment screw by turning the screw counter-clockwise. Insert your M.2 SSD into the M.2 key edge connector, sliding the drive into the slot at a slight upward angle. Don't force the drive into the slot: it slides in gently. +

image::images/m2-hat-plus-installation-05.png[width="60%"]

. Push the notch on the drive attachment screw into the slot at the end of your M.2 drive. Push the drive flat against the M.2 HAT+, and insert the SSD attachment screw by turning the screw clockwise until the SSD feels secure. Do not over-tighten the screw. +

image::images/m2-hat-plus-installation-06.png[width="60%"]

Congratulations, you have successfully installed the M.2 HAT+.

.Installed M.2 HAT+
image::images/m2-hat-plus-installation-07.png[width="80%"]

[[compact-installation]]
== Install the M.2 HAT+ Compact

Follow these steps to install the M.2 HAT+ Compact. To install the M.2 HAT+ go to <> instead.

=== Install the mounting hardware

. Install the spacers using the provided screws. +

image::images/m2-hat-plus-compact-installation-02.png[width="60%"]

=== Install the board

. Set the M.2 HAT+ Compact on top of the spacers and use the remaining screws to secure it in place. +

image::images/m2-hat-plus-compact-installation-03.png[width="60%"]

. Insert the ribbon cable into the PCIe port of your Raspberry Pi. + Lift the ribbon cable holder from both sides, then insert the cable with the copper contact points facing inward, towards the USB ports. With the ribbon cable fully and evenly inserted into the PCIe port, push the cable holder down from both sides to secure the ribbon cable firmly in place. +

image::images/m2-hat-plus-compact-installation-04.png[width="60%"]

=== Install your M.2 drive

. Remove the drive attachment screw by turning the screw counter-clockwise. Insert your M.2 SSD into the M.2 key edge connector, sliding the drive into the slot at a slight upward angle. Don't force the drive into the slot: it slides in gently. +

image::images/m2-hat-plus-compact-installation-05.png[width="60%"]

. Push the notch on the drive attachment screw into the slot at the end of your M.2 drive. Push the drive flat against the M.2 HAT+ Compact, and insert the SSD attachment screw by turning the screw clockwise until the SSD feels secure. Do not over-tighten the screw. +

image::images/m2-hat-plus-compact-installation-06.png[width="60%"]

Congratulations, you have successfully installed the M.2 HAT+ Compact.

.Installed M.2 HAT+ Compact
image::images/m2-hat-plus-compact-installation-07.png[width="80%"]

== Start your Raspberry Pi

If your NVMe drive is new or unformatted, it doesn't appear as an icon on the Raspberry Pi OS desktop. Additionally, commands such as sudo blkid don't show a partition UUID. You must partition and format your drive (for example, by using the Erase option in https://www.raspberrypi.com/software/[Raspberry Pi Imager]) to make it visible and accessible to the operating system. For more information, see <> or xref:../computers/configuration.adoc#automatically-mount-a-storage-device[automatically mount a storage device].

. Connect your Raspberry Pi to power. Raspberry Pi OS automatically detects the M.2 HAT+ or M.2 HAT+ Compact.
+

  • To verify the hardware is detected, open a terminal and run:

[source,console]

$ ls -l /dev/nvme*

If the drive has been correctly detected, you see /dev/nvme0 and /dev/nvme0n1.

  • If you plan to boot from the drive, see <>. Raspberry Pi Imager automatically partitions and formats the drive during installation.
  • If you plan to use the drive purely as additional storage, format the drive before xref:../computers/configuration.adoc#automatically-mount-a-storage-device[configuring automatic mounting].

. To make your drive automatically available for file access, consider xref:../computers/configuration.adoc#automatically-mount-a-storage-device[configuring automatic mounting].

WARNING: Always disconnect your Raspberry Pi from power before connecting or disconnecting a device from the M.2 slot.

== Boot from NVMe

To boot from an NVMe drive attached to the M.2 HAT+ or M.2 HAT+ Compact, complete the following steps:

. Flash Raspberry Pi OS to your NVMe drive using Raspberry Pi Imager. For more information, see xref:../computers/raspberry-pi.adoc[Installing Raspberry Pi OS].

  • If you already have Raspberry Pi OS running from an SD card, run Raspberry Pi Imager directly on your Raspberry Pi and select the NVMe drive as the target storage.
  • Alternatively, if your bootloader firmware is up to date, use the Raspberry Pi Network Installer to download and run Raspberry Pi Imager over an Ethernet connection without needing an SD card. For more information, see xref:../computers/raspberry-pi.adoc[Network installation].

. Reboot your Raspberry Pi.

  • If you don’t have an SD card inserted in your Raspberry Pi 5, it boots automatically from your NVMe drive.
  • If you do have an SD card inserted in your Raspberry Pi 5, it attempts to boot from the SD card first. You can change the boot order on your Raspberry Pi by completing the following steps:
    .. Boot your Raspberry Pi into Raspberry Pi OS using an SD card.
    .. In a terminal on your Raspberry Pi, run sudo raspi-config to open the Raspberry Pi Configuration CLI.
    .. Under Advanced Options > Boot Order, choose NVMe/USB boot.
    .. Exit raspi-config with Finish or the Escape key.
    .. Reboot your Raspberry Pi with sudo reboot.

For detailed information about NVMe boot, see xref:../computers/raspberry-pi.adoc[NVMe boot].

== Enable PCIe Gen 3

WARNING: The Raspberry Pi 5 is not certified for Gen 3.0 speeds. PCIe Gen 3.0 connections might be unstable.

To enable PCIe Gen 3 speeds, follow the instructions at xref:../computers/raspberry-pi.adoc#pcie-gen-3-0[enable PCIe Gen 3.0].

== Schematics

The schematics for the M.2 HAT+ are available as a https://pip.raspberrypi.com/documents/RP-008218-DS[PDF]

== Product brief

For more information about the M.2 HAT+ and M.2 HAT+ Compact, including mechanical specifications and operating environment limitations, see the https://pip.raspberrypi.com/documents/RP-009234-MM[product brief].


Documentation Asciidoc Accessories Monitor Monitor Intro (`documentation/asciidoc/accessories/monitor/monitor_intro.adoc`)

== Raspberry Pi Monitor

The https://www.raspberrypi.com/products/raspberry-pi-monitor/[Raspberry Pi Monitor] is a 15.6" 1920 × 1080p IPS LCD display that connects to a computer using an HDMI cable. The Monitor also requires a USB-C power source. For full brightness and volume range, this must be a USB-PD source capable of at least 1.5A of current.

.The Raspberry Pi Monitor
image::images/monitor-hero.png[The Raspberry Pi Monitor, width="100%"]

The Monitor is compatible with all models of Raspberry Pi that support HDMI output.

=== Controls

The back of the Monitor includes the following controls:

  • a button that enters and exits Standby mode (indicated by the ⏻ (power) symbol)
  • buttons that increase and decrease display brightness (indicated by the 🔆 (sun) symbol)
  • buttons that increase and decrease speaker volume (indicated by the 🔈 (speaker) symbol)

=== On screen display messages

The on-screen display (OSD) can show the following messages:

[cols="1a,6"]
|===
| Message | Description

| image::images/no-hdmi.png[No HDMI signal detected]
| No HDMI signal detected.

| image::images/no-valid-hdmi-signal-standby.png[Standby mode]
| The monitor will soon enter standby mode to conserve power.

| image::images/not-supported-resolution.png[Unsupported resolution]
| The output display resolution of the connected device is not supported.

| image::images/power-saving-mode.png[Power saving mode]
| The monitor is operating in Power Saving mode, with reduced brightness and volume, because the monitor is not connected to a power supply capable of delivering 1.5A of current or greater.
|===

Additionally, the OSD shows information about display brightness changes using the 🔆 (sun) symbol, and speaker volume level changes using the 🔈 (speaker) symbol. Both brightness and volume use a scale that ranges from 0 to 100.

TIP: If you attempt to exit Standby mode when the display cannot detect an HDMI signal, the red LED beneath the Standby button will briefly light, but the display will remain in Standby mode.

=== Position the Monitor

Use the following approaches to position the Monitor:

  • Angle the Monitor on the integrated stand.
  • Mount the Monitor on an arm or stand using the four VESA mount holes on the back of the red rear plastic housing.

IMPORTANT: Use spacers to ensure adequate space for display and power cable egress.

  • Flip the integrated stand fully upwards, towards the top of the monitor. Use the drill hole template to create two mounting points spaced 55 mm apart. Hang the Monitor using the slots on the back of the integrated stand.

.Drill hole template
image::images/drill-hole-template.png[Drill hole template, width="40%"]

=== Power the Monitor

The Raspberry Pi Monitor draws power from a 5V https://en.wikipedia.org/wiki/USB_hardware#USB_Power_Delivery[USB Power Delivery] (USB-PD) power source. Many USB-C power supplies, including the official power supplies for the Raspberry Pi 4 and Raspberry Pi 5, support this standard.

When using a power source that provides at least 1.5A of current over USB-PD, the Monitor operates in Full Power mode. In Full Power mode, you can use the full range (0%-100%) of display brightness and speaker volume.

When using a power source that does not supply at least 1.5A of current over USB-PD (including all USB-A power sources), the Monitor operates in Power Saving mode. Power Saving mode limits the maximum display brightness and the maximum speaker volume to ensure reliable operation. In Power Saving mode, you can use a limited range (0-50%) of display brightness and a limited range (0-60%) of speaker volume. When powered from a Raspberry Pi, the Monitor operates in Power Saving mode, since Raspberry Pi devices cannot provide 1.5A of current over a USB-A connection.

To switch from Power Saving mode to Full Power mode, press and hold the increase brightness button for 3 seconds.

[TIP]

If the Monitor flashes on and off, your USB power supply is not capable of providing sufficient current to power the monitor. This can happen if you power the Monitor from a Raspberry Pi 5, 500, or 500+ which is itself powered by a 5V/3A power supply. Try the following fixes to stop the Monitor from flashing on and off:

  • reduce the display brightness and volume (you might have to connect your monitor to another power supply to access the settings)
  • switch to a different power source or cable

====

=== Specification

Diagonal: 15.6"

Resolution: 1920 × 1080

Type: IPS LCD

Colour gamut: 45%

Contrast: 800:1

Brightness: 250cd/m^2^

Screen coating: Anti-glare 3H hardness

Display area: 344 × 193 mm

Dimensions: 237 × 360 × 20 mm

Weight: 850g

Supported resolutions:

  • 1920 × 1080p @ 50/60Hz
  • 1280 × 720p @ 50/60Hz
  • 720 × 576p @ 50/60Hz
  • 720 × 480p @ 50/60Hz
  • 640 × 480p @ 50/60Hz

Input: HDMI 1.4; supports DDC-CI

Power input: USB-C; requires 1.5A over USB-PD at 5V for full brightness and volume range

Power consumption: 4.5-6.5 W during use; < 0.1 W at idle

Speakers: 2 × 1.2 W (stereo)

Ports: 3.5 mm audio jack

=== Mechanical drawing

.Mechanical Drawing
image::images/mechanical-drawing.png[Mechanical drawing, width="80%"]


Documentation Asciidoc Accessories Sd Cards About (`documentation/asciidoc/accessories/sd-cards/about.adoc`)

== About

.A Raspberry Pi SD Card inserted into a Raspberry Pi 5
image::images/sd-hero.jpg[width="80%"]

SD card quality is a critical factor in determining the overall user experience for a Raspberry Pi. Slow bus speeds and lack of command queueing can reduce the performance of even the most powerful Raspberry Pi models.

Raspberry Pi official microSD cards support DDR50 and SDR104 bus speeds. Additionally, Raspberry Pi SD cards support the command queueing (CQ) extension, which permits some pipelining of random read operations, ensuring optimal performance.

You can even buy Raspberry Pi SD cards pre-programmed with the latest version of Raspberry Pi OS.

Raspberry Pi SD cards are available in the following sizes:

  • 32 GB
  • 64 GB
  • 128 GB

== Specifications

.A 128 GB Raspberry Pi SD Card
image::images/sd-cards.png[width="80%"]

Raspberry Pi SD cards use the SD6.1 SD specification.

Raspberry Pi SD cards use the microSDHC/microSDXC form factor.

Raspberry Pi SD cards have the following Speed Class ratings: C10, U3, V30, A2.

The following table describes the read and write speeds of Raspberry Pi SD cards using 4 kB of random data:

|===
| Raspberry Pi Model | Interface | Read Speed | Write Speed

| 4 | DDR50 | 3,200 IOPS | 1,200 IOPS
| 5 | SDR104 | 5,000 IOPS | 2,000 IOPS
|===


Documentation Asciidoc Accessories Sense Hat Hardware (`documentation/asciidoc/accessories/sense-hat/hardware.adoc`)

== Features

The Sense HAT has an 8×8 RGB LED matrix and a five-button joystick, and includes the following sensors:

  • Gyroscope
  • Accelerometer
  • Magnetometer
  • Temperature
  • Barometric pressure
  • Humidity
  • Colour and brightness

Schematics and mechanical drawings for the Sense HAT and the Sense HAT V2 are available for download on the https://pip.raspberrypi.com/categories/676-raspberry-pi-sense-hat[Product Information Portal].

=== LED matrix

The LED matrix is an RGB565 https://www.kernel.org/doc/Documentation/fb/framebuffer.txt[framebuffer] with the id RPi-Sense FB. The appropriate device node can be written to as a standard file or mmap-ed. The included snake example shows how to access the framebuffer.

=== Joystick

The joystick comes up as an input event device named Raspberry Pi Sense HAT Joystick, mapped to the arrow keys and Enter. It is supported by any library which is capable of handling inputs or directly through the https://www.kernel.org/doc/Documentation/input/input.txt[evdev interface]. Suitable libraries include https://www.libsdl.org/[SDL], https://www.pygame.org/docs/[pygame], and https://python-evdev.readthedocs.org/en/latest/[python-evdev]. The included snake example shows how to access the joystick directly.


--- METRICS ---