通过 sysfs 编写用户态 GPIO LED 驱动程序
不写内核模块,仅通过 sysfs 接口和 udev 规则,创建可被普通用户控制的 GPIO LED 设备。 · 难度:入门 · +10XP
通过 sysfs 编写用户态 GPIO LED 驱动程序
虽然内核 GPIO 子系统有标准接口,但本教程演示一种更底层的玩法:直接操作 /sys/class/gpio 导出 GPIO 引脚,然后用 C 程序定时翻转电平实现呼吸灯效果。同时编写 udev 规则固定设备权限与符号链接,配合 systemd 服务实现开机自启,完全在用户空间完成设备驱动功能。
int gpio_export(unsigned pin) {
int fd = open("/sys/class/gpio/export", O_WRONLY);
char buf[4]; snprintf(buf, sizeof(buf), "%u", pin);
write(fd, buf, strlen(buf)); close(fd);
}
void gpio_write(unsigned pin, int val) {
char path[64];
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%u/value", pin);
int fd = open(path, O_WRONLY);
write(fd, val ? "1" : "0", 1); close(fd);
}