解决Raspberry PI Zero W中Lua使用lua-periphery与Python中设置的GPIO端口不一致的问题

栏目: Python · 发布时间: 5年前

内容简介:在当时选择为了应对这种情况,可以用如下的代码进行端口的重新映射,解决上述问题:

树莓派实时系统下脚本语言的选择(应当使用 Lua 而不是Python) 中,我们没有使用 rpi-gpio ,而是使用了 lua-periphery 来解决 Lua 语言下操作树莓派 GPIO 的问题。

当时选择 lua-periphery 的原因在于 rpi-gpioRaspberry PI Zero W 中使用的时候会崩溃。这个原因是在于 cpuinfo.c 这个文件中缺少对于 BCM2835 这颗新的 CPU 的判断,只判断了 BCM2708 估计写这个库的时候,只有 BCM2708 )。导致 RPi_GPIO_Lua_module.c 在初始化 GPIO 的时候抛出了异常。这个已经有人提交了代码合并请求,估计很快会修复。

但是在 lua-periphery 中,没有对于 GPIO 进行重新映射,导致跟 rpi-gpio 以及树莓派自带的 Python 库在设置 GPIO 的时候,端口号对应不一致。比如,在 Python 中设置 GPIO 22 ,执行命令观察 ls /sys/class/gpio/ ,会发现系统创建的是 GPIO 25 这个对应关系就是通过查表获取的。如下图:

解决Raspberry PI Zero W中Lua使用lua-periphery与 <a href='https://www.codercto.com/topics/20097.html'>Python</a> 中设置的GPIO端口不一致的问题

为了应对这种情况,可以用如下的代码进行端口的重新映射,解决上述问题:

function rpi_gpio_map(pin)
  local pin_to_gpio_rev1 = {-1, -1, -1, 0, -1, 1, -1, 4, 14, -1, 15, 17, 18, 21, -1, 22, 23, -1, 24, 10, -1, 9, 25, 11, 8, -1, 7}
  local pin_to_gpio_rev2 = {-1, -1, -1, 2, -1, 3, -1, 4, 14, -1, 15, 17, 18, 27, -1, 22, 23, -1, 24, 10, -1, 9, 25, 11, 8, -1, 7}
 
  -- check gpio rev
  local revision = ""
  local rpi_found = false
  for line in io.lines("/proc/cpuinfo") do
    line = string.lower(line)
    local idx = string.find(line , "hardware%s:%s")
    if idx ~= nil then
      line = string.sub(line,idx)
      idx = string.find(line , "bcm2708")
      if idx == nil then
        idx = string.find(line , "bcm2835")
      end
      if idx ~= nil then
        rpi_found = true
      end
    end
    idx = string.find(line , "revision%s:%s")
    if idx ~= nil then
      revision =  string.sub(line,idx)
    end
  end
  if rpi_found == false then
    revision = ""
  end
  if revision == "0002" or revision == "1000002" or revision == "003" or revision == "1000003" then 
    return pin_to_gpio_rev1[pin+1]
  else
    return pin_to_gpio_rev2[pin+1]
  end		
end

上述代码参考 RPi_GPIO_Lua_module.c 中的逻辑,简单调整而来。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithms in Java

Data Structures and Algorithms in Java

Michael T. Goodrich、Roberto Tamassia / Wiley / 2010-01-26 / USD 177.41

* This newest edition examines fundamental data structures by following a consistent object-oriented framework that builds intuition and analysis skills of data structures and algorithms * Presents ne......一起来看看 《Data Structures and Algorithms in Java》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

随机密码生成器
随机密码生成器

多种字符组合密码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具