解决 ws281x LED 驱动在新版本树莓派上不兼容的问题,


之前遇到一个奇葩问题,同样的程序,同样都是树莓派4B,老版本(4G V1.4)可以运行,新版本(4G V1.5)却提示 module 'board' has no sttribute 'D21'
经过排查,发现是使用了 Adafruit 的 ws281x 灯带驱动库存在问题。他们会检查树莓派的具体型号,如果库里面没有定义,则直接影响运行。这里涉及到下面两个库。

1、Adafruit_Python_PlatformDetect
2、Adafruit_Blinka

当然,也有另一种驱动 ws281x 灯带的方法,可以不用上面两个库,而是直接使用 rpi_ws281x 库,但是也同样会存在版本不识别的问题。
如果你是直接调用 rpi_ws281x 驱动灯条,可以跳过对 Adafruit 库的升级,直接拉到文末参考 rpi_ws281x 的修改步骤。

修改 Adafruit 库

Adafruit_Python_PlatformDetect、Adafruit_Blinka 这两个库都内置了开发板识别程序,如果识别到的开发板型号和库里面写死的型号不匹配就会提示「硬件不支持」。

1、卸载之前的库,重新装最新的库。

sudo pip3 uninstall adafruit_platformdetect
sudo pip3 uninstall Adafruit_Blinka
sudo pip3 uninstall adafruit-circuitpython-neopixel
sudo pip3 install adafruit_platformdetect
sudo pip3 install Adafruit_Blinka
sudo pip3 install adafruit-circuitpython-neopixel

2、确认自己的树莓派型号,方法参考这里:
https://shumeipai.nxez.com/raspberry-pi-revision-codes

Revision 后面所显示的代号就是了。以笔者的树莓派 4B 4G v1.5 为例,版本代号是 c03115

3、新装了之后还要手动修改库的代码。位置如下(根据你安装的 Python 版本,路径会有所不同):

/usr/local/lib/python3.9/dist-packages/adafruit_platformdetect/constants/boards.py

这个文件中添加相应的树莓派型号,加到哪里可以参考他原先定义的格式。

修改 rpi_ws281x 库

做完上面的还不够,因为 Adafruit 的库是依赖 rpi_ws281x 库的。rpi_ws281x 这个模块也是把支持的设备写死了,不认识新版树莓派。
这个库是 C 语言写的,需要重新编译安装这个库。源码在这里:
https://github.com/jgarff/rpi_ws281x
需要修改的文件是:
https://github.com/jgarff/rpi_ws281x/blob/master/rpihw.c
加入我们的新型号。

    {
        .hwver = 0xc03115,
        .type = RPI_HWVER_TYPE_PI4,
        .periph_base = PERIPH_BASE_RPI4,
        .videocore_base = VIDEOCORE_BASE_RPI2,
        .desc = "Pi 4 Model B - 4GB v1.5"
    },

如何编译安装,参考这个 readme 文件。
https://github.com/jgarff/rpi_ws281x

用到的编译工具 CMake 如何安装可以参考这个教程:
https://shumeipai.nxez.com/2022/04/12/install-cmake-on-raspberry-pi.html

准备就绪之后,开始下载源码并编译安装:

sudo pip3 uninstall rpi_ws281x
git clone --recurse-submodules https://github.com/rpi-ws281x/rpi-ws281x-python
vim rpi-ws281x-python/library/lib/rpihw.c
make the changes needed
cd rpi-ws281x-python/library/
sudo python3 setup.py install

一切顺利的话,问题就解决了!

文章标题:解决 ws281x LED 驱动在新版本树莓派上不兼容的问题 - 树莓派实验室 固定链接:https://shumeipai.nxez.com/2022/05/11/the-solution-to-the-ws281x-led-strip-problem-caused-by-the-raspberry-pi-version.html

相关内容