配置
raspi-config
工具
Edit this on GitHub
raspi-config
是Raspberry Pi配置工具,最初由 Alex Bradbury 编写. 要打开配置工具,请在命令行中键入以下内容:
sudo raspi-config
sudo
是必需的,因为您将更改不属于pi用户的文件。
Note
|
如果您使用的是Raspberry Pi桌面,那么您可以使用 Preferences 菜单中的 Raspberry Pi Configuration 图形应用程序来配置。
|
然后,您应该会看到一个蓝屏,灰色框中有选项:
Note
|
显示的菜单可能略有不同。 |
使用上下箭头键在可用选项之间移动突出显示的选项。按右箭头键将跳出“选项”菜单,并将您带到 <Select>
和 <Finish>
。按下left将带您回到选项。或者,您可以使用Tab键在这些之间切换。
一般来说,raspi-config
旨在提供进行最常见的配置更改的功能。这可能会导致对 /boot/config.txt
和各种标准Linux配置文件的自动编辑。有些选项需要重新启动才能生效。如果您更改了其中的任何一项,当您选择 <Finish>
按钮时, raspi-config
会询问您是否希望现在重新启动。
Note
|
在选项值的长列表(如时区城市列表)中,您还可以键入一个字母以跳到列表的该部分。例如,输入 L 将跳过您到里斯本,距离伦敦只有两个选项,以节省您一直滚动字母表的时间。
|
选项列表
Note
|
由于 raspi-config 工具的不断发展,下面的选项列表可能不是完全最新的。另请注意,不同型号的Raspberry Pi可能有不同的选择。
|
Note
|
所有选项均可通过非交互式命令行界面使用。有关更多信息,请参阅 raspi-config command line interface 上的部分。
|
Display Options
Underscan
就不会丢失;这被称为过扫描。现代的电视和显示器不需要边框,信号也不允许。如果屏幕上显示的初始文本从边缘消失,您需要启用过扫描来恢复边界。。 任何更改都将在重新启动后生效。您可以通过编辑配置 config.txt 来更好地控制设置。 在某些显示器上,尤其是监视器,禁用过扫描会使图像充满整个屏幕并修正分辨率。对于其他显示器,可能需要保持过扫描启用并调整其值。
Interfacing Options
在此子菜单中,有以下选项可以启用/禁用:相机、SSH、VNC、SPI、I2C、串行、1 线和远程 GPIO。
SSH
使用 SSH 启用/禁用对Raspberry Pi的远程命令行访问。 SSH允许您从另一台计算机远程访问Raspberry Pi的命令行。默认情况下,SSH 处于禁用状态。在 SSH 文档页面 上阅读有关使用 SSH 的更多信息。如果将Raspberry Pi直接连接到公共网络,则不应启用SSH,除非您为所有用户设置了安全密码。
Overclock
在某些型号上,可以使用此工具对Raspberry Pi的 CPU 进行超频。您可以实现的超频会有所不同;超频过高可能会导致不稳定。选择此选项将显示以下警告:
*请注意,超频可能会缩短Raspberry Pi的使用寿命。*如果达到一定水平的超频导致系统不稳定,请尝试更适度的超频。在启动过程中按住 Shift 键可暂时禁用超频。
Advanced Options
Expand Filesystem
此选项将扩展您的安装以填充整个SD卡,从而为您提供更多空间用于文件。您需要重新启动Raspberry Pi才能使其可用。
Warning
|
没有确认:选择该选项会立即开始分区扩展。 |
Boot Order
在Raspberry Pi 4 上,您可以指定如果未插入 SD 卡,是从 USB 还是网络启动。有关详细信息,请参阅 此页面 。
raspi-config
命令行接口
raspi-config
工具还可以在非交互模式下运行,这对于设置Raspberry Pi映像以进行分发非常有用。
sudo raspi-config nonint <command> <arguments>
sudo
是必需的,因为您将更改不以 pi
用户身份拥有的文件。
Note
|
在参数中 0 和 1 没有一致的含义。每个功能都将记录该功能 0 和 1 的含义。
|
List of Options
Note
|
由于该工具的不断发展,下面的选项列表可能不是完全最新的。另请注意,不同型号的Raspberry Pi可能有不同的选择。 |
Wireless LAN
允许设置无线局域网SSID和密码。
sudo raspi-config nonint do_wifi_ssid_passphrase <ssid> <passphrase> [hidden] [plain]
hidden 0
= 可见,1
= 隐藏。默认为可见。
普通:如果 plain 是 1,则默认,密码短语被引用
例:
sudo raspi-config nonint do_wifi_ssid_passphrase myssid mypassphrase sudo raspi-config nonint do_wifi_ssid_passphrase myssid mypassphrase 1 # Hidden SSID sudo raspi-config nonint do_wifi_ssid_passphrase myssid '"mypassphrase"' 0 0 # Visible SSID, passphrase quoted
Audio
指定音频输出目标。
sudo raspi-config nonint do_audio <N>
Password
您可以更改“默认”用户密码。
Note
|
直到最近,Raspberry Pi操作系统上的默认用户都是 pi 密码 raspberry .默认用户现在使用配置向导在首次引导时设置。
|
sudo raspi-config nonint do_change_pass
Note
|
这不会检查交互式标志,并且将显示全屏消息。 |
Display Options
Resolution
定义系统在没有连接电视或显示器的情况下启动时要使用的默认 HDMI/DVI 视频分辨率。如果启用了 VNC 选项,这可能会对 RealVNC 产生影响。
sudo raspi-config nonint do_resolution <group> <mode>
Group: 2
= DMT, 其他 = CEA
Mode: 0
= 默认自动
Underscan
旧电视机产生的图像大小差异很大;有些柜子与屏幕重叠。因此,电视画面被赋予了黑色边框,因此不会丢失任何画面;这称为过扫描。现代电视和显示器不需要边框,信号也不允许。如果屏幕上显示的初始文本从边缘消失,则需要启用过扫描以恢复边框。 任何更改都将在重新启动后生效。您可以通过编辑 config.txt 来更好地控制设置。 在某些显示器上,尤其是显示器上,禁用过扫描将使图像填满整个屏幕并校正分辨率。对于其他显示器,可能需要启用过扫描并调整其值。
sudo raspi-config nonint do_overscan <0/1>
0
- 启用过扫描
1
- 禁用过扫描
Interfacing Options
在此子菜单中,有以下选项可以启用/禁用:相机、SSH、VNC、SPI、I2C、串行、1-wire和远程 GPIO。
SSH
使用 SSH 启用/禁用对Raspberry Pi的远程命令行访问。 SSH允许您从另一台计算机远程访问Raspberry Pi的命令行。默认情况下,SSH 处于禁用状态。在 SSH 文档 上阅读有关使用 SSH 的更多信息。如果将Raspberry Pi直接连接到公共网络,则不应启用SSH,除非您为所有用户设置了安全密码。
sudo raspi-config nonint do_ssh <0/1>
0
- 启用 SSH
1
- 禁用 SSH
SPI
启用/禁用 SPI 接口并自动加载 SPI 内核模块,这是 PiFace 等产品所需的。
sudo raspi-config nonint do_spi <0/1>
0
- 启用 SPI
1
- 禁用 SPI
Serial
在串行连接上启用/禁用 shell 和内核消息。
sudo raspi-config nonint do_serial <0/1/2>
0
- 通过串行端口启用控制台
1
- 禁用串行端口
2
- 启用串行端口
Overclock
在某些型号上,可以使用此工具对Raspberry Pi的 CPU 进行超频。您可以实现的超频会有所不同;超频过高可能会导致不稳定。选择此选项将显示以下警告:
请注意,超频可能会缩短Raspberry Pi的使用寿命。 如果达到一定水平的超频导致系统不稳定,请尝试更适度的超频。在启动过程中按住 Shift 键可暂时禁用超频。
sudo raspi-config nonint do_overclock <setting>
设置是以下设置之一:
- None
- 默认
- Modest
- 超频至最大值的50%
- Medium
- 超频至最大值的 75%
- High
- 超频至最大值的100%
- Turbo
- 超频至最大值的 125%
Localisation Options
本地化子菜单为您提供了以下选项供您选择:键盘布局、时区、区域设置和无线 LAN 国家/地区代码。
Time Zone
选择您的本地时区,从区域开始,例如欧洲,然后选择一个城市,例如伦敦。键入一个字母以将列表向下跳到字母表中的该点。
sudo raspi-config nonint do_change_timezone <timezone> sudo raspi-config nonint do_change_timezone America/Los_Angeles
Advanced Options
Expand Filesystem
此选项将扩展您的安装以填充整个SD卡,从而为您提供更多空间用于文件。您需要重新启动Raspberry Pi才能使其可用。
Warning
|
没有确认:选择该选项会立即开始分区扩展。 |
sudo raspi-config nonint do_expand_rootfs
Network Interface Names
启用或禁用可预测的网络接口名称。
sudo raspi-config nonint do_net_names <0/1>
0
- 启用可预测的网络接口名称
1
- 禁用可预测的网络接口名称
Boot Order
在Raspberry Pi 4 上,您可以指定如果未插入 SD 卡,是从 USB 还是网络启动。有关详细信息,请参阅 此页面。
sudo raspi-config nonint do_boot_order <B1/B2/B3>
-
B1
- SD 卡启动 - 从 SD 卡启动(如果可用),否则从 USB 启动 -
B2
- USB 启动 - 如果可用,则从 USB 启动,否则从 SD 卡启动 -
B3
- 网络启动 - 如果 SD 卡启动失败,则从网络启动
配置网络
Edit this on GitHub
提供了一个GUI,用于在Raspberry Pi操作系统中设置带有桌面的无线连接。但是,如果您使用的是Raspberry Pi OS Lite,则可以从命令行设置无线网络。
使用桌面
可以通过菜单栏右侧的网络图标进行无线连接。如果您使用的是具有内置无线连接的Raspberry Pi,或者插入了无线加密狗,则左键单击此图标将显示可用无线网络的列表,如下所示。如果未找到网络,它将显示消息“未找到 AP - 正在扫描…'.等待几秒钟而不关闭菜单,它应该会找到您的网络。 请注意,在支持 5GHz 频段(Pi3B+、Pi4、CM4、Pi400)的 Raspberry Pi 设备上,由于监管原因,无线网络将被禁用,直到设置国家/地区代码。要设置国家/地区代码,请从首选项菜单中打开应用程序Raspberry Pi Configuration,选择 Localisation 并设置相应的代码。
右侧的图标显示网络是否安全,并指示其信号强度。单击要连接到的网络。如果它是安全的,一个对话框将提示您输入网络密钥:
输入密钥并单击 OK,然后等待几秒钟。网络图标将短暂闪烁,表示正在建立连接。准备就绪后,图标将停止闪烁并显示信号强度。
使用命令行
如果您无法访问通常用于在Raspberry Pi上设置无线 LAN 的图形用户界面,则此方法适用。如果您无法访问屏幕或有线以太网网络,它特别适合与串行控制台电缆一起使用。另请注意,不需要其他软件;您需要的一切都已经包含在Raspberry Pi中。
使用 raspi-config
启用无线网络的最快方法是使用命令行工具 raspi-config
。
sudo raspi-config
从菜单中选择 Localisation Options,然后选择 Change wireless country 选项。在全新安装中,出于监管目的,您需要指定使用设备的国家/地区。然后设置网络的 SSID 和网络的密码。如果您不知道要连接的网络的 SSID,请参阅下一节,了解如何在raspi-config运行之前列出可用网络。
请注意, raspi-config
它不提供用于设置无线网络的完整选项集;如果raspi-config无法将Raspberry Pi连接到您请求的网络,您可能需要参考下面的额外部分以获取更多详细信息。
获取无线局域网网络详细信息
要扫描无线网络,请使用命令 sudo iwlist wlan0 scan
。这将列出所有可用的无线网络以及其他有用信息。注意:
-
'ESSID:"testing"' 是无线网络的名称
-
'IE: IEEE 802.11i/WPA2 Version 1' 是使用的身份验证。在这种情况下,它是WPA2,这是取代WPA的更新,更安全的无线标准。本指南应适用于 WPA 或 WPA2,但可能不适用于 WPA2 企业版。您还需要无线网络的密码。对于大多数家用路由器,这可以在路由器背面的贴纸上找到。以下示例的 ESSID (ssid) 为
testing
,密码 (psk) 为testingPassword
将网络详细信息添加到Raspberry Pi
在 nano 中打开配置文件 wpa-supplicant
:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
转到文件底部并添加以下内容:
network={ ssid="testing" psk="testingPassword" }
密码可以配置为 ASCII 表示形式、根据上述示例用引号表示形式或预加密的 32 字节十六进制数。您可以使用该 wpa_passphrase
实用程序生成加密的 PSK。这将获取 SSID 和密码,并生成加密的 PSK。通过上面的示例,您可以使用 wpa_passphrase "testing"
.然后,系统将要求您输入无线网络的密码(在这种情况下testingPassword)。输出如下:
network={ ssid="testing" #psk="testingPassword" psk=131e1e221f6e06e3911a2d11ff2fac9182665c004de85300f9cac208a6a80531 }
请注意,代码的纯文本版本存在,但已注释掉。您应该从 wpa_supplicant
最终文件中删除此行以提高安全性。
该 wpa_passphrase
工具需要 8 到 63 个字符的密码。要使用更复杂的密码,可以提取文本文件的内容并将其用作 wpa_passphrase
的输入。将密码存储在文本文件中,并通过调用 wpa_passphrase "testing"<file_where_password_is_stored
将其输入到 wpa_passphrase
。为了提高安全性,您应该删除 file_where_password_is_stored
之后的,因此系统上没有原始密码的纯文本副本。
要使用 wpa_passphrase --encrypted
的 PSK,您可以将加密的 PSK 复制并粘贴到文件 wpa_supplicant.conf
中,或者通过以下两种方式之一将工具的输出重定向到配置文件:
-
更改为
root
通过执行sudo su
,然后在询问时调用wpa_passphrase "testing" >> /etc/wpa_supplicant/wpa_supplicant.conf
并输入测试密码 -
或者使用
wpa_passphrase "testing" | sudo tee -a /etc/wpa_supplicant/wpa_supplicant.conf > /dev/null
并输入测试密码; 用tee重定向到/dev/null防止也输出到屏幕(标准输出)。
如果要使用这两个选项之一,请确保使用 >>
,或者使用 tee -a
— 两者都会将文本附加到现有文件。使用单个 >
,或者在使用 tee
时省略 -a
,将擦除所有内容,然后将输出附加到指定的文件。
现在通过按 Ctrl+X
保存文件 ,然后按 Y
,最后按 Enter
。
使用 `wpa_cli -i wlan0 reconfigure`重新配置接口.
您可以使用ifconfig wlan0 验证它是否已成功连接。如果字段。inet addr旁边有地址,则Raspberry Pi已连接到网络。如果没有,请检查您的密码和 ESSID 是否正确
您可以使用 ifconfig wlan0
验证它是否已成功连接。如果字段。 inet addr
旁边有地址,则Raspberry Pi已连接到网络。如果没有,请检查您的密码和 ESSID 是否正确
在Raspberry Pi3B+和Raspberry Pi4B上,您还需要设置国家/地区代码,以便5GHz网络可以选择正确的频段。您可以使用该 raspi-config
应用程序执行此操作:选择“本地化选项”菜单,然后选择 'Change Wi-Fi Country' 。或者,您可以编辑 wpa_supplicant.conf
文件并添加以下内容。(注意:您需要将“GB”替换为您所在国家/地区的 2 个字母的 ISO 代码。请参阅 维基百科 以获取 2 个字母的 ISO 3166-1 国家/地区代码列表。
country=GB
请注意,对于最新的Buster Raspberry Pi OS版本,您必须确保该 wpa_supplicant.conf
文件在顶部包含以下信息:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev update_config=1 country=<Insert 2 letter ISO 3166-1 country code here>
使用不安全的网络
如果要连接到的网络不使用密码,则 wpa_supplican
网络的条目需要包含正确的 tkey_mgmt
条目。 例如
network={ ssid="testing" key_mgmt=NONE }
Warning
|
使用不安全的无线网络时应小心。 |
隐藏的网络
如果您使用的是隐藏网络,则 wpa_supplicant file
, scan_ssid
中的额外选项可能有助于连接。
network={ ssid="yourHiddenSSID" scan_ssid=1 psk="Your_wireless_network_password" }
您可以使用 ifconfig wlan0
验证它是否已成功连接。如果字段 inet addr
旁边有地址,则Raspberry Pi已连接到网络。如果没有,请检查您的密码和ESSID是否正确。
添加多个无线网络配置
在最新版本的Raspberry Pi操作系统上,可以为无线网络设置多个配置。例如,您可以为家庭设置一个,为学校设置一个。
例如
network={ ssid="SchoolNetworkSSID" psk="passwordSchool" id_str="school" } network={ ssid="HomeNetworkSSID" psk="passwordHome" id_str="home" }
如果范围内有两个网络,则可以添加优先级选项以在它们之间进行选择。范围内具有最高优先级的网络将是连接的网络。
network={ ssid="HomeOneSSID" psk="passwordOne" priority=1 id_str="homeOne" } network={ ssid="HomeTwoSSID" psk="passwordTwo" priority=2 id_str="homeTwo" }
DHCP 守护程序
Raspberry Pi 用 dhcpcd
在其所有网络接口上配置 TCP/IP。该dhcpcd守护程序旨在成为类 UNIX 系统的一体化 ZeroConf 客户端。这包括为每个接口分配一个 IP 地址、设置网络掩码以及通过名称服务交换机 (NSS) 设施配置 DNS 解析。
默认情况下,Raspberry Pi OS 尝试通过 DHCP 自动配置所有网络接口,如果 DHCP 失败,则回退到 169.254.0.0/16 范围内的自动专用地址。这与其他Linux变体和Microsoft Windows的行为一致。
静态 IP 地址
Warning
|
如果 IP 地址的分配通常由网络上的 DHCP 服务器处理,则为 Raspberry Pi 分配静态 IP 地址可能会导致地址冲突,从而导致网络问题。 |
如果要为Raspberry Pi分配静态IP地址,最好的方法是在路由器上为其保留一个地址。这样,您的Raspberry Pi将继续通过DHCP分配其地址,但每次都会收到相同的地址。DHCP服务器可以分配一个 固定
地址,将其与Raspberry Pi的MAC地址相关联。IP 地址的管理将保留在 DHCP 服务器上,这将避免地址冲突和潜在的网络问题。
但是,如果您希望禁用接口的自动配置,而是对其进行静态配置,则可以在 /etc/dhcpcd.conf
中执行此操作。例如:
interface eth0 static ip_address=192.168.0.4/24 static routers=192.168.0.254 static domain_name_servers=192.168.0.254 8.8.8.8
设置无显示的Raspberry Pi
Edit this on GitHub
如果您不使用显示器或键盘来运行 Raspberry Pi(称为headless),但您仍然需要进行一些无线设置,则可以在 创建映像 时启用无线网络和 SSH。 在 SD 卡上创建映像后,通过将其插入 Linux 或 Windows 计算机上的读卡器,可以访问 boot 文件夹。将某些文件添加到此文件夹将在Raspberry Pi首次启动时激活某些设置功能。
Important
|
如果您正在安装 Raspberry Pi OS,并打算headless运行它,则需要创建一个新的用户帐户。由于您将无法使用 首次启动向导 创建用户帐户,因为它需要显示器和键盘,因此您 必须 将 userconf.txt 文件添加到启动文件夹以在首次启动时创建用户,或使用 Raspberry Pi 成像器中的 高级菜单 使用用户帐户配置操作系统。
|
配置网络
您需要为特定无线网络定义一个 wpa_supplicant.conf
文件。将此文件放到 SD 卡的启动文件夹中。当Raspberry Pi首次启动时,它会将该文件复制到 Linux 根文件系统中的正确位置,并使用这些设置启动无线网络。Raspberry Pi的 IP 地址在开机后不会立即可见,因此此步骤对于无头连接它至关重要。根据您创建此文件的操作系统和编辑器,该文件可能具有不正确的换行符或错误的文件扩展名,因此请确保使用说明此问题的编辑器。Linux 需要换行符 (LF) 换行符。
Warning
|
Raspberry Pi连接到电源后,请确保等待几分钟(最多 5 分钟)让它启动并在网络上注册。 |
A wpa_supplicant.conf
文件示例:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev country=<Insert 2 letter ISO 3166-1 country code here> update_config=1 network={ ssid="<Name of your wireless LAN>" psk="<Password for your wireless LAN>" }
国家/地区代码应设置为您使用的国家/地区的两个字母的 ISO/IEC alpha2 代码,例如:
-
GB (英国)
-
FR (法国)
-
DE (德国)
-
US (美国)
-
SE (瑞典)
下面是一个更详细的示例,应该适用于大多数典型的 wpa2 个人网络。下面的模板适用于 2.4GHz/5GHz 隐藏或非网络。在 ssid - psk 周围使用引号可以帮助避免任何奇怪的情况,如果您的网络 ssid 或密码有特殊的字符(! @ # $ 等)
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev update_config=1 country=<Insert 2 letter ISO 3166-1 country code here> network={ scan_ssid=1 ssid="<Name of your wireless LAN>" psk="<Password for your wireless LAN>" proto=RSN key_mgmt=WPA-PSK pairwise=CCMP auth_alg=OPEN }
Note
|
一些较旧的Raspberry Pi板和一些USB无线加密狗不支持5GHz网络。 |
Note
|
在没有键盘或显示器的情况下,您将需要某种 远程访问 无头Raspberry Pi的方法。对于无头设置,可以通过将一个名为 ssh 的文件(没有任何扩展名)放在 SD 卡的启动文件夹中来启用 SSH。有关详细信息,请参阅有关 设置 SSH 服务器的部分。
|
设置路由无线接入点
Edit this on GitHub
以太网网络中的Raspberry Pi可以用作无线接入点,创建辅助网络。由此产生的新无线网络完全由Raspberry Pi管理。 如果您希望将现有以太网网络扩展到无线客户端,请考虑改为 桥接接入点.。
+- RPi -------+ +---+ 10.10.0.2 | +- Laptop ----+ | | WLAN AP +-))) (((-+ WLAN Client | | | 192.168.4.1 | | 192.168.4.2 | | +-------------+ +-------------+ +- Router ----+ | | Firewall | | +- PC#2 ------+ (Internet)---WAN-+ DHCP server +-LAN-+---+ 10.10.0.3 | | 10.10.0.1 | | +-------------+ +-------------+ | | +- PC#1 ------+ +---+ 10.10.0.4 | +-------------+
可以使用Raspberry Pi 4,Raspberry Pi 3或Raspberry Pi Zero W的内置无线功能,或使用支持接入点模式的合适USB无线加密狗来创建路由无线接入点。 某些 USB 加密狗可能需要对其设置稍作更改。如果您在使用 USB 无线加密狗时遇到问题,请查看 论坛。
本文档在运行全新安装的Raspberry Pi OS Buster的Raspberry Pi 3B上进行了测试。
Before you Begin
-
确保您对Raspberry Pi具有管理访问权限。网络设置将作为安装的一部分进行修改:建议使用本地访问,将屏幕和键盘连接到Raspberry Pi。
-
将Raspberry Pi连接到以太网并启动Raspberry Pi操作系统。
-
确保Raspberry Pi上的Raspberry Pi操作系统是 最新 的,如果在此过程中安装了软件包,请重新启动。
-
记下Raspberry Pi所连接的以太网网络的IP配置:
-
在本文档中,我们假设IP网络
10.10.0.0/24
是在以太网LAN上配置的,并且Raspberry Pi将管理无线客户端的IP网络192.168.4.0/24
。 -
请选择另一个用于无线的 IP 网络,例如
192.168.10.0/24
,如果您的以太网 LAN 已经在使用 IP 网络192.168.4.0/24
。
-
-
准备好无线客户端(笔记本电脑、智能手机等)来测试您的新接入点。
安装 AP 和管理软件
为了用作接入点,Raspberry Pi需要安装接入点软件包hostapd:
sudo apt install hostapd
启用无线接入点服务并将其设置为在Raspberry Pi启动时启动:
sudo systemctl unmask hostapd sudo systemctl enable hostapd
为了向无线客户端提供网络管理服务(DNS,DHCP),Raspberry Pi需要安装软件包 dnsmasq
:
sudo apt install dnsmasq
最后,安装 netfilter-persistent
及其插件 iptables-persistent
。此实用程序通过保存防火墙规则并在Raspberry Pi启动时恢复它们来帮助:
sudo DEBIAN_FRONTEND=noninteractive apt install -y netfilter-persistent iptables-persistent
软件安装完成。稍后我们将配置软件包。
设置网络路由器
Raspberry Pi将运行和管理独立的无线网络。它还将在无线和以太网之间路由,为无线客户端提供互联网访问。如果您愿意,可以通过跳过下面的“启用路由和 IP 伪装”部分来选择跳过路由,并在完全隔离的情况下运行无线网络。
定义无线接口 IP 配置
Raspberry Pi为无线网络运行DHCP服务器;这需要Raspberry Pi中无线接口 (wlan0
) 的静态 IP 配置。 Raspberry Pi还充当无线网络上的路由器,按照惯例,我们将为其提供网络中的第一个 IP 地址: 192.168.4.1
.
要配置静态 IP 地址,请使用以下命令编辑dhcpcd配置文件:
sudo nano /etc/dhcpcd.conf
转到文件末尾并添加以下内容:
interface wlan0 static ip_address=192.168.4.1/24 nohook wpa_supplicant
启用路由和 IP 伪装
本节将 Raspberry Pi 配置为允许无线客户端访问主(以太网)网络上的计算机,并从那里访问互联网。
Note
|
如果您希望阻止无线客户端访问以太网网络和互联网,请跳过此部分。 |
要启用路由,即允许流量在Raspberry Pi中从一个网络流向另一个网络,请使用以下命令创建一个文件,内容如下:
sudo nano /etc/sysctl.d/routed-ap.conf
文件内容:
# Enable IPv4 routing net.ipv4.ip_forward=1
启用路由将允许来自网络 192.168.4.0/24
的主机到达 LAN 和主路由器,连接互联网。为了允许此外部无线网络上的客户端与互联网之间的流量而不更改主路由器的配置,Raspberry Pi可以使用“伪装”防火墙规则将无线客户端的IP地址替换为LAN上自己的IP地址。
-
主路由器将看到来自无线客户端的所有传出流量来自Raspberry Pi,从而允许与互联网通信。
-
Raspberry Pi将接收所有传入流量,替换 IP 地址,并将流量转发到原始无线客户端。
Raspberry Pi将接收所有传入流量,替换 IP 地址,并将流量转发到原始无线客户端。
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
现在保存 IPv4(包括上述规则)和 IPv6 的当前防火墙规则,以便在 netfilter-persistent
服务启动时加载:
sudo netfilter-persistent save
过滤规则将保存到目录 /etc/iptables/
中。如果将来更改防火墙的配置,请确保在重新启动之前保存配置。
为无线网络配置 DHCP 和 DNS 服务
DHCP 和 DNS 服务由 dnsmasq
提供。默认配置文件用作所有可能的配置选项的模板,而我们只需要几个。从空文件开始更容易。
重命名默认配置文件并编辑一个新配置文件:
sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig sudo nano /etc/dnsmasq.conf
将以下内容添加到文件并保存:
interface=wlan0 # Listening interface dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h # Pool of IP addresses served via DHCP domain=wlan # Local wireless DNS domain address=/gw.wlan/192.168.4.1 # Alias for this router
Raspberry Pi将在 192.168.4.2
和 192.168.4.20
之间提供 IP 地址,租用时间为 24 小时,到无线 DHCP 客户端。您应该能够从无线客户端以该gw.wlan名称访问Raspberry Pi。
Note
|
为专用网络预留了三个 IP 地址块。有一个 A 类块从 10.0.0.0 到 10.255.255.255 ,一个 B 类块从 172.16.0.0 到 172.31.255.255 ,可能最常用的是 C 类块从 192.168.0.0 到 192.168.255.255 。
|
还有 dnsmasq
更多选项 ;有关详细信息,请参阅默认配置文件 (/etc/dnsmasq.conf
) 或http://www.thekelleys.org.uk/dnsmasq/doc.html[联机文档]。
确保无线操作
世界各国对电信无线电频段的使用进行监管,以确保无干扰运行。
Linux 操作系统通过允许应用程序配置两个字母的“WiFi 国家/地区代码”来帮助用户遵守这些 规则,例如 US
用于在美国使用的计算机。
在Raspberry Pi OS中,在用户配置WiFi国家/地区代码之前,5 GHz无线网络将被禁用,通常作为初始安装过程的一部分(有关详细信息,请参阅本节中的无线配置页面。 要确保 WiFi 无线电不会在Raspberry Pi上被阻止,请执行以下命令:
sudo rfkill unblock wlan
此设置将在启动时自动恢复。接下来,我们将在接入点软件配置中定义适当的国家/地区代码。
配置 AP 软件
创建位于 /etc/hostapd/hostapd.conf
的配置文件 hostapd
,为新无线网络添加各种参数。
sudo nano /etc/hostapd/hostapd.conf
将以下信息添加到配置文件中。此配置假设我们使用通道 7,网络名称为 NameOfNetwork
,密码 AardvarkBadgerHedgehog
。请注意,名称和密码 不 应有引号。密码的长度应介于 8 到 64 个字符之间。
country_code=GB interface=wlan0 ssid=NameOfNetwork hw_mode=g channel=7 macaddr_acl=0 auth_algs=1 ignore_broadcast_ssid=0 wpa=2 wpa_passphrase=AardvarkBadgerHedgehog wpa_key_mgmt=WPA-PSK wpa_pairwise=TKIP rsn_pairwise=CCMP
请注意这一行 country_code=GB
:它将计算机配置为在英国使用正确的无线频率。调整此行并指定您所在国家/地区的两个字母的 ISO 代码。请参阅 维基百科 以获取两个字母的ISO 3166-1国家/地区代码列表。
要使用 5 GHz 频段,可以将操作模式从 hw_mode=g
更改为 hw_mode=a
。hw_mode
的可能值为:
-
a = IEEE 802.11a (5 GHz) (Raspberry Pi 3B+ onwards)
-
b = IEEE 802.11b (2.4 GHz)
-
g = IEEE 802.11g (2.4 GHz)
请注意,在更改 hw_mode
时,您可能还需要更改channel - 有关允许的组合列表,请参阅https://en.wikipedia.org/wiki/List_of_WLAN_channels[维基百科]。
运行新的无线 AP
现在重新启动Raspberry Pi并验证无线接入点是否自动可用。
sudo systemctl reboot
Raspberry Pi重新启动后,使用无线客户端搜索无线网络。您在 /etc/hostapd/hostapd.conf
文件中指定的网络 SSID 现在应该存在,并且应该可以使用指定的密码访问它。
如果在Raspberry Pi上启用了SSH,则假设该 pi
帐户存在,则应该可以从无线客户端连接到它,如下所示: ssh pi@192.168.4.1
或 ssh pi@gw.wlan
如果您的无线客户端可以访问您的Raspberry Pi(以及互联网,如果您设置了路由),那么恭喜您设置了新的接入点!
如果您遇到困难,请联系 论坛 寻求帮助。请在您的消息中参考此页面。
设置桥接无线接入点
Edit this on GitHub
Raspberry Pi 可用作现有以太网网络中的桥接无线接入点。这会将网络扩展到无线计算机和设备。 如果要创建独立的无线网络,请考虑改为设置路由接入点。
+- RPi -------+ +---+ 10.10.0.2 | +- Laptop ----+ | | WLAN AP +-))) (((-+ WLAN Client | | | Bridge | | 10.10.0.5 | | +-------------+ +-------------+ +- Router ----+ | | Firewall | | +- PC#2 ------+ (Internet)---WAN-+ DHCP server +-LAN-+---+ 10.10.0.3 | | 10.10.0.1 | | +-------------+ +-------------+ | | +- PC#1 ------+ +---+ 10.10.0.4 | +-------------+
桥接无线接入点可以使用Raspberry Pi 4,Raspberry Pi 3或Raspberry Pi Zero W的内置无线功能,或使用支持接入点模式的合适USB无线加密狗来创建。 某些 USB 加密狗可能需要对其设置稍作更改。如果您在使用 USB 无线加密狗时遇到问题,请查看https://forums.raspberrypi.com/[论坛]。
开始之前
-
确保您对Raspberry Pi具有管理访问权限。作为安装的一部分,网络设置将完全重置:建议使用本地访问,将屏幕和键盘连接到Raspberry Pi。
Note如果通过 SSH 远程安装,请按 名称 而不是 IP 地址连接到您的Raspberry Pi,例如
ssh pi@raspberrypi.local
,因为您的Raspberry Pi在网络上的地址可能会在安装后发生变化。如果需要,您还应该准备好添加屏幕和键盘,以防您在安装后与Raspberry Pi失去联系。 -
将Raspberry Pi连接到以太网并启动Raspberry Pi操作系统。
-
确保Raspberry Pi上的Raspberry Pi操作系统是 最新的,如果在此过程中安装了软件包,请重新启动。
-
准备好无线客户端(笔记本电脑、智能手机等)来测试您的新接入点。
安装 AP 和管理软件
为了用作桥接接入点,Raspberry Pi 需要安装接入点软件包 hostapd
:
sudo apt install hostapd
启用无线接入点服务并将其设置为在Raspberry Pi启动时启动:
sudo systemctl unmask hostapd sudo systemctl enable hostapd
软件安装完成。稍后我们将配置接入点软件。
设置网桥
在Raspberry Pi上运行的桥接网络设备将使用其内置接口连接以太网和无线网络。
创建网桥设备并填充网桥
通过使用以下命令创建文件来添加网桥网络设备br0,内容如下:
sudo nano /etc/systemd/network/bridge-br0.netdev
文件内容:
[NetDev] Name=br0 Kind=bridge
为了将以太网网络与无线网络桥接,首先通过创建以下文件将内置以太网接口 (eth0
) 添加为网桥成员:
sudo nano /etc/systemd/network/br0-member-eth0.network
文件内容:
[Match] Name=eth0 [Network] Bridge=br0
Note
|
接入点软件将在服务启动时将无线接口wlan0添加到网桥。无需为该接口创建文件。这种情况特定于无线 LAN 接口。 |
接入点软件将在服务启动时将无线接口wlan0添加到网桥。无需为该接口创建文件。这种情况特定于无线 LAN 接口。
sudo systemctl enable systemd-networkd
定义网桥设备 IP 配置
作为网桥设备成员的网络接口永远不会分配 IP 地址,因为它们通过网桥进行通信。桥接设备本身需要一个 IP 地址,以便您可以在网络上访问您的Raspberry Pi。
dhcpcd
,Raspberry Pi上的 DHCP 客户端会自动为每个活动接口请求一个 IP 地址。因此,我们需要阻止处理 eth0
和 wlan0
,并 dhcpcd
仅通过 DHCP 进行配置 br0
。
sudo nano /etc/dhcpcd.conf
在文件开头附近添加以下行(第一行上方interface xxx,如果有):
denyinterfaces wlan0 eth0
Go to the end of the file and add the following:
interface br0
使用此行,接口 br0
将通过 DHCP 根据默认值进行配置。保存文件以完成计算机的 IP 配置。
确保无线操作
世界各国对电信无线电频段的使用进行监管,以确保无干扰运行。
Linux 操作系统通过允许应用程序配置两个字母的“WiFi 国家/地区代码”来帮助用户遵守这些 规则,例如 US
用于在美国使用的计算机。
在Raspberry Pi OS中,在用户配置WiFi国家/地区代码之前,5 GHz无线网络将被禁用,通常作为初始安装过程的一部分(有关详细信息,请参阅本节中的无线配置页面。 要确保 WiFi 无线电不会在Raspberry Pi上被阻止,请执行以下命令:
sudo rfkill unblock wlan
此设置将在启动时自动恢复。接下来,我们将在接入点软件配置中定义适当的国家/地区代码。
软件配置AP
创建位于 /etc/hostapd/hostapd.conf
的配置文件 hostapd
,为新无线网络添加各种参数。
sudo nano /etc/hostapd/hostapd.conf
将以下信息添加到配置文件中。此配置假设我们使用通道 7,网络名称为 NameOfNetwork
,密码 AardvarkBadgerHedgehog
。请注意,名称和密码 不 应有引号。密码的长度应介于 8 到 64 个字符之间。
country_code=GB interface=wlan0 bridge=br0 ssid=NameOfNetwork hw_mode=g channel=7 macaddr_acl=0 auth_algs=1 ignore_broadcast_ssid=0 wpa=2 wpa_passphrase=AardvarkBadgerHedgehog wpa_key_mgmt=WPA-PSK wpa_pairwise=TKIP rsn_pairwise=CCMP
Note the lines interface=wlan0
and bridge=br0
: these direct hostapd
请注意这一行 country_code=GB
:它将计算机配置为在英国使用正确的无线频率。调整此行并指定您所在国家/地区的两个字母的 ISO 代码。请参阅 维基百科 以获取两个字母的ISO 3166-1国家/地区代码列表。
要使用 5 GHz 频段,可以将操作模式从 hw_mode=g
更改为 hw_mode=a
。hw_mode
的可能值为:
-
a = IEEE 802.11a (5 GHz) (Raspberry Pi 3B+ onwards)
-
b = IEEE 802.11b (2.4 GHz)
-
g = IEEE 802.11g (2.4 GHz)
请注意,在更改 hw_mode
时,您可能还需要更改channel - 有关允许的组合列表,请参阅https://en.wikipedia.org/wiki/List_of_WLAN_channels[维基百科]。
运行新的无线 AP
现在重新启动Raspberry Pi并验证无线接入点是否自动可用。
sudo systemctl reboot
Raspberry Pi重新启动后,使用无线客户端搜索无线网络。您在 /etc/hostapd/hostapd.conf
文件中指定的网络 SSID 现在应该存在,并且应该可以使用指定的密码访问它。
如果您的无线客户端可以访问本地网络和互联网,则恭喜您设置了新的接入点!
如果您遇到困难,请联系 论坛寻求帮助。请在您的消息中参考此页面。
使用代理服务器
Edit this on GitHub
如果您希望Raspberry Pi通过代理服务器(可能从学校或其他工作场所)访问互联网,则需要将Raspberry Pi配置为使用服务器,然后才能上网。
您将需要:
-
代理服务器的 IP 地址或主机名和端口
-
代理的用户名和密码(如果需要)
配置Raspberry Pi
您需要设置三个环境变量 (http_proxy
, https_proxy
, 和 no_proxy
) 以便您的Raspberry Pi知道如何访问代理服务器。
打开终端窗口,然后使用 nano 打开文件 /etc/environment
:
sudo nano /etc/environment
将以下内容添加到 /etc/environment
文件中以创建变量 http_proxy
:
export http_proxy="http://proxyipaddress:proxyport"
将 proxyipaddress
和 proxyport
替换为代理的 IP 地址和端口。
Note
|
如果您的代理需要用户名和密码,请使用以下格式添加它们: |
export http_proxy="http://username:password@proxyipaddress:proxyport"
输入与环境变量 https_proxy
相同的信息::
export https_proxy="http://username:password@proxyipaddress:proxyport"
创建 no_proxy
环境变量,这是一个逗号分隔的地址列表,您的Raspberry Pi不应将代理用于:
export no_proxy="localhost, 127.0.0.1"
您的 /etc/environment
文件现在应如下所示:
export http_proxy="http://username:password@proxyipaddress:proxyport" export https_proxy="http://username:password@proxyipaddress:proxyport" export no_proxy="localhost, 127.0.0.1"
按下 Ctrl + X 可保存并退出。
HDMI配置
Edit this on GitHub
在绝大多数情况下,只需使用标准HDMI电缆将配备HDMI的显示器插入Raspberry Pi,即可自动使Raspberry Pi使用显示器支持的最佳分辨率。Raspberry Pi Zero,Zero W和Zero 2 W使用迷你HDMI端口,因此您需要迷你HDMI到全尺寸HDMI引线或适配器。在Raspberry Pi 4和Raspberry Pi 400上有两个微型HDMI端口,因此您需要为要连接的每台显示器配备微型HDMI到全尺寸HDMI引线或适配器。在打开Raspberry Pi之前,您应该连接任何 HDMI 引线。
Raspberry Pi 4最多可以驱动两个显示器,分辨率高达1080p,刷新率为60Hz。在 4K 分辨率下,如果您连接两台显示器,那么您的刷新率限制为 30Hz。您还可以以 4K 60Hz 刷新率驱动单个显示器:这要求显示器连接到 USB-C 电源输入(标记为 HDMI0)旁边的 HDMI 端口。您还必须通过在 config.txt 中设置 hdmi_enable_4kp60=1
标志来启用 4Kp60 输出。此标志也可以在桌面环境中使用"Raspberry Pi Configuration"”"工具进行设置。
如果您运行的是 3D 图形驱动程序(也称为 FKMS 驱动程序),则在"Preferences"菜单中,您将找到用于设置标准显示器(包括多显示器设置)的图形应用程序。
Note
|
屏幕配置工具 ( |
如果您使用的是旧版图形驱动程序,或者发现自己处于 Raspberry Pi 可能无法确定最佳模式的情况下,或者您可能特别希望设置非默认分辨率,则本页的其余部分可能会有用。
Note
|
所有命令都完整地记录在文档的 config.txt 部分中。 |
HDMI 组和模式
HDMI有两个常见的组:CEA(消费电子协会,电视通常使用的标准)和DMT(显示器计时,显示器通常使用的标准)。每个组通告一组特定的模式,其中模式描述输出的分辨率、帧速率、时钟速率和纵横比。
我的设备支持哪些模式?
您可以在命令行上使用 tvservice
应用程序来确定您的设备支持哪些模式以及其他有用数据:
-
tvservice -s
显示当前HDMI状态,包括模式和分辨率 -
tvservice -m
CEA列出所有支持的 CEA 模式 -
tvservice -m
DMT列出所有支持的 DMT 模式
如果您使用的是连接了多个显示器的Raspberry Pi 4,则 tvservice
需要被告知要询问哪个设备的信息。您可以使用以下命令获取所有连接设备的显示 ID:
tvservice -l
您可以通过添加 -v <display id>
到 tvservice
命令来指定使用哪个 tvservice
显示器,例如:
-
tvservice -v 7 -m CEA
, 列出显示 ID 7 支持的所有 CEA 模式
设置特定的HDMI模式
设置特定模式是使用 hdmi_group
和 hdmi_mode
config.txt 条目完成的。组条目在 CEA 或 DMT 之间进行选择,模式选择分辨率和帧速率。您可以在config.txt 视频配置页面上找到模式表,但您应该使用上述 tvservice
命令来准确了解您的设备支持哪些模式。
在Raspberry Pi 4 和Raspberry Pi 400 上指定 HDMI 端口,在 config.txt 中的 hdmi_group
或者 hdmi_mode
条目中添加索引标识符,例如 hdmi_mode:0
或 hdmi_group:1
。
设置自定义 HDMI 模式
有两个选项可用于设置自定义模式: hdmi_cvt
和 hdmi_timings
.
hdmi_cvt
设置自定义协调视频计时条目,此处对此进行了全面描述: 视频配置
在某些极少数情况下,可能需要定义HDMI信号的确切时钟要求。这是一种完全自定义的模式,它通过设置 hdmi_group=2
和 hdmi_mode=87
.然后,您可以使用 hdmi_timings
config.txt
命令来设置显示器的特定参数。 hdmi_timings指定HDMI信号需要使用的所有时序。这些时序通常可在所用显示器的数据表中找到。
hdmi_timings=<h_active_pixels> <h_sync_polarity> <h_front_porch> <h_sync_pulse> <h_back_porch> <v_active_pixels> <h_sync_polarity> <h_front_porch> <h_sync_pulse> <h_back_porch> <v_active_lines> <v_sync_polarity> v_front_porch> <v_sync_pulse> <v_back_porch> <v_sync_offset_a> <v_sync_offset_b> <pixel_rep> <frame_rate> <interlaced> <pixel_freq> <aspect_ratio>
Timing | Purpose |
---|---|
|
The horizontal resolution |
|
0 or 1 to define the horizontal sync polarity |
|
Number of horizontal front porch pixels |
|
Width of horizontal sync pulse |
|
Number of horizontal back porch pixels |
|
The vertical resolution |
|
0 or 1 to define the vertical sync polarity |
|
Number of vertical front porch pixels |
|
Width of vertical sync pulse |
|
Number of vertical back porch pixels |
|
Leave at 0 |
|
Leave at 0 |
|
Leave at 0 |
|
Frame rate of mode |
|
0 for non-interlaced, 1 for interlaced |
|
The mode pixel frequency |
|
The aspect ratio required |
aspect_ratio
should be one of the following:
Ratio |
aspect_ratio ID |
---|---|
|
1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
要让Raspberry Pi 4 和Raspberry Pi 400 指定 HDMI 端口,您可以在config.txt中添加索引标识符。例如 hdmi_cvt:0=...
. 或 hdmi_timings:1=...
。如果未指定端口标识符,则设置将应用于端口 0。
对 HDMI 进行故障排除
在极少数情况下,您可能需要增加HDMI驱动器强度,例如,当显示器上有斑点或使用很长的电缆时。有一个 config.txt 项可以执行此操作 config_hdmi_boost
,该项记录在 config.txt 视频页面上。
注意 Raspberry Pi 4B 尚不支持 config_hdmi_boost
,对此选项的支持将在未来的软件更新中添加。
旋转显示器
Edit this on GitHub
旋转Raspberry Pi显示器的选项取决于它正在运行的显示驱动程序软件,这可能还取决于您使用的Raspberry Pi。
Fake 或 Full KMS 图形驱动程序
Note
|
这是Raspberry Pi 4 Model B的默认设置。 |
如果您正在运行Raspberry Pi桌面,则使用 Screen Configuration Utility
桌面 Preferences
菜单实现旋转。这将调出连接到Raspberry Pi的一个或多个显示器的图形表示。右键单击要旋转的显示屏,然后选择所需的选项。
也可以使用命令行 xrandr
选项更改这些设置。以下命令分别提供 0°、-90°、+90° 和 180° 旋转。
xrandr --output HDMI-1 --rotate normal
xrandr --output HDMI-1 --rotate left
xrandr --output HDMI-1 --rotate right
xrandr --output HDMI-1 --rotate inverted
请注意,该 --output
条目指定轮换应用于哪个设备。您只需在命令行上键入 xrandr
即可确定设备名称,该命令行将显示所有连接设备的信息,包括名称。
您还可以使用该—reflect选项使用命令行镜像显示。反射可以是’normal' 'x', 'y' 或 'xy’之一。这会导致输出内容反映在指定的轴上。例如:
xrandr --output HDMI-1 --reflect x
如果仅使用控制台(没有图形桌面),则需要设置适当的内核命令行标志。按照此页面上的说明更改控制台设置。
传统的图形驱动程序
Note
|
这是Raspberry Pi 4 型号 B 之前的型号的默认设置。 |
使用旧版显示驱动程序时,config.txt
有一些轮换选项。
display_hdmi_rotate
用于旋转HDMI显示器,display_hdmi_rotate
用于旋转任何连接的LCD面板(使用DSI或DPI接口)。这些选项可旋转桌面和控制台。每个选项都采用以下参数之一:
display_*_rotate | result |
---|---|
0 |
no rotation |
1 |
rotate 90 degrees clockwise |
2 |
rotate 180 degrees clockwise |
3 |
rotate 270 degrees clockwise |
0x10000 |
horizontal flip |
0x20000 |
vertical flip |
请注意,90 度和 270 度旋转选项在 GPU 上需要额外的内存,因此这些选项不适用于 16MB GPU 拆分。
您可以通过将它们添加在一起来将旋转设置与翻转组合在一起。您还可以以相同的方式进行水平和垂直翻转。例如,垂直和水平翻转的 180 度旋转将0x20000 + 0x10000 + 2 = 0x30002。
音频配置
Edit this on GitHub
Raspberry Pi最多有三种音频输出模式:HDMI 1和2(如果有)以及耳机插孔。您可以随时在这些模式之间切换。 如果您的 HDMI 显示器或电视具有内建扬声器,则可以通过 HDMI 电缆播放音频,但您可以将其切换到插入耳机插孔的一组耳机或其他扬声器。如果您的显示器声称有扬声器,则默认情况下通过HDMI输出声音;如果没有,则通过耳机插孔输出。这可能不是所需的输出设置,或者自动检测不准确,在这种情况下,您可以手动切换输出。
更改音频输出
有两种方法可以设置音频输出;使用桌面音量控制,或使用 raspi-config
命令行工具。
使用桌面
Right-clicking the volume icon on the desktop taskbar brings up the audio output selector; this allows you to select between the internal audio outputs. It also allows you to select any external audio devices, such as USB sound cards and Bluetooth audio devices. A green tick is shown against the currently selected audio output device — simply left-click the desired output in the pop-up menu to change this. The volume control and mute operate on the currently selected device.
使用 raspi-config
通过在命令行中输入以下内容来打开 raspi-config:
sudo raspi-config
这将打开配置屏幕:
选择 System Options
(当前选项 1,但您的选项可能不同)并按 Enter
。
现在选择名为的选项 Audio
(当前选项S2,但您的选项可能不同),然后按 Enter
:
选择所需的模式,然后按 Enter
向右箭头键退出选项列表,然后选择 Finish
退出配置工具。
修改完音频设置后,您需要重新启动Raspberry Pi才能使更改生效。
外部存储配置
Edit this on GitHub
您可以将外部硬盘、SSD 或 U 盘连接到 Raspberry Pi 上的任何 USB 端口,并挂载文件系统以访问存储在其上的数据。
默认情况下,您的Raspberry Pi会自动在该 /media/pi/<HARD-DRIVE-LABEL>
位置挂载一些流行的文件系统,例如 FAT、NTFS 和 HFS+。
Note
|
Raspberry Pi OS Lite 不实现自动挂载。 |
若要设置存储设备以使其始终装载到您选择的特定位置,必须手动装载它。
挂载存储设备
您可以将存储设备装载到特定的文件夹位置。例如 /mnt/mydisk
,通常在 /mnt
文件夹中执行此操作。请注意,该文件夹必须为空。
-
将存储设备插入Raspberry Pi上的 USB 端口。
-
使用以下命令列出Raspberry Pi上的所有磁盘分区:
sudo lsblk -o UUID,NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL,MODEL
Raspberry Pi使用挂载点
/
和/boot
.您的存储设备将与任何其他连接的存储一起显示在此列表中。 -
使用“大小”、“标签”和“型号”列标识指向存储设备的磁盘分区的名称。例如
sda1
。 -
FSTYPE 列包含文件系统类型。如果您的存储设备使用 exFAT 文件系统,请安装 exFAT 驱动程序:
sudo apt update sudo apt install exfat-fuse
-
如果您的存储设备使用 NTFS 文件系统,您将对其具有只读访问权限。如果要写入设备,可以安装
ntfs-3g
驱动程序:sudo apt update sudo apt install ntfs-3g
-
运行以下命令以获取磁盘分区的位置:
sudo blkid
例如
/dev/sda1
。 -
创建一个目标文件夹作为存储设备的装入点。 本例中使用的装入点名称为
mydisk
。您可以指定您选择的名称:sudo mkdir /mnt/mydisk
-
将存储设备挂载到您创建的挂载点
sudo mount /dev/sda1 /mnt/mydisk
-
通过列出以下内容来验证存储设备是否已成功装载:
ls /mnt/mydisk
设置自动挂载
您可以修改 fstab
文件以定义在Raspberry Pi启动时存储设备自动挂载的位置。在 fstab
文件中,磁盘分区由通用唯一标识符 (UUID) 标识。
-
获取磁盘分区的 UUID:
sudo blkid
-
从列表中找到磁盘分区并记下 UUID。例如
5C24-1453
。 -
使用命令行编辑器(如 nano)打开
fstab
文件:sudo nano /etc/fstab
-
在
fstab
文件中添加以下行:UUID=5C24-1453 /mnt/mydisk fstype defaults,auto,users,rw,nofail 0 0
替换
fstype
为您在上述“挂载存储设备”的步骤 2 中找到的文件系统类型,例如:ntfs
。 -
5. 如果文件系统类型为 FAT 或 NTFS,请紧随
nofail
其后添加umask=000
- 这将允许所有用户对存储设备上的每个文件进行完全读/写访问。
现在您已经在中设置了一个 fstab
条目,您可以在连接或不连接存储设备的情况下启动Raspberry Pi。在拔下设备之前,您必须关闭Raspberry Pi,或使用下面“卸载存储设备”中的步骤手动卸载它。
Note
|
如果您在Raspberry Pi启动时没有连接存储设备,Raspberry Pi将需要额外的 90 秒才能启动。您可以通过在 nofail 后步骤 4 中立即添加 ,x-systemd.device-timeout=30 来缩短此时间。这会将超时更改为 30 秒,这意味着系统将只等待 30 秒,然后放弃尝试装载磁盘。
|
有关每个 Linux 命令的详细信息,请参阅使用该 man
命令的特定手册页。例如 man fstab
。
本地化您的Raspberry Pi
Edit this on GitHub
您可以将Raspberry Pi设置为与您的区域设置相匹配。
更改语言
如果要选择其他语言,请使用 raspi-config.
配置键盘
如果要选择其他键盘,请使用 raspi-config.
更改时区
使用 raspi-config
更改默认引脚配置
Edit this on GitHub
Warning
|
此功能适用于高级用户。 |
截至 2014 年 <7> 月,Raspberry Pi 固件通过用户提供的设备树 blob 文件支持自定义默认引脚配置。要了解您的固件是否足够新,请运行 vcgencmd version
启动序列期间的器件引脚
在启动序列期间,GPIO 引脚会经历各种操作
-
上电 — 引脚默认为具有默认拉动的输入; 数据手册 中描述了每个引脚的默认状态
-
通过引导进行设置
-
依据
bootcode.bin
-
依据
dt-blob.bin
-
通过在 GPIO command
config.txt
中设置 -
附加固件引脚 (例如 UARTS)
-
内核/设备树
在软复位时,相同的过程适用,但默认拉取除外,默认拉取仅适用于上电复位。
请注意,从阶段 1 到阶段 4 可能需要几秒钟。在此期间,GPIO 引脚可能未处于连接的外设(如 dtblob.bin
或 `config.txt`中所定义)所期望的状态。由于不同的 GPIO 引脚具有不同的默认拉取,因此应为外设执行以下操作之一:
-
选择一个 GPIO 引脚,该引脚默认为复位时外设需要拉取
-
将外设的启动延迟到达到第 4/5 阶段
-
添加适当的上拉/下拉电阻
自定义 Device Tree Blob
要将设备树源 (.dts
) 文件编译为设备树 blob (.dtb
) 文件,必须通过运行 sudo apt install device-tree-compiler
来安装设备树编译器。然后可以按如下方式使用该 dtc
命令:
sudo dtc -I dts -O dtb -o /boot/dt-blob.bin dt-blob.dts
同样,如果需要,可以将 .dtb
文件转换回文件 .dts
。
dtc -I dtb -O dts -o dt-blob.dts /boot/dt-blob.bin
dt-blob
章节
dt-blob.bin
用于在启动时配置二进制 blob (视频核心)。Linux 内核目前没有使用它,但稍后我们将重新配置 Raspberry Pi 内核以使用 dt-blob 进行配置时,将添加一个内核部分。dt-blob
可以配置所有版本的Raspberry Pi,包括计算模块,以使用替代设置。以下部分在 dt-blob 中有效:
-
videocore
本部分包含所有视频核心 blob 信息。所有后续部分必须包含在此部分中。
-
pins_*
有许多单独的
pins_*
部分,基于特定的Raspberry Pi模型,即:-
pins_rev1 Rev1 pin setup. 由于移动了I2C引脚,因此存在一些差异。
-
pins_rev2 Rev2 pin setup. 这包括 P5 上的附加编解码器引脚。
-
pins_bplus1 Raspberry Pi 1 Model B+ rev 1.1, 包括完整的 40 针连接器。
-
pins_bplus2 Raspberry Pi 1 Model B+ rev 1.2, 交换低功耗和局域网运行引脚。
-
pins_aplus Raspberry Pi 1 Model A+, 缺少以太网。
-
pins_2b1 Raspberry Pi 2 Model B rev 1.0; 通过 I2C0 控制 SMPS。
-
pins_2b2 Raspberry Pi 2 Model B rev 1.1; 通过软件 I2C 控制 42 和 43 上的 SMPS。
-
pins_3b1 Raspberry Pi 3 Model B rev 1.0
-
pins_3b2 Raspberry Pi 3 Model B rev 1.2
-
pins_3bplus Raspberry Pi 3 Model B+
-
pins_3aplus Raspberry Pi 3 Model A+
-
pins_pi0 Raspberry Pi Zero
-
pins_pi0w Raspberry Pi Zero W
-
pins_cm Raspberry Pi Compute Module 1. 默认值是芯片的默认值,因此它是有关芯片上默认上拉/下拉的有用信息来源。
-
pins_cm3 Raspberry Pi Compute Module 3
Each
pins_*
section can containpin_config
andpin_defines
sections.
-
-
pin_config
该
pin_config
部分用于配置各个引脚。此部分中的每个项目都必须是命名引脚部分,例如pin@p32
,表示 GPIO32。有一个特殊的部分pin@default
,其中包含pin_config部分中未明确命名的任何内容的默认设置。 -
pin@pinname
此部分可以包含以下项的任意组合:
-
polarity
-
active_high
-
active_low
-
-
termination
-
pull_up
-
pull_down
-
no_pulling
-
-
startup_state
-
active
-
inactive
-
-
function
-
input
-
output
-
sdcard
-
i2c0
-
i2c1
-
spi
-
spi1
-
spi2
-
smi
-
dpi
-
pcm
-
pwm
-
uart0
-
uart1
-
gp_clk
-
emmc
-
arm_jtag
-
-
drive_strength_mA
驱动强度用于设置引脚的强度。请注意,您只能为引脚指定单个驱动器强度。<8> 和 <16> 是有效值。
-
-
pin_defines
此部分用于将特定的视频核心功能设置为特定引脚。这使用户能够将相机电源使能引脚移动到其他位置,或移动HDMI热插拔位置:Linux无法控制的事情。请参考下面的 DTS 文件示例。
时钟配置
可以通过此接口更改时钟的配置,尽管很难预测结果!时钟系统的配置非常复杂。有五个独立的PLL,每个PLL都有自己的固定(或可变,在PLLC的情况下)VCO频率。然后,每个VCO都有许多不同的通道,可以使用不同的VCO频率划分来设置这些通道。每个时钟目标都可以配置为来自其中一个时钟通道,尽管源到目标的映射有限,因此 并非所有通道都可以路由到所有时钟目标。
以下是可用于更改特定时钟的几个示例配置。当提出时钟配置请求时,我们将添加到此资源中。
clock_routing { vco@PLLA { freq = <1966080000>; }; chan@APER { div = <4>; }; clock@GPCLK0 { pll = "PLLA"; chan = "APER"; }; }; clock_setup { clock@PWM { freq = <2400000>; }; clock@GPCLK0 { freq = <12288000>; }; clock@GPCLK1 { freq = <25000000>; }; };
上述内容会将 PLLA 设置为运行在 1.96608GHz 的源 VCO(此 VCO 的限制为 600MHz - 2.4GHz),将 APER 信道更改为 /4,并将 GPCLK0 配置为通过 APER 从 PLLA 源。这用于为音频编解码器提供产生 12288000 频率范围所需的 48000Hz。
示例设备树源文件
示例文件来自固件存储库 https://github.com/raspberrypi/firmware/blob/master/extra/dt-blob.dts. 这是主Raspberry Pi blob,其他文件通常是从它派生的。
设备树, Overlays 和参数
Edit this on GitHub
Raspberry Pi内核和固件使用设备树(DT)来描述Raspberry Pi中存在的硬件。这些设备树可能包括 DT 参数,这些参数提供对某些板载功能的一定程度的控制。DT叠加允许描述和配置可选的外部硬件,并且它们还支持参数以进行更多控制。
固件加载程序(start.elf
及其变体)负责加载 DTB(设备树 blob - 机器可读的 DT 文件)。它根据主板修订号选择要加载的,并进行某些修改以进一步定制它(内存大小、以太网地址等)。这种运行时自定义避免了对大量 DTB 的需求,只有细微的差异。
config.txt
扫描用户提供的参数以及任何叠加及其参数,然后应用这些参数。加载程序检查结果以了解(例如)哪个 UART(如果有)将用于控制台。最后,它启动内核,传递指向合并的 DTB 的指针。
Device Trees
设备树 (DT) 是对系统中硬件的描述。它应包括基本 CPU 的名称、内存配置和任何外围设备(内部和外部)。DT 不应用于描述软件,尽管通过列出硬件模块通常会导致加载驱动程序模块。记住DT应该是操作系统中立的,所以任何特定于Linux的东西可能都不应该存在。
设备树将硬件配置表示为节点层次结构。每个节点可以包含属性和子节点。属性是命名的字节数组,其中可能包含字符串、数字(大端序)、任意字节序列及其任意组合。通过类比文件系统,节点是目录,属性是文件。可以使用路径来描述树中节点和属性的位置,斜杠作为分隔符,单个斜杠 (/
) 表示根。
基本 DTS 语法
设备树通常以称为设备树源 (DTS) 的文本形式编写,并存储在带有后缀的 .dts
文件中。DTS 语法类似于 C,每行末尾都有用于分组的大括号和分号。请注意,DTS 在右大括号后需要分号:考虑 C struct 而不是函数。编译的二进制格式称为平展设备树 (FDT) 或设备树 Blob (DTB),存储在.dtb文件中。
以下是 .dts
格式的简单树:
/dts-v1/; /include/ "common.dtsi"; / { node1 { a-string-property = "A string"; a-string-list-property = "first string", "second string"; a-byte-data-property = [0x01 0x23 0x34 0x56]; cousin: child-node1 { first-child-property; second-child-property = <1>; a-string-property = "Hello, world"; }; child-node2 { }; }; node2 { an-empty-property; a-cell-property = <1 2 3 4>; /* each number (cell) is a uint32 */ child-node1 { my-cousin = <&cousin>; }; }; }; /node2 { another-property-for-node2; };
此树包含:
-
必需的标头
/dts-v1/
. -
包含另一个 DTS 文件,通常命名
*.dtsi
并类似于 C 中的头文件.h
- 请参阅下面的关于 /include/ 的旁白。 -
单个根节点:
/
-
几个子节点:
node1
和node2
-
节点 1 的一些子节点:
child-node1
和child-node2
-
标签 (
cousin
) 和对该标签的引用 (&cousin
): 参阅 Labels and References。 -
分散在树中的几个属性
-
重复节点 (
/node2
) - 参阅 An aside about /include/。
属性是简单的键值对,其中的值可以是空的,也可以包含任意字节流。虽然数据类型没有在数据结构中编码,但是有一些基本的数据表示可以在设备树源文件中表达。
文本字符串(以 NUL 结尾)用双引号表示:
string-property = "a string";
单元格是用尖括号分隔的 32 位无符号整数:
cell-property = <0xbeef 123 0xabcd1234>;
任意字节数据用方括号分隔,并以十六进制输入:
binary-property = [01 23 45 67 89 ab cd ef];
不同表示形式的数据可以使用逗号连接:
mixed-property = "a string", [01 23 45 67], <0x12345678>;
逗号也用于创建字符串列表:
string-list = "red fish", "blue fish";
关于 /include/
/include/
指令导致简单的文本包含,很像C #的 #include
指令,但是设备树编译器的一个特性导致不同的使用模式。假定节点是命名的,可能带有绝对路径,则同一个节点可能会在DTS文件(及其包含文件)中出现两次。当这种情况发生时,节点和属性被组合,根据需要交错和覆盖属性(后面的值覆盖前面的值)。
在上面的示例中,第二次 /node2
出现会导致将新属性添加到原始属性:
/node2 { an-empty-property; a-cell-property = <1 2 3 4>; /* each number (cell) is a uint32 */ another-property-for-node2; child-node1 { my-cousin = <&cousin>; }; };
因此, .dtsi
可以覆盖树中的多个位置或为树中的多个位置提供默认值。
标签和引用
树的一部分通常需要引用另一部分,有四种方法可以做到这一点:
-
Path strings
路径应该是不言自明的,类似于文件系统-
/soc/i2s@7e203000
是BCM2835和BCM2836中i2s设备的完整路径。注意,虽然构造一个属性的路径很容易(例如,/soc/i2s@7e203000/status
),但是标准的API不会这样做;首先找到一个节点,然后选择该节点的属性。 -
phandles
phandle是在其
phandle
属性中分配给节点的唯一32位整数。由于历史原因,你可能还会看到一个冗余的、匹配的linux,phandle
。phandles按顺序编号,从1开始;0不是有效的phandle。它们通常由DT编译器在遇到对整数上下文中的节点的引用时分配,通常以标签的形式(见下文)。使用phandles对节点的引用被简单地编码为相应的整数(单元)值;没有标记表明它们应该被解释为phandles,因为这是应用程序定义的。 -
Labels
就像C语言中的标签给代码中的位置命名一样,DT标签给层次结构中的节点命名。当在字符串上下文(
&node
)和整数上下文(<&node>
)中使用phandles时,编译器接受对标签的引用并将其转换为路径;原始标签不会出现在编译后的输出中。请注意,标签不包含任何结构;它们只是平面全局名称空间中的标记。 -
Aliases
别名与标注类似,只是它们以索引的形式出现在FDT输出中。它们存储为
/aliases
节点的属性,每个属性将一个别名映射到一个路径字符串。尽管别名节点出现在源代码中,但路径字符串通常作为对标签(&node
)的引用出现,而不是被完整写出。将路径字符串解析为节点的DT APIs通常会查看路径的第一个字符,将不以斜杠开头的路径视为别名,必须首先使用/aliases
表将其转换为路径。
设备树语义
如何构建设备树,以及如何最好地使用它来捕获某些硬件的配置,是一个庞大而复杂的主题。有许多可用的资源,下面列出了其中一些资源,但本文档中有几点值得一提:
compatible
属性是硬件描述和驱动程序软件之间的链接。当操作系统遇到具有 compatible
属性的节点时,它会在设备驱动程序数据库中查找,以找到最佳匹配。在Linux中,这通常会导致驱动程序模块被自动加载,前提是它已经被适当地标记并且没有被列入黑名单。
status
属性表示设备是启用还是禁用。如果 status
为 ok
, okay
或 absent,则设备已启用。否则,应禁用状态,以便禁用设备。将状态设置为禁用的设备放在. dtsi
文件中会很有用。派生的配置可以包括该内容。.dtsi
,并将所需设备的状态设置为正常。
Device Tree Overlays
现代SoC(片上系统)是一个非常复杂的设备;一个完整的设备树可能有数百行长。更进一步,将SoC与其他组件一起放在电路板上只会让事情变得更糟。为了保持可管理性,特别是如果有共享组件的相关设备,将公共元素放在 .dtsi
文件中是有意义的,这些元素可能包含在多个 .dts
文件中。
当像Raspberry Pi这样的系统也支持可选的插件配件(如 HAT)时,问题就会增加。最终,每种可能的配置都需要设备树来描述它,但是一旦考虑到所有不同的基本型号和大量可用的附件,组合的数量就会开始迅速增加。
需要的是一种使用部分设备树描述这些可选组件的方法,然后能够通过采用基本数字孪生并添加许多可选元素来构建完整的树。您可以执行此操作,这些可选元素称为"overlays"。
除非您想学习如何为 Raspberry Pis 编写叠加层,否则您可能更愿意跳到 Part 3: Using Device Trees on Raspberry Pi 在 Raspberry Pi 上使用设备树。
Fragments
A DT overlay comprises a number of fragments, each of which targets one node and its subnodes. Although the concept sounds simple enough, the syntax seems rather strange at first:
// Enable the i2s interface /dts-v1/; /plugin/; / { compatible = "brcm,bcm2835"; fragment@0 { target = <&i2s>; __overlay__ { status = "okay"; test_ref = <&test_label>; test_label: test_subnode { dummy; }; }; }; };
The compatible
string identifies this as being for BCM2835, which is the base architecture for the Raspberry Pi SoCs; if the overlay makes use of features of a Raspberry Pi 4 then brcm,bcm2711
is the correct value to use, otherwise brcm,bcm2835
can be used for all Raspberry Pi overlays. Then comes the first (and in this case only) fragment. Fragments should be numbered sequentially from zero. Failure to adhere to this may cause some or all of your fragments to be missed.
Each fragment consists of two parts: a target
property, identifying the node to apply the overlay to; and the __overlay__
itself, the body of which is added to the target node. The example above can be interpreted as if it were written like this:
/dts-v1/; /plugin/; / { compatible = "brcm,bcm2835"; }; &i2s { status = "okay"; test_ref = <&test_label>; test_label: test_subnode { dummy; }; };
(In fact, with a sufficiently new version of dtc
you can write it exactly like that and get identical output, but some homegrown tools don’t understand this format yet so any overlay that you might want to be included in the standard Raspberry Pi OS kernel should be written in the old format for now).
The effect of merging that overlay with a standard Raspberry Pi base Device Tree (e.g. bcm2708-rpi-b-plus.dtb
), provided the overlay is loaded afterwards, would be to enable the I2S interface by changing its status to okay
. But if you try to compile this overlay using:
dtc -I dts -O dtb -o 2nd.dtbo 2nd-overlay.dts
you will get an error:
Label or path i2s not found
This shouldn’t be too unexpected, since there is no reference to the base .dtb
or .dts
file to allow the compiler to find the i2s
label.
Trying again, this time using the original example and adding the -@
option to allow unresolved references (and -Hepapr
to remove some clutter):
dtc -@ -Hepapr -I dts -O dtb -o 1st.dtbo 1st-overlay.dts
If dtc
returns an error about the third line, it doesn’t have the extensions required for overlay work. Run sudo apt install device-tree-compiler
and try again - this time, compilation should complete successfully. Note that a suitable compiler is also available in the kernel tree as scripts/dtc/dtc
, built when the dtbs
make target is used:
make ARCH=arm dtbs
It is interesting to dump the contents of the DTB file to see what the compiler has generated:
fdtdump 1st.dtbo
/dts-v1/;
// magic: 0xd00dfeed
// totalsize: 0x207 (519)
// off_dt_struct: 0x38
// off_dt_strings: 0x1c8
// off_mem_rsvmap: 0x28
// version: 17
// last_comp_version: 16
// boot_cpuid_phys: 0x0
// size_dt_strings: 0x3f
// size_dt_struct: 0x190
/ {
compatible = "brcm,bcm2835";
fragment@0 {
target = <0xffffffff>;
__overlay__ {
status = "okay";
test_ref = <0x00000001>;
test_subnode {
dummy;
phandle = <0x00000001>;
};
};
};
__symbols__ {
test_label = "/fragment@0/__overlay__/test_subnode";
};
__fixups__ {
i2s = "/fragment@0:target:0";
};
__local_fixups__ {
fragment@0 {
__overlay__ {
test_ref = <0x00000000>;
};
};
};
};
After the verbose description of the file structure there is our fragment. But look carefully - where we wrote &i2s
it now says 0xffffffff
, a clue that something strange has happened (older versions of dtc might say 0xdeadbeef
instead). The compiler has also added a phandle
property containing a unique (to this overlay) small integer to indicate that the node has a label, and replaced all references to the label with the same small integer.
After the fragment there are three new nodes:
-
__symbols__
lists the labels used in the overlay (test_label
here), and the path to the labelled node. This node is the key to how unresolved symbols are dealt with. -
__fixups__
contains a list of properties mapping the names of unresolved symbols to lists of paths to cells within the fragments that need patching with the phandle of the target node, once that target has been located. In this case, the path is to the0xffffffff
value oftarget
, but fragments can contain other unresolved references which would require additional fixes. -
__local_fixups__
holds the locations of any references to labels that exist within the overlay - thetest_ref
property. This is required because the program performing the merge will have to ensure that phandle numbers are sequential and unique.
Back in section 1.3 it says that "the original labels do not appear in the compiled output", but this isn’t true when using the -@
switch. Instead, every label results in a property in the __symbols__
node, mapping a label to a path, exactly like the aliases
node. In fact, the mechanism is so similar that when resolving symbols, the Raspberry Pi loader will search the "aliases" node in the absence of a __symbols__
node. This was useful at one time because providing sufficient aliases allowed very old versions of dtc
to be used to build the base DTB files, but fortunately that is ancient history now.
Device Tree parameters
To avoid the need for lots of Device Tree overlays, and to reduce the need for users of peripherals to modify DTS files, the Raspberry Pi loader supports a new feature - Device Tree parameters. This permits small changes to the DT using named parameters, similar to the way kernel modules receive parameters from modprobe
and the kernel command line. Parameters can be exposed by the base DTBs and by overlays, including HAT overlays.
Parameters are defined in the DTS by adding an __overrides__
node to the root. It contains properties whose names are the chosen parameter names, and whose values are a sequence comprising a phandle (reference to a label) for the target node, and a string indicating the target property; string, integer (cell) and boolean properties are supported.
String parameters
String parameters are declared like this:
name = <&label>,"property";
where label
and property
are replaced by suitable values. String parameters can cause their target properties to grow, shrink, or be created.
Note that properties called status
are treated specially; non-zero/true/yes/on values are converted to the string "okay"
, while zero/false/no/off becomes "disabled"
.
Integer parameters
Integer parameters are declared like this:
name = <&label>,"property.offset"; // 8-bit name = <&label>,"property;offset"; // 16-bit name = <&label>,"property:offset"; // 32-bit name = <&label>,"property#offset"; // 64-bit
where label
, property
and offset
are replaced by suitable values; the offset is specified in bytes relative to the start of the property (in decimal by default), and the preceding separator dictates the size of the parameter. In a change from earlier implementations, integer parameters may refer to non-existent properties or to offsets beyond the end of an existing property.
Boolean parameters
Device Tree encodes boolean values as zero-length properties; if present then the property is true, otherwise it is false. They are defined like this:
boolean_property; // Set 'boolean_property' to true
Note that a property is assigned the value false
by not defining it. Boolean parameters are declared like this:
name = <&label>,"property?";
where label
and property
are replaced by suitable values.
Inverted booleans invert the input value before applying it in the same was as a regular boolean; they are declared similarly, but use !
to indicate the inversion:
name = <&label>,"property!";
Boolean parameters can cause properties to be created or deleted, but they can’t delete a property that already exists in the base DTB.
Byte string parameters
Byte string properties are arbitrary sequences of bytes, e.g. MAC addresses. They accept strings of hexadecimal bytes, with or without colons between the bytes.
mac_address = <ðernet0>,"local_mac_address[";
The [
was chosen to match the DT syntax for declaring a byte string:
local_mac_address = [aa bb cc dd ee ff];
Parameters with multiple targets
There are some situations where it is convenient to be able to set the same value in multiple locations within the Device Tree. Rather than the ungainly approach of creating multiple parameters, it is possible to add multiple targets to a single parameter by concatenating them, like this:
__overrides__ { gpiopin = <&w1>,"gpios:4", <&w1_pins>,"brcm,pins:0"; ... };
(example taken from the w1-gpio
overlay)
Note
|
It is even possible to target properties of different types with a single parameter. You could reasonably connect an "enable" parameter to a status string, cells containing zero or one, and a proper boolean property.
|
Literal assignments
As seen in 2.2.5, the DT parameter mechanism allows multiple targets to be patched from the same parameter, but the utility is limited by the fact that the same value has to be written to all locations (except for format conversion and the negation available from inverted booleans). The addition of embedded literal assignments allows a parameter to write arbitrary values, regardless of the parameter value supplied by the user.
Assignments appear at the end of a declaration, and are indicated by a =
:
str_val = <&target>,"strprop=value"; // 1 int_val = <&target>,"intprop:0=42 // 2 int_val2 = <&target>,"intprop:0=",<42>; // 3 bytes = <&target>,"bytestr[=b8:27:eb:01:23:45"; // 4
Lines 1, 2 and 4 are fairly obvious, but line 3 is more interesting because the value appears as an integer (cell) value. The DT compiler evaluates integer expressions at compile time, which might be convenient (particularly if macro values are used), but the cell can also contain a reference to a label:
// Force an LED to use a GPIO on the internal GPIO controller. exp_led = <&led1>,"gpios:0=",<&gpio>, <&led1>,"gpios:4";
When the overlay is applied, the label will be resolved against the base DTB in the usual way. Note that it is a good idea to split multi-part parameters over multiple lines like this to make them easier to read - something that becomes more necessary with the addition of cell value assignments like this.
Bear in mind that parameters do nothing unless they are applied - a default value in a lookup table is ignored unless the parameter name is used without assigning a value.
Lookup tables
Lookup tables allow parameter input values to be transformed before they are used. They act as associative arrays, rather like switch/case statements:
phonetic = <&node>,"letter{a=alpha,b=bravo,c=charlie,d,e,='tango uniform'}"; bus = <&fragment>,"target:0{0=",<&i2c0>,"1=",<&i2c1>,"}";
A key with no =value
means to use the key as the value, an =
with no key before it is the default value in the case of no match, and starting or ending the list with a comma (or an empty key=value pair anywhere) indicates that the unmatched input value should be used unaltered; otherwise, not finding a match is an error.
Note
|
The comma separator within the table string after a cell integer value is implicit - adding one explicitly creates an empty pair (see above). |
Note
|
As lookup tables operate on input values and literal assignments ignore them, it’s not possible to combine the two - characters after the closing } in the lookup declaration are treated as an error.
|
Overlay/fragment parameters
The DT parameter mechanism as described has a number of limitations, including no easy way to create arrays of integers and the inability to create new nodes. One way to overcome some of these limitations is to conditionally include or exclude certain fragments.
A fragment can be excluded from the final merge process (disabled) by renaming the __overlay__
node to __dormant__
. The parameter declaration syntax has been extended to allow the otherwise illegal zero target phandle to indicate that the following string contains operations at fragment or overlay scope. So far, four operations have been implemented:
+<n> // Enable fragment <n> -<n> // Disable fragment <n> =<n> // Enable fragment <n> if the assigned parameter value is true, otherwise disable it !<n> // Enable fragment <n> if the assigned parameter value is false, otherwise disable it
Examples:
just_one = <0>,"+1-2"; // Enable 1, disable 2 conditional = <0>,"=3!4"; // Enable 3, disable 4 if value is true, // otherwise disable 3, enable 4.
The i2c-rtc
overlay uses this technique.
Special properties
A few property names, when targeted by a parameter, get special handling. One you may have noticed already - status
- which will convert a boolean to either okay
for true and disabled
for false.
Assigning to the bootargs
property appends to it rather than overwriting it - this is how settings can be added to the kernel command line.
The reg
property is used to specify device addresses - the location of a memory-mapped hardware block, the address on an I2C bus, etc. The names of child nodes should be qualified with their addresses in hexadecimal, using @
as a separator:
bmp280@76 { reg = <0x77>; ... };
When assigning to the reg
property, the address portion of the parent node name will be replaced with the assigned value. This can be used to prevent a node name clash when using the same overlay multiple times - a technique used by the i2c-gpio
overlay.
The name
property is a pseudo-property - it shouldn’t appear in a DT, but assigning to it causes the name of its parent node to be changed to the assigned value. Like the reg
property, this can be used to give nodes unique names.
The overlay map file
The introduction of the Raspberry Pi 4, built around the BCM2711 SoC, brought with it many changes; some of these changes are additional interfaces, and some are modifications to (or removals of) existing interfaces. There are new overlays intended specifically for the Raspberry Pi 4 that don’t make sense on older hardware, e.g. overlays that enable the new SPI, I2C and UART interfaces, but other overlays don’t apply correctly even though they control features that are still relevant on the new device.
There is therefore a need for a method of tailoring an overlay to multiple platforms with differing hardware. Supporting them all in a single .dtbo file would require heavy use of hidden ("dormant") fragments and a switch to an on-demand symbol resolution mechanism so that a missing symbol that isn’t needed doesn’t cause a failure. A simpler solution is to add a facility to map an overlay name to one of several implementation files depending on the current platform.
The overlay map, which is rolling out with the switch to Linux 5.4, is a file that gets loaded by the firmware at bootup. It is written in DTS source format - overlay_map.dts
, compiled to overlay_map.dtb
and stored in the overlays directory.
This is an edited version of the current map file (see the full version):
/ { vc4-kms-v3d { bcm2835; bcm2711 = "vc4-kms-v3d-pi4"; }; vc4-kms-v3d-pi4 { bcm2711; }; uart5 { bcm2711; }; pi3-disable-bt { renamed = "disable-bt"; }; lirc-rpi { deprecated = "use gpio-ir"; }; };
Each node has the name of an overlay that requires special handling. The properties of each node are either platform names or one of a small number of special directives. The current supported platforms are bcm2835
, which includes all Raspberry Pis built around the BCM2835, BCM2836 and BCM2837 SoCs, and bcm2711
for Raspberry Pi 4B.
A platform name with no value (an empty property) indicates that the current overlay is compatible with the platform; for example, vc4-kms-v3d
is compatible with the bcm2835
platform. A non-empty value for a platform is the name of an alternative overlay to use in place of the requested one; asking for vc4-kms-v3d
on BCM2711 results in vc4-kms-v3d-pi4
being loaded instead. Any platform not included in an overlay’s node is not compatible with that overlay.
The second example node - vc4-kms-v3d-pi4
- could be inferred from the content of vc4-kms-v3d
, but that intelligence goes into the construction of the file, not its interpretation.
In the event that a platform is not listed for an overlay, one of the special directives may apply:
-
The
renamed
directive indicates the new name of the overlay (which should be largely compatible with the original), but also logs a warning about the rename. -
The
deprecated
directive contains a brief explanatory error message which will be logged after the common prefixoverlay '...' is deprecated:
.
Remember: only exceptions need to be listed - the absence of a node for an overlay means that the default file should be used for all platforms.
Accessing diagnostic messages from the firmware is covered in Debugging.
The dtoverlay
and dtmerge
utilities have been extended to support the map file:
-
dtmerge
extracts the platform name from the compatible string in the base DTB. -
dtoverlay
reads the compatible string from the live Device Tree at/proc/device-tree
, but you can use the-p
option to supply an alternate platform name (useful for dry runs on a different platform).
They both send errors, warnings and any debug output to STDERR.
Examples
Here are some examples of different types of properties, with parameters to modify them:
/ { fragment@0 { target-path = "/"; __overlay__ { test: test_node { string = "hello"; status = "disabled"; bytes = /bits/ 8 <0x67 0x89>; u16s = /bits/ 16 <0xabcd 0xef01>; u32s = /bits/ 32 <0xfedcba98 0x76543210>; u64s = /bits/ 64 < 0xaaaaa5a55a5a5555 0x0000111122223333>; bool1; // Defaults to true // bool2 defaults to false mac = [01 23 45 67 89 ab]; spi = <&spi0>; }; }; }; fragment@1 { target-path = "/"; __overlay__ { frag1; }; }; fragment@2 { target-path = "/"; __dormant__ { frag2; }; }; __overrides__ { string = <&test>,"string"; enable = <&test>,"status"; byte_0 = <&test>,"bytes.0"; byte_1 = <&test>,"bytes.1"; u16_0 = <&test>,"u16s;0"; u16_1 = <&test>,"u16s;2"; u32_0 = <&test>,"u32s:0"; u32_1 = <&test>,"u32s:4"; u64_0 = <&test>,"u64s#0"; u64_1 = <&test>,"u64s#8"; bool1 = <&test>,"bool1!"; bool2 = <&test>,"bool2?"; entofr = <&test>,"english", <&test>,"french{hello=bonjour,goodbye='au revoir',weekend}"; pi_mac = <&test>,"mac[{1=b8273bfedcba,2=b8273b987654}"; spibus = <&test>,"spi:0[0=",<&spi0>,"1=",<&spi1>,"2=",<&spi2>; only1 = <0>,"+1-2"; only2 = <0>,"-1+2"; enable1 = <0>,"=1"; disable2 = <0>,"!2"; }; };
For further examples, there is a large collection of overlay source files hosted in the Raspberry Pi Linux GitHub repository.
Exporting labels
The overlay handling in the firmware and the run-time overlay application using the dtoverlay
utility treat labels defined in an overlay as being private to that overlay. This avoids the need to invent globally unique names for labels (which keeps them short), and it allows the same overlay to be used multiple times without clashing (provided some tricks are used - see Special properties).
Sometimes, however, it is very useful to be able to create a label with one overlay and use it from another. Firmware released since 14th February 2020 has the ability to declare some labels as being global - the __exports__
node:
... public: ... __exports__ { public; // Export the label 'public' to the base DT }; };
When this overlay is applied, the loader strips out all symbols except those that have been exported, in this case public
, and rewrites the path to make it relative to the target of the fragment containing the label. Overlays loaded after this one can then refer to &public
.
Overlay application order
Under most circumstances it shouldn’t matter which order the fragments are applied, but for overlays that patch themselves (where the target of a fragment is a label in the overlay, known as an intra-overlay fragment) it becomes important. In older firmware, fragments are applied strictly in order, top to bottom. With firmware released since 14th February 2020, fragments are applied in two passes:
-
First the fragments that target other fragments are applied and hidden.
-
Then the regular fragments are applied.
This split is particularly important for runtime overlays, since step (i) occurs in the dtoverlay
utility, and step (ii) is performed by the kernel (which can’t handle intra-overlay fragments).
Using Device Trees on Raspberry Pi
DTBs, overlays and config.txt
On a Raspberry Pi it is the job of the loader (one of the start.elf
images) to combine overlays with an appropriate base device tree, and then to pass a fully resolved Device Tree to the kernel. The base Device Trees are located alongside start.elf
in the FAT partition (/boot from Linux), named bcm2711-rpi-4-b.dtb
, bcm2710-rpi-3-b-plus.dtb
, etc. Note that some models (3A+, A, A+) will use the "b" equivalents (3B+, B, B+), respectively. This selection is automatic, and allows the same SD card image to be used in a variety of devices.
Note
|
DT and ATAGs are mutually exclusive, and passing a DT blob to a kernel that doesn’t understand it will cause a boot failure. The firmware will always try to load the DT and pass it to the kernel, since all kernels since rpi-4.4.y will not function without a DTB. You can override this by adding device_tree= in config.txt, which forces the use of ATAGs, which can be useful for simple "bare-metal" kernels.
|
[ The firmware used to look for a trailer appended to kernels by the mkknlimg
utility, but support for this has been withdrawn. ]
The loader now supports builds using bcm2835_defconfig, which selects the upstreamed BCM2835 support. This configuration will cause bcm2835-rpi-b.dtb
and bcm2835-rpi-b-plus.dtb
to be built. If these files are copied with the kernel, then the loader will attempt to load one of those DTBs by default.
In order to manage Device Tree and overlays, the loader supports a number of config.txt
directives:
dtoverlay=acme-board dtparam=foo=bar,level=42
This will cause the loader to look for overlays/acme-board.dtbo
in the firmware partition, which Raspberry Pi OS mounts on /boot
. It will then search for parameters foo
and level
, and assign the indicated values to them.
The loader will also search for an attached HAT with a programmed EEPROM, and load the supporting overlay from there - either directly or by name from the "overlays" directory; this happens without any user intervention.
There are several ways to tell that the kernel is using Device Tree:
-
The "Machine model:" kernel message during bootup has a board-specific value such as "Raspberry Pi 2 Model B", rather than "BCM2709".
-
/proc/device-tree
exists, and contains subdirectories and files that exactly mirror the nodes and properties of the DT.
With a Device Tree, the kernel will automatically search for and load modules that support the indicated enabled devices. As a result, by creating an appropriate DT overlay for a device you save users of the device from having to edit /etc/modules
; all of the configuration goes in config.txt
, and in the case of a HAT, even that step is unnecessary. Note, however, that layered modules such as i2c-dev
still need to be loaded explicitly.
The flipside is that because platform devices don’t get created unless requested by the DTB, it should no longer be necessary to blacklist modules that used to be loaded as a result of platform devices defined in the board support code. In fact, current Raspberry Pi OS images ship with no blacklist files (except for some WLAN devices where multiple drivers are available).
DT parameters
As described above, DT parameters are a convenient way to make small changes to a device’s configuration. The current base DTBs support parameters for enabling and controlling the onboard audio, I2C, I2S and SPI interfaces without using dedicated overlays. In use, parameters look like this:
dtparam=audio=on,i2c_arm=on,i2c_arm_baudrate=400000,spi=on
Note
|
Multiple assignments can be placed on the same line, but ensure you don’t exceed the 80-character limit. |
If you have an overlay that defines some parameters, they can be specified either on subsequent lines like this:
dtoverlay=lirc-rpi dtparam=gpio_out_pin=16 dtparam=gpio_in_pin=17 dtparam=gpio_in_pull=down
or appended to the overlay line like this:
dtoverlay=lirc-rpi,gpio_out_pin=16,gpio_in_pin=17,gpio_in_pull=down
Overlay parameters are only in scope until the next overlay is loaded. In the event of a parameter with the same name being exported by both the overlay and the base, the parameter in the overlay takes precedence; for clarity, it’s recommended that you avoid doing this. To expose the parameter exported by the base DTB instead, end the current overlay scope using:
dtoverlay=
Board-specific labels and parameters
Raspberry Pi boards have two I2C interfaces. These are nominally split: one for the ARM, and one for VideoCore (the "GPU"). On almost all models, i2c1
belongs to the ARM and i2c0
to VC, where it is used to control the camera and read the HAT EEPROM. However, there are two early revisions of the Model B that have those roles reversed.
To make it possible to use one set of overlays and parameters with all Raspberry Pis, the firmware creates some board-specific DT parameters. These are:
i2c/i2c_arm i2c_vc i2c_baudrate/i2c_arm_baudrate i2c_vc_baudrate
These are aliases for i2c0
, i2c1
, i2c0_baudrate
, and i2c1_baudrate
. It is recommended that you only use i2c_vc
and i2c_vc_baudrate
if you really need to - for example, if you are programming a HAT EEPROM (which is better done using a software I2C bus using the i2c-gpio
overlay). Enabling i2c_vc
can stop the Raspberry Pi Camera or Raspberry Pi Touch Display functioning correctly.
For people writing overlays, the same aliasing has been applied to the labels on the I2C DT nodes. Thus, you should write:
fragment@0 { target = <&i2c_arm>; __overlay__ { status = "okay"; }; };
Any overlays using the numeric variants will be modified to use the new aliases.
HATs and Device Tree
A Raspberry Pi HAT is an add-on board with an embedded EEPROM designed for a Raspberry Pi with a 40-pin header. The EEPROM includes any DT overlay required to enable the board (or the name of an overlay to load from the filing system), and this overlay can also expose parameters.
The HAT overlay is automatically loaded by the firmware after the base DTB, so its parameters are accessible until any other overlays are loaded, or until the overlay scope is ended using dtoverlay=
. If for some reason you want to suppress the loading of the HAT overlay, put dtoverlay=
before any other dtoverlay
or dtparam
directive.
Dynamic Device Tree
As of Linux 4.4, Raspberry Pi kernels support the dynamic loading of overlays and parameters. Compatible kernels manage a stack of overlays that are applied on top of the base DTB. Changes are immediately reflected in /proc/device-tree
and can cause modules to be loaded and platform devices to be created and destroyed.
The use of the word "stack" above is important - overlays can only be added and removed at the top of the stack; changing something further down the stack requires that anything on top of it must first be removed.
There are some new commands for managing overlays:
The dtoverlay
command
dtoverlay
is a command line utility that loads and removes overlays while the system is running, as well as listing the available overlays and displaying their help information.
Use dtoverlay -h
to get usage information:
Usage: dtoverlay <overlay> [<param>=<val>...] Add an overlay (with parameters) dtoverlay -D [<idx>] Dry-run (prepare overlay, but don't apply - save it as dry-run.dtbo) dtoverlay -r [<overlay>] Remove an overlay (by name, index or the last) dtoverlay -R [<overlay>] Remove from an overlay (by name, index or all) dtoverlay -l List active overlays/params dtoverlay -a List all overlays (marking the active) dtoverlay -h Show this usage message dtoverlay -h <overlay> Display help on an overlay dtoverlay -h <overlay> <param>.. Or its parameters where <overlay> is the name of an overlay or 'dtparam' for dtparams Options applicable to most variants: -d <dir> Specify an alternate location for the overlays (defaults to /boot/overlays or /flash/overlays) -v Verbose operation
Unlike the config.txt
equivalent, all parameters to an overlay must be included in the same command line - the dtparam command is only for parameters of the base DTB.
Two points to note:
-
Command variants that change kernel state (adding and removing things) require root privilege, so you may need to prefix the command with
sudo
. -
Only overlays and parameters applied at run-time can be unloaded - an overlay or parameter applied by the firmware becomes "baked in" such that it won’t be listed by
dtoverlay
and can’t be removed.
The dtparam
command
dtparam
creates and loads an overlay that has largely the same effect as using a dtparam directive in config.txt
. In usage it is largely equivalent to dtoverlay
with an overlay name of -
, but there are a few differences:
-
dtparam
will list the help information for all known parameters of the base DTB. Help on the dtparam command is still available usingdtparam -h
. -
When indicating a parameter for removal, only index numbers can be used (not names).
-
Not all Linux subsystems respond to the addition of devices at runtime - I2C, SPI and sound devices work, but some won’t.
Guidelines for writing runtime-capable overlays
This area is poorly documented, but here are some accumulated tips:
-
The creation or deletion of a device object is triggered by a node being added or removed, or by the status of a node changing from disabled to enabled or vice versa. Beware - the absence of a "status" property means the node is enabled.
-
Don’t create a node within a fragment that will overwrite an existing node in the base DTB - the kernel will rename the new node to make it unique. If you want to change the properties of an existing node, create a fragment that targets it.
-
ALSA doesn’t prevent its codecs and other components from being unloaded while they are in use. Removing an overlay can cause a kernel exception if it deletes a codec that is still being used by a sound card. Experimentation found that devices are deleted in the reverse of fragment order in the overlay, so placing the node for the card after the nodes for the components allows an orderly shutdown.
Caveats
The loading of overlays at runtime is a recent addition to the kernel, and so far there is no accepted way to do this from userspace. By hiding the details of this mechanism behind commands the aim is to insulate users from changes in the event that a different kernel interface becomes standardised.
-
Some overlays work better at run-time than others. Parts of the Device Tree are only used at boot time - changing them using an overlay will not have any effect.
-
Applying or removing some overlays may cause unexpected behaviour, so it should be done with caution. This is one of the reasons it requires
sudo
. -
Unloading the overlay for an ALSA card can stall if something is actively using ALSA - the LXPanel volume slider plugin demonstrates this effect. To enable overlays for sound cards to be removed, the
lxpanelctl
utility has been given two new options -alsastop
andalsastart
- and these are called from the auxiliary scriptsdtoverlay-pre
anddtoverlay-post
before and after overlays are loaded or unloaded, respectively. -
Removing an overlay will not cause a loaded module to be unloaded, but it may cause the reference count of some modules to drop to zero. Running
rmmod -a
twice will cause unused modules to be unloaded. -
Overlays have to be removed in reverse order. The commands will allow you to remove an earlier one, but all the intermediate ones will be removed and re-applied, which may have unintended consequences.
-
Only Device Tree nodes at the top level of the tree and children of a bus node will be probed. For nodes added at run-time there is the further limitation that the bus must register for notifications of the addition and removal of children. However, there are exceptions that break this rule and cause confusion: the kernel explicitly scans the entire tree for some device types - clocks and interrupt controller being the two main ones - in order to (for clocks) initialise them early and/or (for interrupt controllers) in a particular order. This search mechanism only happens during booting and so doesn’t work for nodes added by an overlay at run-time. It is therefore recommended for overlays to place fixed-clock nodes in the root of the tree unless it is guaranteed that the overlay will not be used at run-time.
Supported overlays and parameters
As it is too time-consuming to document the individual overlays here, please refer to the README file found alongside the overlay .dtbo
files in /boot/overlays
. It is kept up-to-date with additions and changes.
Firmware parameters
The firmware uses the special /chosen node to pass parameters between the bootloader and/or firmware and the operating system.
overlay_prefix
- string
The overlay_prefix string selected by config.txt
.
os_prefix
- string
The os_prefix string selected by config.txt
.
rpi-boardrev-ext
- 32-bit integer
The extended board revision code from OTP row 33.
rpi-country-code
- 32-bit integer
The country code used used by PiWiz - Pi400 only.
Common bootloader properties /chosen/bootloader
boot-mode
- 32-bit integer
The boot-mode used to load the kernel. See BOOT_ORDER.
partition
- 32-bit integer
The partition number used during boot. If a boot.img
ramdisk is loaded then this refers to partition that the ramdisk was loaded from rather than the partition number within the ramdisk.
pm_rsts
- 32-bit integer
The value of the PM_RSTS
register during boot.
tryboot
- 32-bit integer
Set to 1
if the tryboot
flag was set at boot.
BCM2711 specific bootloader properties /chosen/bootloader
The following properties are specific to BCM2711 SPI EEPROM bootloader.
build_timestamp
- 32-bit integer
The UTC build time for the EEPROM bootloader.
capabilities
- 32-bit integer
This bit-field describes the features supported by the current bootloader. This may be used to check whether a feature (e.g. USB boot) is supported before enabling it in the bootloader EEPROM config.
Bit | Feature |
---|---|
0 |
USB boot using the VLI USB host controller. |
1 |
|
2 |
TRYBOOT_A_B mode. |
3 |
|
4 |
USB boot using the BCM2711 USB host controller. |
5 |
|
6 |
|
7 |
update_timestamp
- 32-bit integer
The UTC update timestamp set by rpi-eeprom-update
.
signed_boot
- 32-bit integer
If secure-boot is enabled then this bit-field will be non-zero. The individual bits indicate the current secure-boot configuration.
Bit | Description |
---|---|
0 |
|
1 |
Reserved. |
2 |
The ROM development key has been revoked. See revoke_devkey. |
3 |
The customer public key digest has been written to OTP. See program_pubkey. |
4..31 |
Reserved. |
version
- string
The Git version string for the bootloader.
BCM2711 USB boot properties /chosen/bootloader/usb
The following properties are defined if the system was booted from USB. These may be used to uniquely identify the USB boot device.
usb-version
- 32-bit integer
The USB major protocol version (2 or 3).
route-string
- 32-bit integer
The USB route-string identifier for the device as defined by the USB 3.0 specification.
root-hub-port-number
- 32-bit integer
The root hub port number that the boot device is connected to - possibly via other USB hubs.
lun
- 32-bit integer
The Logical Unit Number for the mass-storage device.
NVMEM nodes
The firmware provides read-only, in-memory copies of portions of the bootloader EEPROM via the NVMEM Subsystem.
Each region appears as an NVMEM device under /sys/bus/nvmem/devices/
with a named alias under /sys/firmware/devicetree/base/aliases
.
Example shell script code for reading an NVMEM mode from rpi-eeprom-update
blconfig_alias="/sys/firmware/devicetree/base/aliases/blconfig" blconfig_nvmem_path="" if [ -f "${blconfig_alias}" ]; then blconfig_ofnode_path="/sys/firmware/devicetree/base"$(strings "${blconfig_alias}")"" blconfig_ofnode_link=$(find -L /sys/bus/nvmem -samefile "${blconfig_ofnode_path}" 2>/dev/null) if [ -e "${blconfig_ofnode_link}" ]; then blconfig_nvmem_path=$(dirname "${blconfig_ofnode_link}") fi fi fi
blconfig
The blconfig
alias refers to an NVMEM device that stores a copy of the bootloader EEPROM config file.
blpubkey
The blpubkey
alias points to an NVMEM device that stores a copy of the bootloader EEPROM public key (if defined) in binary format.
The rpi-bootloader-key-convert utility can be used to convert the data into PEM format for use with OpenSSL.
See also: secure-boot
Troubleshooting
Debugging
The loader will skip over missing overlays and bad parameters, but if there are serious errors, such as a missing or corrupt base DTB or a failed overlay merge, then the loader will fall back to a non-DT boot. If this happens, or if your settings don’t behave as you expect, it is worth checking for warnings or errors from the loader:
sudo vcdbg log msg
Extra debugging can be enabled by adding dtdebug=1
to config.txt
.
You can create a human-readable representation of the current state of DT like this:
dtc -I fs /proc/device-tree
This can be useful to see the effect of merging overlays onto the underlying tree.
If kernel modules don’t load as expected, check that they aren’t blacklisted in /etc/modprobe.d/raspi-blacklist.conf
; blacklisting shouldn’t be necessary when using Device Tree. If that shows nothing untoward, you can also check that the module is exporting the correct aliases by searching /lib/modules/<version>/modules.alias
for the compatible
value. Otherwise, your driver is probably missing either:
.of_match_table = xxx_of_match,
or:
MODULE_DEVICE_TABLE(of, xxx_of_match);
Failing that, depmod
has failed or the updated modules haven’t been installed on the target filesystem.
Testing overlays using dtmerge, dtdiff and ovmerge
Alongside the dtoverlay
and dtparam
commands is a utility for applying an overlay to a DTB - dtmerge
. To use it you first need to obtain your base DTB, which can be obtained in one of two ways:
a) generate it from the live DT state in /proc/device-tree
:
dtc -I fs -O dtb -o base.dtb /proc/device-tree
This will include any overlays and parameters you have applied so far, either in config.txt
or by loading them at runtime, which may or may not be what you want. Alternatively…
b) copy it from the source DTBs in /boot. This won’t include overlays and parameters, but it also won’t include any other modifications by the firmware. To allow testing of all overlays, the dtmerge
utility will create some of the board-specific aliases ("i2c_arm", etc.), but this means that the result of a merge will include more differences from the original DTB than you might expect. The solution to this is to use dtmerge to make the copy:
dtmerge /boot/bcm2710-rpi-3-b.dtb base.dtb -
(the -
indicates an absent overlay name).
You can now try applying an overlay or parameter:
dtmerge base.dtb merged.dtb - sd_overclock=62 dtdiff base.dtb merged.dtb
which will return:
--- /dev/fd/63 2016-05-16 14:48:26.396024813 +0100 +++ /dev/fd/62 2016-05-16 14:48:26.396024813 +0100 @@ -594,7 +594,7 @@ }; sdhost@7e202000 { - brcm,overclock-50 = <0x0>; + brcm,overclock-50 = <0x3e>; brcm,pio-limit = <0x1>; bus-width = <0x4>; clocks = <0x8>;
You can also compare different overlays or parameters.
dtmerge base.dtb merged1.dtb /boot/overlays/spi1-1cs.dtbo dtmerge base.dtb merged2.dtb /boot/overlays/spi1-2cs.dtbo dtdiff merged1.dtb merged2.dtb
to get:
--- /dev/fd/63 2016-05-16 14:18:56.189634286 +0100 +++ /dev/fd/62 2016-05-16 14:18:56.189634286 +0100 @@ -453,7 +453,7 @@ spi1_cs_pins { brcm,function = <0x1>; - brcm,pins = <0x12>; + brcm,pins = <0x12 0x11>; phandle = <0x3e>; }; @@ -725,7 +725,7 @@ #size-cells = <0x0>; clocks = <0x13 0x1>; compatible = "brcm,bcm2835-aux-spi"; - cs-gpios = <0xc 0x12 0x1>; + cs-gpios = <0xc 0x12 0x1 0xc 0x11 0x1>; interrupts = <0x1 0x1d>; linux,phandle = <0x30>; phandle = <0x30>; @@ -743,6 +743,16 @@ spi-max-frequency = <0x7a120>; status = "okay"; }; + + spidev@1 { + #address-cells = <0x1>; + #size-cells = <0x0>; + compatible = "spidev"; + phandle = <0x41>; + reg = <0x1>; + spi-max-frequency = <0x7a120>; + status = "okay"; + }; }; spi@7e2150C0 {
The Utils repo includes another DT utility - ovmerge
. Unlike dtmerge
, ovmerge
combines file and applies overlays in source form. Because the overlay is never compiled, labels are preserved and the result is usually more readable. It also has a number of other tricks, such as the ability to list the order of file inclusion.
Forcing a specific Device Tree
If you have very specific needs that aren’t supported by the default DTBs, or if you just want to experiment with writing your own DTs, you can tell the loader to load an alternate DTB file like this:
device_tree=my-pi.dtb
Disabling Device Tree usage
Since the switch to the 4.4 kernel and the use of more upstream drivers, Device Tree usage is required in Raspberry Pi Linux kernels. However, for bare metal and other OSs, the method of disabling DT usage is to add:
device_tree=
to config.txt
.
Shortcuts and syntax variants
The loader understands a few shortcuts:
dtparam=i2c_arm=on dtparam=i2s=on
can be shortened to:
dtparam=i2c,i2s
(i2c
is an alias of i2c_arm
, and the =on
is assumed). It also still accepts the long-form versions: device_tree_overlay
and device_tree_param
.
Other DT commands available in config.txt
device_tree_address
This is used to override the address where the firmware loads the device tree (not dt-blob). By default the firmware will choose a suitable place.
device_tree_end
This sets an (exclusive) limit to the loaded device tree. By default the device tree can grow to the end of usable memory, which is almost certainly what is required.
dtdebug
If non-zero, turn on some extra logging for the firmware’s device tree processing.
enable_uart
Enable the primary/console UART (ttyS0 on a Raspberry Pi 3, 4, 400, Zero W and Zero 2 W, ttyAMA0 otherwise - unless swapped with an overlay such as miniuart-bt). If the primary UART is ttyAMA0 then enable_uart
defaults to 1 (enabled), otherwise it defaults to 0 (disabled). This is because it is necessary to stop the core frequency from changing which would make ttyS0 unusable, so enable_uart=1
implies core_freq=250
(unless force_turbo=1
). In some cases this is a performance hit, so it is off by default.
overlay_prefix
Specifies a subdirectory/prefix from which to load overlays - defaults to "overlays/". Note the trailing "/". If desired you can add something after the final "/" to add a prefix to each file, although this is not likely to be needed.
Further ports can be controlled by the DT, for more details see section 3.
Further help
If you’ve read through this document and not found the answer to a Device Tree problem, there is help available. The author can usually be found on Raspberry Pi forums, particularly the Device Tree forum.
The Kernel Command Line
Edit this on GitHub
The Linux kernel accepts a command line of parameters during boot. On the Raspberry Pi, this command line is defined in a file in the boot partition, called cmdline.txt. This is a simple text file that can be edited using any text editor, e.g. Nano.
sudo nano /boot/cmdline.txt
Note
|
We have to use sudo to edit anything in the boot partition, and all parameters in cmdline.txt must be on the same line (no carriage returns).
|
The command line that was passed to the kernel at boot time can be displayed using cat /proc/cmdline
. It will not be exactly the same as that in cmdline.txt
as the firmware can make changes to it prior to launching the kernel.
Command Line Options
There are many kernel command line parameters, some of which are defined by the kernel. Others are defined by code that the kernel may be using, such as the Plymouth splash screen system.
Standard Entries
-
console: defines the serial console. There are usually two entries:
-
console=serial0,115200
-
console=tty1
-
-
root: defines the location of the root filesystem, e.g.
root=/dev/mmcblk0p2
means multimedia card block 0 partition 2. -
rootfstype: defines what type of filesystem the rootfs uses, e.g.
rootfstype=ext4
-
quiet: sets the default kernel log level to
KERN_WARNING
, which suppresses all but very serious log messages during boot.
Display Entries in FKMS and KMS modes
The firmware automatically adds a preferred resolution and overscan settings via an entry such as:
video=HDMI-A-1:1920x1080M@60,margin_left=0,margin_right=0,margin_top=0,margin_bottom=0
This default entry can be modified by duplicating the entry above manually in /boot/cmdline.txt and making required changes to the margin parameters. In addition, it is possible to add rotation and reflect parameters as documented in the standard Linux framebuffer documentation. By default the margin_*
options are set from the overscan
entries in config.txt, if present. The firmware can be prevented from making any KMS specific changes to the command line by adding disable_fw_kms_setup=1
to config.txt
An example entry may be as follows:
video=HDMI-A-1:1920x1080M@60,margin_left=0,margin_right=0,margin_top=0,margin_bottom=0,rotate=90,reflect_x`
Possible options for the display type, the first part of the video=
entry, are as follows:
video option | Display |
---|---|
HDMI-A-1 |
HDMI 1 (HDMI 0 on silkscreen of Raspberry Pi 4B, HDMI on single HDMI boards) |
HDMI-A-2 |
HDMI 2 (HDMI 1 on silkscreen of Raspberry Pi 4B) |
DSI-1 |
DSI or DPI |
Composite-1 |
Composite |
Other Entries (not exhaustive)
-
splash: tells the boot to use a splash screen via the Plymouth module.
-
plymouth.ignore-serial-consoles: normally if the Plymouth module is enabled it will prevent boot messages from appearing on any serial console which may be present. This flag tells Plymouth to ignore all serial consoles, making boot messages visible again, as they would be if Plymouth was not running.
-
dwc_otg.lpm_enable=0: turns off Link Power Management (LPM) in the dwc_otg driver; the dwc_otg driver is the driver for the USB controller built into the processor used on Raspberry Pi computers.
NoteOn Raspberry Pi 4 this controller is disabled by default, and is only connected to the USB type C power input connector; the USB type A ports on Raspberry Pi 4 are driven by a separate USB controller which is not affected by this setting. -
dwc_otg.speed: sets the speed of the USB controller built into the processor on Raspberry Pi computers.
dwc_otg.speed=1
will set it to full speed (USB 1.0), which is slower than high speed (USB 2.0). This option should not be set except during troubleshooting of problems with USB devices. -
smsc95xx.turbo_mode: enables/disables the wired networking driver turbo mode.
smsc95xx.turbo_mode=N
turns turbo mode off. -
usbhid.mousepoll: specifies the mouse polling interval. If you have problems with a slow or erratic wireless mouse, setting this to 0 might help:
usbhid.mousepoll=0
.
Configuring UARTs
Edit this on GitHub
There are two types of UART available on the Raspberry Pi - PL011 and mini UART. The PL011 is a capable, broadly 16550-compatible UART, while the mini UART has a reduced feature set.
All UARTs on the Raspberry Pi are 3.3V only - damage will occur if they are connected to 5V systems. An adaptor can be used to connect to 5V systems. Alternatively, low-cost USB to 3.3V serial adaptors are available from various third parties.
Raspberry Pi Zero, 1, 2 and 3
The Raspberry Pi Zero, 1, 2, and 3 each contain two UARTs as follows:
Name | Type |
---|---|
UART0 |
PL011 |
UART1 |
mini UART |
Raspberry Pi 4 and 400
The Raspberry Pi 4B and 400 have an additional four PL011s, which are disabled by default:
Name | Type |
---|---|
UART0 |
PL011 |
UART1 |
mini UART |
UART2 |
PL011 |
UART3 |
PL011 |
UART4 |
PL011 |
UART5 |
PL011 |
CM1, CM3, CM3+ and CM4
The first generation Compute Module, together with Compute Module 3 and Compute Module 3+ each have two UARTs, while Compute Module 4 has six UARTs as described above.
On all models of Compute Module, the UARTs are disabled by default and can be explicitly enabled using a device tree overlay. You may also specify which GPIO pins to use, for example:
dtoverlay=uart1,txd1_pin=32,rxd1_pin=33
Primary UART
On the Raspberry Pi, one UART is selected to be present on GPIO 14 (transmit) and 15 (receive) - this is the primary UART. By default, this will also be the UART on which a Linux console may be present. Note that GPIO 14 is pin 8 on the GPIO header, while GPIO 15 is pin 10.
Secondary UART
The secondary UART is not normally present on the GPIO connector. By default, the secondary UART is connected to the Bluetooth side of the combined wireless LAN/Bluetooth controller, on models which contain this controller.
Primary and Secondary UART
The following table summarises the assignment of the first two UARTs:
Model | first PL011 (UART0) | mini UART |
---|---|---|
Raspberry Pi Zero |
primary |
secondary |
Raspberry Pi Zero W / Raspberry Pi Zero 2 W |
secondary (Bluetooth) |
primary |
Raspberry Pi 1 |
primary |
secondary |
Raspberry Pi 2 |
primary |
secondary |
Raspberry Pi 3 |
secondary (Bluetooth) |
primary |
Compute Module 3 & 3+ |
primary |
secondary |
Raspberry Pi 4 |
secondary (Bluetooth) |
primary |
Note
|
The mini UART is disabled by default, whether it is designated primary or secondary UART. |
Linux devices on Raspberry Pi OS:
Linux device | Description |
---|---|
|
mini UART |
|
first PL011 (UART0) |
|
primary UART |
|
secondary UART |
Note
|
/dev/serial0 and /dev/serial1 are symbolic links which point to either /dev/ttyS0 or /dev/ttyAMA0 .
|
Mini-UART and CPU Core Frequency
In order to use the mini UART, you need to configure the Raspberry Pi to use a fixed VPU core clock frequency. This is because the mini UART clock is linked to the VPU core clock, so that when the core clock frequency changes, the UART baud rate will also change. The enable_uart
and core_freq
settings can be added to config.txt
to change the behaviour of the mini UART. The following table summarises the possible combinations:
Mini UART set to | core clock | Result |
---|---|---|
primary UART |
variable |
mini UART disabled |
primary UART |
fixed by setting |
mini UART enabled, core clock fixed to 250MHz, or if |
secondary UART |
variable |
mini UART disabled |
secondary UART |
fixed by setting |
mini UART enabled |
The default state of the enable_uart
flag depends on which UART is the primary UART:
Primary UART | Default state of enable_uart flag |
---|---|
mini UART |
0 |
first PL011 (UART0) |
1 |
Disabling the Linux Serial Console
By default, the primary UART is assigned to the Linux console. If you wish to use the primary UART for other purposes, you must reconfigure Raspberry Pi OS. This can be done by using raspi-config:
-
Start raspi-config:
sudo raspi-config
. -
Select option 3 - Interface Options.
-
Select option P6 - Serial Port.
-
At the prompt
Would you like a login shell to be accessible over serial?
answer 'No' -
At the prompt
Would you like the serial port hardware to be enabled?
answer 'Yes' -
Exit raspi-config and reboot the Raspberry Pi for changes to take effect.
Enabling Early Console for Linux
Although the Linux kernel starts the UARTs relatively early in the boot process, it is still long after some critical bits of infrastructure have been set up. A failure in those early stages can be hard to diagnose without access to the kernel log messages from that time. To enable earlycon
support for one of the UARTs, add one of the following options to cmdline.txt
, depending on which UART is the primary:
For Raspberry Pi 4, 400 and Compute Module 4:
earlycon=uart8250,mmio32,0xfe215040 earlycon=pl011,mmio32,0xfe201000
For Raspberry Pi 2, Pi 3 and Compute Module 3:
earlycon=uart8250,mmio32,0x3f215040 earlycon=pl011,mmio32,0x3f201000
For Raspberry Pi 1, Pi Zero and Compute Module 1:
earlycon=uart8250,mmio32,0x20215040 earlycon=pl011,mmio32,0x20201000
The baudrate defaults to 115200bps.
Note
|
Selecting the wrong early console can prevent the Raspberry Pi from booting. |
UARTs and Device Tree
Various UART Device Tree overlay definitions can be found in the kernel GitHub tree. The two most useful overlays are disable-bt
and miniuart-bt
.
disable-bt
disables the Bluetooth device and makes the first PL011 (UART0) the primary UART. You must also disable the system service that initialises the modem, so it does not connect to the UART, using sudo systemctl disable hciuart
.
miniuart-bt
switches the Bluetooth function to use the mini UART, and makes the first PL011 (UART0) the primary UART. Note that this may reduce the maximum usable baud rate (see mini UART limitations below). You must also set the VPU core clock to a fixed frequency using either force_turbo=1
or core_freq=250
.
The overlays uart2
, uart3
, uart4
, and uart5
are used to enable the four additional UARTs on the Raspberry Pi 4. There are other UART-specific overlays in the folder. Refer to /boot/overlays/README
for details on Device Tree overlays, or run dtoverlay -h overlay-name
for descriptions and usage information.
You add a line to the config.txt
file to apply a Device Tree overlay. Note that the -overlay.dts
part of the filename is removed. For example:
dtoverlay=disable-bt
PL011 and mini-UART
There are some differences between PL011 UARTs and mini-UART.
The mini-UART has smaller FIFOs. Combined with the lack of flow control, this makes it more prone to losing characters at higher baudrates. It is also generally less capable than a PL011, mainly due to its baud rate link to the VPU clock speed.
The particular deficiencies of the mini UART compared to a PL011 are :
-
No break detection
-
No framing errors detection
-
No parity bit
-
No receive timeout interrupt
Neither the mini UART nor the BCM2835 implementation of the PL011 have DCD, DSR, DTR or RI signals.
Further documentation on the mini UART can be found in the SoC peripherals document.
Firmware Warning Icons
Edit this on GitHub
Under certain circumstances, the Raspberry Pi firmware will display a warning icon on the display, to indicate an issue. There are currently three icons that can be displayed.
Undervoltage Warning
If the power supply to the Raspberry Pi drops below 4.63V (±5%), the following icon is displayed.
LED Warning Flash Codes
Edit this on GitHub
If a Raspberry Pi fails to boot for some reason, or has to shut down, in many cases an LED will be flashed a specific number of times to indicate what happened. The LED will blink for a number of long flashes (0 or more), then short flashes, to indicate the exact status. In most cases, the pattern will repeat after a 2 second gap.
Long flashes | Short flashes | Status |
---|---|---|
0 |
3 |
Generic failure to boot |
0 |
4 |
start*.elf not found |
0 |
7 |
Kernel image not found |
0 |
8 |
SDRAM failure |
0 |
9 |
Insufficient SDRAM |
0 |
10 |
In HALT state |
2 |
1 |
Partition not FAT |
2 |
2 |
Failed to read from partition |
2 |
3 |
Extended partition not FAT |
2 |
4 |
File signature/hash mismatch - Pi 4 |
3 |
1 |
SPI EEPROM error - Pi 4 |
3 |
2 |
SPI EEPROM is write protected - Pi 4 |
3 |
3 |
I2C error - Pi 4 |
3 |
4 |
Secure-boot configuration is not valid |
4 |
4 |
Unsupported board type |
4 |
5 |
Fatal firmware error |
4 |
6 |
Power failure type A |
4 |
7 |
Power failure type B |
Securing your Raspberry Pi
Edit this on GitHub
The security of your Raspberry Pi is important. Gaps in security leave your Raspberry Pi open to hackers who can then use it without your permission.
What level of security you need depends on how you wish to use your Raspberry Pi. For example, if you are simply using your Raspberry Pi on your home network, behind a router with a firewall, then it is already quite secure by default.
However, if you wish to expose your Raspberry Pi directly to the internet, either with a direct connection (unlikely) or by letting certain protocols through your router firewall (e.g. SSH), then you need to make some basic security changes.
Even if you are hidden behind a firewall, it is sensible to take security seriously. This documentation will describe some ways of improving the security of your Raspberry Pi. Please note, though, that it is not exhaustive.
Change the Default Password
The default username and password is used for every single Raspberry Pi running Raspberry Pi OS. So, if you can get access to a Raspberry Pi, and these settings have not been changed, you have root
access to that Raspberry Pi.
So the first thing to do is change the password. This can be done via the raspi-config
application, or from the command line.
sudo raspi-config
Select option 2, and follow the instructions to change the password.
However, all raspi-config
does is start up the command line passwd
application, which you can do from the command line. So instead you can type in your new password and confirm it.
passwd
Changing your Username
You can, of course, make your Raspberry Pi even more secure by also changing your username. All Raspberry Pis come with the default username pi
, so changing this will immediately make your Raspberry Pi more secure.
To add a new user, enter:
sudo adduser alice
You will be prompted to create a password for the new user.
The new user will have a home directory at /home/alice/
.
To add them to the sudo
group to give them sudo
permissions as well as all of the other necessary permissions:
sudo usermod -a -G adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,input,netdev,gpio,i2c,spi alice
You can check your permissions are in place (i.e. you can use sudo
) by trying the following:
sudo su - alice
If it runs successfully, then you can be sure that the new account is in the sudo
group.
Once you have confirmed that the new account is working, you can delete the pi
user. In order to do this, you’ll need to first change the autologin user to your new user alice
, with the following:
sudo raspi-config
Select option 1, S5 Boot / Auto login
, and say yes to reboot.
Please note that with the current Raspberry Pi OS distribution, there are some aspects that require the pi
user to be present. If you are unsure whether you will be affected by this, then leave the pi
user in place. Work is being done to reduce the dependency on the pi
user.
To delete the pi
user, type the following:
sudo deluser pi
This command will delete the pi
user but will leave the /home/pi
folder. If necessary, you can use the command below to remove the home folder for the pi
user at the same time. Note the data in this folder will be permanently deleted, so make sure any required data is stored elsewhere.
sudo deluser -remove-home pi
This command will result in a warning that the group pi
has no more members. The deluser
command removes both the pi
user and the pi
group though, so the warning can be safely ignored.
Make sudo
Require a Password
Placing sudo
in front of a command runs it as a superuser, and by default, that does not need a password. In general, this is not a problem. However, if your Raspberry Pi is exposed to the internet and somehow becomes exploited (perhaps via a webpage exploit for example), the attacker will be able to change things that require superuser credentials, unless you have set sudo
to require a password.
To force sudo
to require a password, enter:
sudo visudo /etc/sudoers.d/010_pi-nopasswd
and change the pi
entry (or whichever usernames have superuser rights) to:
pi ALL=(ALL) PASSWD: ALL
Then save the file: it will be checked for any syntax errors. If no errors were detected, the file will be saved and you will be returned to the shell prompt. If errors were detected, you will be asked 'what now?' Press the 'enter' key on your keyboard: this will bring up a list of options. You will probably want to use 'e' for '(e)dit sudoers file again', so you can edit the file and fix the problem.
Note
|
Choosing option 'Q' will save the file with any syntax errors still in place, which makes it impossible for any user to use the sudo command. |
Updating Raspberry Pi OS
An up-to-date distribution contains all the latest security fixes, so you should go ahead and update your version of Raspberry Pi OS to the latest version.
If you are using SSH to connect to your Raspberry Pi, it can be worthwhile to add a cron
job that specifically updates the ssh-server. The following command, perhaps as a daily cron job, will ensure you have the latest SSH security fixes promptly, independent of your normal update process.
apt install openssh-server
Improving SSH Security
SSH is a common way of accessing a Raspberry Pi remotely. By default, logging in with SSH requires a username/password pair, and there are ways to make this more secure. An even more secure method is to use key based authentication.
Improving username/password security
The most important thing to do is ensure you have a very robust password. If your Raspberry Pi is exposed to the internet, the password needs to be very secure. This will help to avoid dictionary attacks or the like.
You can also allow or deny specific users by altering the sshd
configuration.
sudo nano /etc/ssh/sshd_config
Add, edit, or append to the end of the file the following line, which contains the usernames you wish to allow to log in:
AllowUsers alice bob
You can also use DenyUsers
to specifically stop some usernames from logging in:
DenyUsers jane john
After the change you will need to restart the sshd
service using sudo systemctl restart ssh
or reboot so the changes take effect.
Using key-based authentication.
Key pairs are two cryptographically secure keys. One is private, and one is public. They can be used to authenticate a client to an SSH server (in this case the Raspberry Pi).
The client generates two keys, which are cryptographically linked to each other. The private key should never be released, but the public key can be freely shared. The SSH server takes a copy of the public key, and, when a link is requested, uses this key to send the client a challenge message, which the client will encrypt using the private key. If the server can use the public key to decrypt this message back to the original challenge message, then the identity of the client can be confirmed.
Generating a key pair in Linux is done using the ssh-keygen
command on the client; the keys are stored by default in the .ssh
folder in the user’s home directory. The private key will be called id_rsa
and the associated public key will be called id_rsa.pub
. The key will be 2048 bits long: breaking the encryption on a key of that length would take an extremely long time, so it is very secure. You can make longer keys if the situation demands it. Note that you should only do the generation process once: if repeated, it will overwrite any previous generated keys. Anything relying on those old keys will need to be updated to the new keys.
You will be prompted for a passphrase during key generation: this is an extra level of security. For the moment, leave this blank.
The public key now needs to be moved on to the server: see Copy your public key to your Raspberry Pi.
Finally, we need to disable password logins, so that all authentication is done by the key pairs.
sudo nano /etc/ssh/sshd_config
There are three lines that need to be changed to no
, if they are not set that way already:
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
Save the file and either restart the ssh system with sudo service ssh reload
or reboot.
Install a Firewall
There are many firewall solutions available for Linux. Most use the underlying iptables project to provide packet filtering. This project sits over the Linux netfiltering system. iptables
is installed by default on Raspberry Pi OS, but is not set up. Setting it up can be a complicated task, and one project that provides a simpler interface than iptables
is ufw, which stands for 'Uncomplicated Fire Wall'. This is the default firewall tool in Ubuntu, and can be easily installed on your Raspberry Pi:
sudo apt install ufw
ufw
is a fairly straightforward command line tool, although there are some GUIs available for it. This document will describe a few of the basic command line options. Note that ufw
needs to be run with superuser privileges, so all commands are preceded with sudo
. It is also possible to use the option --dry-run
any ufw
commands, which indicates the results of the command without actually making any changes.
To enable the firewall, which will also ensure it starts up on boot, use:
sudo ufw enable
To disable the firewall, and disable start up on boot, use:
sudo ufw disable
Allow a particular port to have access (we have used port 22 in our example):
sudo ufw allow 22
Denying access on a port is also very simple (again, we have used port 22 as an example):
sudo ufw deny 22
You can also specify which service you are allowing or denying on a port. In this example, we are denying tcp on port 22:
sudo ufw deny 22/tcp
You can specify the service even if you do not know which port it uses. This example allows the ssh service access through the firewall:
sudo ufw allow ssh
The status command lists all current settings for the firewall:
sudo ufw status
The rules can be quite complicated, allowing specific IP addresses to be blocked, specifying in which direction traffic is allowed, or limiting the number of attempts to connect, for example to help defeat a Denial of Service (DoS) attack. You can also specify the device rules are to be applied to (e.g. eth0, wlan0). Please refer to the ufw
man page (man ufw
) for full details, but here are some examples of more sophisticated commands.
Limit login attempts on ssh port using tcp: this denies connection if an IP address has attempted to connect six or more times in the last 30 seconds:
sudo ufw limit ssh/tcp
Deny access to port 30 from IP address 192.168.2.1
sudo ufw deny from 192.168.2.1 port 30
Installing fail2ban
If you are using your Raspberry Pi as some sort of server, for example an ssh
or a webserver, your firewall will have deliberate 'holes' in it to let the server traffic through. In these cases, Fail2ban can be useful. Fail2ban, written in Python, is a scanner that examines the log files produced by the Raspberry Pi, and checks them for suspicious activity. It catches things like multiple brute-force attempts to log in, and can inform any installed firewall to stop further login attempts from suspicious IP addresses. It saves you having to manually check log files for intrusion attempts and then update the firewall (via iptables
) to prevent them.
Install fail2ban
using the following command:
sudo apt install fail2ban
On installation, Fail2ban creates a folder /etc/fail2ban
in which there is a configuration file called jail.conf
. This needs to be copied to jail.local
to enable it. Inside this configuration file are a set of default options, together with options for checking specific services for abnormalities. Do the following to examine/change the rules that are used for ssh
:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
Add the following section to the jail.local
file. On some versions of fail2ban this section may already exist, so update this pre-existing section if it is there.
[ssh] enabled = true port = ssh filter = sshd logpath = /var/log/auth.log maxretry = 6
As you can see, this section is named ssh, is enabled, examines the ssh port, filters using the sshd
parameters, parses the /var/log/auth.log
for malicious activity, and allows six retries before the detection threshold is reached. Checking the default section, we can see that the default banning action is:
# Default banning action (e.g. 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
iptables-multiport
means that the Fail2ban system will run the /etc/fail2ban/action.d/iptables-multiport.conf
file when the detection threshold is reached. There are a number of different action configuration files that can be used. Multiport bans all access on all ports.
If you want to permanently ban an IP address after three failed attempts, you can change the maxretry value in the [ssh]
section, and set the bantime to a negative number:
[ssh] enabled = true port = ssh filter = sshd logpath = /var/log/auth.log maxretry = 3 bantime = -1
Configuring Screen Blanking
Edit this on GitHub
You can configure your Raspberry Pi to use a screen saver or to blank the screen.
On Console
When running without a graphical desktop, Raspberry Pi OS will blank the screen after 10 minutes without user input, e.g. mouse movement or key presses.
The current setting, in seconds, can be displayed using:
cat /sys/module/kernel/parameters/consoleblank
To change the consoleblank
setting, edit the kernel command line:
sudo nano /boot/cmdline.txt
The file /boot/cmdline.txt
contains a single line of text. Add consoleblank=n
to have the console blank after n
seconds of inactivity. For example consoleblank=300
will cause the console to blank after 300 seconds, 5 minutes, of inactivity. Make sure that you add your consoleblank
option to the single line of text already in the cmdline.txt
file. To disable screen blanking, set consoleblank=0
.
You can also use the raspi-config
tool to disable screen blanking. Note that the screen blanking setting in raspi-config
also controls screen blanking when the graphical desktop is running.
On the Desktop
Raspberry Pi OS will blank the graphical desktop after 10 minutes without user input. You can disable this by changing the 'Screen Blanking' option in the Raspberry Pi Configuration tool, which is available on the Preferences menu. Note that the 'Screen Blanking' option also controls screen blanking when the graphical desktop is not running.
There is also a graphical screensaver available, which can be installed as follows:
sudo apt install xscreensaver
This may take a few minutes.
Once this has been installed, you can find the Screensaver application on the Preferences menu: it provides many options for setting up the screensaver, including disabling it completely.
Switching off HDMI
If you want to switch off the video display entirely, you can use the vcgencmd command,
vcgencmd display_power 0
Video will not come back on until you reboot or switch it back on:
vcgencmd display_power 1
The boot
Folder
Edit this on GitHub
In a basic Raspberry Pi OS install, the boot files are stored on the first partition of the SD card, which is formatted with the FAT file system. This means that it can be read on Windows, macOS, and Linux devices.
When the Raspberry Pi is powered on, it loads various files from the boot partition/folder in order to start up the various processors, then it boots the Linux kernel.
Once Linux has booted, the boot partition is mounted as /boot
.
Boot Folder Contents
bootcode.bin
This is the bootloader, which is loaded by the SoC on boot, does some very basic setup, and then loads one of the start*.elf
files. bootcode.bin
is not used on the Raspberry Pi 4, because it has been replaced by boot code in the onboard EEPROM.
start.elf, start_x.elf, start_db.elf, start_cd.elf, start4.elf, start4x.elf, start4db.elf, start4cd.elf
These are binary blobs (firmware) that are loaded on to the VideoCore GPU in the SoC, which then take over the boot process.
start.elf
is the basic firmware, start_x.elf
also includes camera drivers and codecs, start_db.elf
can be used for debugging purposes and start_cd.elf
is a cut-down version of the firmware. start_cd.elf
removes support for hardware blocks such as cameras, codecs and 3D as well as having initial framebuffer limitations. The cut-down firmware is automatically used when gpu_mem=16
is specified in config.txt
.
start4.elf
, start4x.elf
, start4db.elf
and start4cd.elf
are equivalent firmware files specific to the Raspberry Pi 4-series (Model 4B, Pi 400, Compute Module 4 and Compute Module 4S).
More information on how to use these files can be found in the config.txt
section.
fixup*.dat
These are linker files and are matched pairs with the start*.elf
files listed in the previous section.
config.txt
Contains many configuration parameters for setting up the Raspberry Pi. See the config.txt
section.
issue.txt
Some text-based housekeeping information containing the date and git commit ID of the distribution.
ssh or ssh.txt
When this file is present, SSH will be enabled on boot. The contents don’t matter, it can be empty. SSH is otherwise disabled by default.
wpa_supplicant.conf
This is the file to configure wireless network settings (if the hardware is capable of it). Edit the country code and the network part to fit your case. More information on how to use this file can be found in the wireless/headless
section.
Device Tree files
There are various Device Tree blob files, which have the extension .dtb
. These contain the hardware definitions of the various models of Raspberry Pi, and are used on boot to set up the kernel according to which Raspberry Pi model is detected.
Kernel Files
The boot folder will contain various kernel image files, used for the different Raspberry Pi models:
Filename | Processor | Raspberry Pi model | Notes |
---|---|---|---|
kernel.img |
BCM2835 |
Pi Zero, Pi 1 |
|
kernel7.img |
BCM2836, BCM2837 |
Pi Zero 2 W, Pi 2, Pi 3 |
Later Pi 2 uses the BCM2837 |
kernel7l.img |
BCM2711 |
Pi 4, Pi 400 |
Large Physical Address Extension (LPAE) |
kernel8.img |
BCM2837, BCM2711 |
Pi Zero 2 W, Pi 2, Pi 3, Pi 4, Pi 400 |
64-bit kernel. Raspberry Pi 2 with BCM2836 does not support 64-bit kernels. |
Note
|
The architecture reported by lscpu is armv7l for systems running a 32-bit kernel (i.e. everything except kernel8.img ), and aarch64 for systems running a 64-bit kernel. The l in the armv7l case refers to the architecture being little-endian, not LPAE as is indicated by the l in the kernel7l.img filename.
|
The Overlays Folder
The overlays
sub-folder contains Device Tree overlays. These are used to configure various hardware devices that may be attached to the system, for example the Raspberry Pi Touch Display or third-party sound boards. These overlays are selected using entries in config.txt
— see 'Device Trees, overlays and parameters, part 2' for more info.