nRF24L01 无线模块使用
本文档简要介绍如何在树莓派 5 上连接并使用 2.4GHz 的 nRF24L01 无线模块。
硬件连接
nRF24L01 通过 SPI 接口与树莓派通信,推荐的引脚连接如下表所示:
nRF24L01 引脚 | Raspberry Pi 引脚 |
---|---|
VCC | 3.3V (Pin 1) |
GND | GND (Pin 6) |
CE | GPIO22 (Pin 15) |
CSN | GPIO8 (Pin 24) |
SCK | GPIO11 (Pin 23) |
MOSI | GPIO10 (Pin 19) |
MISO | GPIO9 (Pin 21) |
IRQ | 可不连接 |
将模块供电接 3.3V,不要 连接到 5V,以免损坏芯片。
启用 SPI 接口
在终端执行 sudo raspi-config
,在 Interface Options 中启用 SPI。重启后即可在 /dev/spidev0.*
查看到设备节点。
安装 Python 库
可以使用 python3-pip
安装社区维护的 pynrf24
库(或其他兼容库):
sudo apt update
sudo apt install python3-pip
pip3 install pynrf24
示例代码
下面的示例展示如何发送简单的字符串数据:
from pynrf24 import NRF24
import spidev
import time
pipes = [[0xe7,0xe7,0xe7,0xe7,0xe7], [0xc2,0xc2,0xc2,0xc2,0xc2]]
radio = NRF24()
radio.begin(0, 0) # 使用 CE0, CSN0
radio.setPayloadSize(32)
radio.setChannel(76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)
radio.setAutoAck(True)
radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])
while True:
message = list(b"hello")
radio.write(message)
print("Sent: hello")
time.sleep(1)
另一台树莓派或 Arduino 上配置相同地址即可接收数据。更多高级用法请参考库文档。
更多脚本与演示可在 pi5-nrf24l01-tools 仓库中找到。