Как настроить TFT LCD дисплей для Raspberry Pi

Поделитесь статьей

For embedded software engineers, hardware hackers, and industrial IoT architects, the Raspberry Pi is the undisputed king of rapid prototyping. In its default “headless” state (accessed via SSH), it is a silent, invisible workhorse. But the moment you need a Human-Machine Interface (HMI)—whether you are building a smart home thermostat, a factory floor control panel, or a bespoke medical device prototype—you must bridge the gap between code and physical interaction.

Integrating a tft lcd raspberry pi display is often the most frustrating rite of passage in hardware development. If you have ever plugged a screen into your Pi’s GPIO headers only to be greeted by the infamous “White Screen of Death,” you know exactly how complex this integration can be.

This comprehensive, step-by-step engineering guide will walk you through the precise hardware connections, the underlying Linux Device Tree overlays, and the modern Wayland/X11 software configurations required to successfully deploy a TFT LCD on a Raspberry Pi.

1. Architectural Triage: Understanding Your Display Interface

Before you touch a single jumper wire or type sudo nano, you must understand Вписаться your display communicates with the Raspberry Pi. The method of connection entirely dictates the frame rate, the CPU overhead, and the software drivers required.

There are four primary ways to connect a tft lcd raspberry pi display.

A. The SPI Interface (Serial Peripheral Interface)

This is the most common interface for small displays (1.5″ to 3.5″). These displays sit directly on the 40-pin GPIO header.

  • The Reality: SPI is a serial protocol. It sends pixel data one bit at a time. It is inherently slow.
  • Use Case: Perfect for static user interfaces, sensor readouts, or text-heavy dashboards.
  • Ограничения: Do not expect to play 60 FPS video on an SPI screen. You are physically limited by the SPI bus speed (typically capped around 32MHz to 48MHz), which yields a maximum of 15 to 25 FPS on a 320×480 resolution screen. High CPU overhead is required to push the pixels.

B. The MIPI DSI Interface (Display Serial Interface)

This utilizes the dedicated ribbon cable connector on the Raspberry Pi board (labeled “DISPLAY” or “MIPI” on Pi 5 models).

  • The Reality: DSI is a high-speed, differential signaling interface that taps directly into the Raspberry Pi’s Broadcom GPU.
  • Use Case: The absolute best option for fluid UIs, video playback, and complex graphics. It frees up the CPU entirely and leaves your GPIO pins available for other sensors.
  • Ограничения: DSI displays are typically limited to official Raspberry Pi screens or specific third-party models with custom bridge chips.

C. The DPI Interface (Display Parallel Interface)

DPI uses almost all the GPIO pins (up to 24 pins for RGB888 color, plus sync signals) to drive a raw LCD panel.

  • The Reality: It offers HDMI-like speeds and zero CPU overhead without using the bulky HDMI port.
  • Use Case: Custom arcade cabinets or industrial builds where the HDMI port is blocked or needed for a secondary screen.
  • Ограничения: You lose almost all of your GPIO pins. You cannot easily add I2C sensors or SPI buttons.

D. The HDMI / USB Combo

Large tft lcd raspberry pi screens (5-inch to 10-inch) often use standard HDMI for the display signal and a USB cable for the touch interface.

  • The Reality: Plug-and-play simplicity. The Pi treats it like a standard desktop monitor.
  • Ограничения: Bulky cabling. It is difficult to integrate cleanly into a slim, bespoke product enclosure.

For the purpose of this hands-on guide, we will focus on the most notoriously difficult integration: the SPI-based GPIO display, as it requires the deepest understanding of the Linux kernel.


2. Hardware Assembly: Wiring the SPI Display

If your SPI display does not snap directly onto the GPIO headers as a “HAT” (Hardware Attached on Top), you will need to wire it manually.

The Golden Rule of Hardware

Never wire a display while the Raspberry Pi is powered on. Hot-plugging GPIO pins can cause a voltage spike that will instantly destroy the LCD driver IC or, worse, fry the Raspberry Pi’s Broadcom SoC.

