如何在嵌入式 Linux 系统上使用 Golang 管理输入/输出(I/O)?

huangapple go评论67阅读模式
英文:

How to manage I/Os with Golang on linux embedded system?

问题

我有一个嵌入式Linux系统。我可以使用shell命令来管理输入/输出(I/O)。这些命令可以改变GPIO #48的状态:

/sys/class/gpio# echo 48 > /sys/class/gpio/export
/sys/class/gpio# echo out > /sys/class/gpio/gpio48/direction
/sys/class/gpio# echo high > /sys/class/gpio/gpio48/direction
/sys/class/gpio# echo low > /sys/class/gpio/gpio48/direction

如何在Goland中高效地管理I/O?是否可以不通过shell命令来管理它们?

英文:

I have an linux embedded system. I can manage I/Os with shell commands. This commands change out status of GPIO #48 :

/sys/class/gpio# echo 48 > /sys/class/gpio/export
/sys/class/gpio# echo out > /sys/class/gpio/gpio48/direction
/sys/class/gpio# echo high > /sys/class/gpio/gpio48/direction
/sys/class/gpio# echo low > /sys/class/gpio/gpio48/direction

How can I manage I/Os with Goland efficiently ? Is it possible to manage them without going through the shell commands ?

答案1

得分: 5

在Linux上,GPIO接口通过sys文件系统在/sys/class/gpio层次结构中导出,所以在你的shell示例中,你只需要将数据写入这些文件,类似于:

// 导出引脚48(相当于 echo 48 > /sys/class/gpio/export)
ioutil.WriteFile("/sys/class/gpio/export", []byte("48"), 0666)
...

根据你的平台和需求,你可能想考虑一些现有的包(例如树莓派的go-rpio或更通用且支持更多功能的periph)。

如果你想要比写入sysfs文件更高效/更快的解决方案,你还可以考虑使用内存映射GPIO访问,这样你基本上可以通过内核给定的内存范围直接访问GPIO外设。这需要对目标平台有一定的了解(了解其GPIO寄存器及其映射)。你可以在这篇博文中详细了解这种方法。

编辑:正如@0andriy在他的评论中指出的那样,gpio sysfs已经被弃用。这适用于你上面的Bash示例和我在Go中执行相同操作的答案。取而代之的是引入了新的ABI和libgpiod来与其交互。Go的端口在这里可用:https://github.com/warthog618/gpiod。

英文:

On Linux GPIO interface is exported via sys filesystem in /sys/class/gpio hierarchy so as in your shell example you just need to write data into these files, something like:

// To export pin 48 (same as echo 48 > /sys/class/gpio/export)
ioutil.WriteFile("/sys/class/gpio/export", []byte("48"), 0666)
...

Depending on your platform and needs you may want to consider some pre-existing package (e.g. go-rpio for Raspberry Pi or periph which is more general and supports much more than GPIO).

If you want more efficient/faster solution than writing sysfs files you might also consider memory-mapped GPIO access where you basically directly access GPIO periphery via memory range given to it by the kernel. This requires somewhat deeper knowledge of your target platform (understanding its GPIO registers and their mapping). You can read about that approach in detail in this blogpost.

EDIT: As @0andriy pointed out in his comment gpio syssfs is deprecated. That applies for both your Bash example above and my answer how to do same thing in Go. Instead a new ABI was introduced and libgpiod to interact with it. Go port is available here https://github.com/warthog618/gpiod.

huangapple
  • 本文由 发表于 2021年9月15日 16:05:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/69189262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定