英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论