The SPI Pinout Anatomy

To make a standard SPI tft lcd raspberry pi screen work, you must connect the power, the SPI bus (MOSI, SCLK, CE), and the control pins (DC, Reset).

Here is the standard mapping you must execute using female-to-female jumper wires:

Display PinФункцияRaspberry Pi Physical PinRaspberry Pi BCM GPIO
VCC/5VПитаниеPin 2 or 45V Power
GNDGroundPin 6 (or any GND)Ground
MOSI (SDI)Data to ScreenPin 19GPIO 10 (SPI0_MOSI)
SCLK (SCK)SPI ClockPin 23GPIO 11 (SPI0_SCLK)
CS / CE0Chip SelectPin 24GPIO 8 (SPI0_CE0)
DC / RSДанные/КомандаКонтакт 22 (Общий по умолчанию)GPIO 25
RST / RESСбросКонтакт 18 (Общий по умолчанию)GPIO 24
BLK / LEDПодсветкаКонтакт 12 (ШИМ) или 3.3ВGPIO 18 (ШИМ0)

Техническая рекомендация: Международный форум по аккредитации (IAF) DC (Данные/Команда) Контакт имеет решающее значение. SPI передаёт только единицы и нули. Контроллер дисплея (например, ILI9341) должен знать, являются ли эти единицы и нули данными цвета пикселей или системными командами (например, “включить экран”). Контакт DC переключается в высокий или низкий уровень, чтобы сообщить контроллеру, как интерпретировать входящие данные SPI.


3. Конфигурация ядра: Наложение дерева устройств (Device Tree Overlay)

Вы подключили экран. Вы включаете Pi. Экран загорается, но он полностью белый. Это Белый экран смерти. Это означает, что подсветка получает питание, но ядро Raspberry Pi не знает о существовании экрана, поэтому не отправляет никаких данных о пикселях.

Мы должны сообщить ядру Linux, как общаться с экраном. В современной Raspberry Pi OS (Bookworm и новее) это делается с помощью Наложений Дерева Устройств (dtoverlay).

Шаг 3.1: Включение шины SPI

Во-первых, необходимо разблокировать аппаратную часть SPI на Pi.

  1. Подключитесь к Raspberry Pi по SSH.
  2. Запустите инструмент конфигурации:Bashsudo raspi-config
  3. Перейдите в Параметры интерфейсов (Interface Options) -> SPI -> Выберите Да для включения.
  4. Перезагрузите Pi.

Шаг 3.2: Определите свой контроллер дисплея (Драйвер)

TFT LCD панели — это просто стекло. Ими управляет микросхема, приклеенная к задней части стекла (или на печатной плате). Наиболее распространенные контроллеры на рынке производителей в Европе/США:

  • ILI9341 (Очень распространен для экранов 2.4″ — 2.8″)
  • ST7789 (Распространен для IPS экранов 1.3″ — 2.0″)
  • ILI9486 (Распространен для экранов 3.5″)

Вы необходимо должны знать, какой контроллер использует ваш экран. Проверьте техническую документацию производителя.

Шаг 3.3: Редактирование config.txt

В современной Raspberry Pi OS файл конфигурации загрузки был перемещен.

Откройте его с помощью текстового редактора nano:

Bash

sudo nano /boot/firmware/config.txt

(Примечание: в старых версиях ОС Bullseye путь был просто /boot/config.txt)

Прокрутите до конца файла и добавьте конкретное наложение (overlay) для вашего драйвера. Например, если вы используете экран ILI9341 , подключенный точно так, как в таблице выше:

Ini, TOML

# Включить SPI

Для дисплея ST7789 (часто используется в Adafruit PiTFT):

Ini, TOML

dtoverlay=adafruit-st7789v-hAT,fps=30

Сохраните файл (Ctrl+O, Enter) и выйдите (Ctrl+X).

Перезагрузите Raspberry Pi: sudo reboot.

При правильной конфигурации белый экран станет черным во время загрузки, и в конечном итоге вы увидите текст консоли Linux, прокручивающийся на маленьком экране.


4. Современные графические архитектуры: FBCP vs. DRM/KMS

Именно здесь многие руководства 2020 года вводят в заблуждение.

Исторически, если вы хотели зеркалировать основной HDMI-рабочий стол на маленький SPI TFT LCD дисплей Raspberry Pi, вы использовали инструмент под названием fbcp (Framebuffer Copy). It took a snapshot of the primary GPU framebuffer (fb0) and aggressively copied it to the SPI screen’s framebuffer (fb1).

The Wayland Reality Check

Starting with Raspberry Pi OS Bookworm, the X11 windowing system and the legacy framebuffer architecture were abandoned. The Pi now uses Wayland (specifically the Wayfire compositor) and the DRM/KMS (Direct Rendering Manager / Kernel Mode Setting) architecture.

fbcp no longer works on modern Raspberry Pi OS.

How to drive the UI today:

If you are building an industrial HMI or a custom device, you should not be trying to run a full desktop GUI on a 3.5-inch screen anyway. Instead, you should write an application that renders directly to the DRM/KMS layer using hardware-accelerated libraries.

The Professional Stack:

  • LVGL (Light and Versatile Graphics Library): An open-source C library that writes directly to the Linux DRM subsystem. It is incredibly lightweight and perfect for SPI screens.
  • Qt / PyQt: You can configure Qt applications to run using the eglfs или linuxfb plugins, bypassing the Wayland desktop entirely and drawing your UI directly to the TFT LCD.
  • Kiosk Mode: If you absolutely must use web technologies (HTML/CSS/JS), you can configure Wayfire to boot directly into a fullscreen Chromium browser pointing to a local Node.js server.

5. Calibrating the Touch Interface

If your tft lcd raspberry pi has a touch overlay, getting the screen to display an image is only half the battle. Now you must ensure that when you tap the top-left corner, the mouse cursor actually goes to the top-left corner.

Resistive vs. Capacitive Touch

  • Resistive (XPT2046 Controller): Requires pressure. Very common on cheap 3.5″ SPI screens. Requires intense calibration because the analog resistance varies by temperature and manufacturing batch.
  • Capacitive (FT6236 / Goodix Controllers): Like a smartphone. Generally requires zero calibration as the grid is digitally mapped to the pixels at the factory. Uses the I2C bus instead of SPI.

Calibrating an XPT2046 Resistive Screen under Wayland/Libinput

Because X11 is dead, the old xinput_calibrator tool is obsolete. Today, touchscreens are handled by libinput и udev rules.

  1. First, ensure the touch driver is loaded in /boot/firmware/config.txt:Ini, TOMLdtoverlay=ads7846,cs=1,penirq=17,penirq_pull=2,speed=1000000,keep_vref_on=1
  2. Reboot and install the libinput calibration tool:Bashsudo apt install weston
  3. Wayfire (the default compositor) uses a specific configuration file for input devices. You must edit the Wayfire config to map the touch matrix correctly.Open ~/.config/wayfire.ini and locate the [input] section. You will need to add a calibration matrix.(Note: The exact matrix depends on whether your screen is landscape or portrait. A default identity matrix is 1 0 0 0 1 0.)

If your touch axes are inverted (moving your finger up moves the mouse down), you must flip the matrix values. For example, to invert the Y-axis, your udev rule or Wayfire config matrix would change the Y-scale multiplier to a negative value.


6. Overclocking the SPI Bus (Chasing Frames)

If your user interface feels sluggish, you can attempt to overclock the SPI bus to squeeze a few more frames per second out of the tft lcd raspberry pi.

Open /boot/firmware/config.txt and locate your driver overlay line. Add the скорость parameter (measured in Hz).

Ini, TOML

dtoverlay=rpi-display,speed=48000000

This requests a 48 MHz SPI clock.

Предупреждение: The Raspberry Pi’s SPI core clock operates on a divider system. If you request 48MHz, you will likely get it. If you request 60MHz, the Pi might divide its core clock and drop you down to 31MHz instead, making it slower. Furthermore, if you push the speed too high (e.g., 80000000), the physical jumper wires will act as antennas, introducing electromagnetic interference (EMI) that corrupts the data, resulting in a screen filled with static “snow” or inverted colors. Keep your wires as short as physically possible (under 10cm) if you intend to push the SPI speed.


Conclusion: The Engineering Payoff

Setting up a tft lcd raspberry pi is rarely a plug-and-play experience. It demands a working knowledge of serial protocols, Linux kernel overlays, and display rendering architectures. However, mastering this process is a critical skill for any hardware developer.

By bypassing bulky HDMI monitors and natively driving an SPI or DSI display, you unlock the ability to design highly integrated, professional-grade hardware prototypes. Whether you are building an industrial telemetry dashboard or a bespoke digital audio player, that glowing piece of glass transforms your invisible code into a tangible, interactive product.


Часто задаваемые вопросы (ЧЗВ)

Q1: Why is my SPI display completely white when I boot the Pi?

О: This is the most common issue. A white screen means the backlight has 3.3V or 5V power, but the display controller IC is not receiving data.

  1. Проверьте проводку: Убедитесь в правильности подключения линий MOSI, SCLK, а особенно CS (Chip Select) и DC (Data/Command).
  2. Проверьте конфигурацию: Убедитесь, что dtparam=spi=on активен в вашем /boot/firmware/config.txt.
  3. Проверьте драйвер: Убедитесь, что вы загружаете правильный dtoverlay для конкретного чипа контроллера вашего экрана (например, ILI9341 или ST7789).

Вопрос 2: Можно ли запустить стандартный графический интерфейс рабочего стола (например, Chromium или VLC) на 3,5-дюймовом SPI-экране?

О: Технически — да, но на практике — нет. Шина SPI просто не обладает достаточной пропускной способностью для передачи 320×480 пикселей с частотой 60 кадров в секунду. Воспроизведение видео приведёт к сильному разрыву кадров, а интерфейс рабочего стола будет крайне медленным. Для работы с графической средой или видео необходимо использовать дисплей с интерфейсом MIPI DSI или HDMI. SPI-экраны предназначены для простых статических интерфейсов, кнопок и текстовых данных.

Вопрос 3: Нажатия на сенсорном экране регистрируются, но курсор мыши перемещается в противоположную сторону экрана. Как это исправить?

О: Оси сенсорного ввода инвертированы относительно осей дисплея. Это происходит, если вы поворачиваете дисплей программно (например, display_lcd_rotate=2), но не применяете поворот к матрице сенсорного ввода. Необходимо применить матрицу преобразования через udev правила или в конфигурации Wayfire/X11, чтобы поменять местами оси X и Y или инвертировать их.

Вопрос 4: Не перегрузит ли подключение ЖК-экрана блок питания Raspberry Pi?

О: Возможно, в зависимости от модели Raspberry Pi и размера экрана. Для Raspberry Pi 4 или 5 требуется надёжный блок питания на 5,1 В / от 3 А до 5 А. 3,5-дюймовый SPI-экран потребляет около 100–150 мА для светодиодной подсветки, что безопасно для выводов 5V GPIO. Однако 7- или 10-дюймовый экран может потреблять от 500 мА до 1 А. Для экранов размером более 5 дюймов рекомендуется запитывать экран от отдельного внешнего источника питания через USB, а не от выводов GPIO Raspberry Pi, чтобы избежать троттлинга из-за просадки напряжения (индикатор — жёлтая иконка молнии).

Вопрос 5: Я хочу создать коммерческий продукт на основе Raspberry Pi Compute Module. Стоит ли использовать SPI?

О: Нет. Если вы разрабатываете коммерческий продукт на основе Compute Module 4 (CM4) или CM5, следует развести линии MIPI DSI или использовать параллельный интерфейс DPI на вашей пользовательской плате-носителе. Это переложит обработку изображения на аппаратный графический процессор, освободив центральный процессор для выполнения логики вашего приложения и обеспечив плавную профессиональную анимацию с частотой 60 кадров в секунду.