我正在模仿Linux源代码中的gpio-hammer示例。我正在使用Raspberry Pi 3B +,希望LED闪烁。
这就是我要做的:
#include <linux/gpio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
int main(int argc, const char **argv) {
int fd, ret;
struct gpiohandle_request req;
struct gpiohandle_data data;
char *gpio_dev_name = "/dev/gpiochip0";
unsigned int gpio_line = 8;
memset(&data.values, 0, sizeof(data.values));
// open device
fd = open(gpio_dev_name, 0);
if (fd == -1) {
fprintf(stderr, "Failed to open %s, %s\n",
gpio_dev_name, strerror(errno));
}
// request gpio output
req.lineoffsets[0] = gpio_line;
req.flags = GPIOHANDLE_REQUEST_OUTPUT | GPIOHANDLE_REQUEST_ACTIVE_LOW;
strcpy(req.consumer_label, "blink");
req.lines = 1;
memcpy(req.default_values, &data, sizeof(req.default_values));
ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
if (ret == -1) {
fprintf(stderr, "Failed to issue %s (%d), %s\n",
"GPIO_GET_LINEHANDLE_IOCTL", ret, strerror(errno));
}
// blink
while (1) {
// read data
ret = ioctl(fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);
if (ret == -1) {
ret = -errno;
fprintf(stderr, "Failed to issue %s (%d), %s\n",
"GPIOHANDLE_GET_LINE_VALUES_IOCTL", ret, strerror(errno));
exit(ret);
}
// flip digits
data.values[0] = !data.values[0];
// set data
ret = ioctl(fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
if (ret == -1) {
ret = -errno;
fprintf(stderr, "Failed to issue %s (%d), %s\n",
"GPIOHANDLE_SET_LINE_VALUES_IOCTL", ret, strerror(errno));
exit(ret);
}
// delay
sleep(1);
}
}
我可以在RPi上编译gpio-hammer示例,并使用./gpio-hammer -n gpiochip0 -o 8
运行它。连接到gpiochip0 line8的LED指示灯闪烁。
但是我的程序不起作用。失败
Failed to issue GPIOHANDLE_GET_LINE_VALUES_IOCTL (-22), Invalid argument
我研究了gpiolib的实现。如果ioctl cmd不是ioctl
也不是EINVAL (22)
,则gpio线句柄的GPIOHANDLE_GET_LINE_VALUES_IOCTL
返回GPIOHANDLE_SET_LINE_VALUES_IOCTL
。但是事实并非如此。怎么了?
答案 0 :(得分:1)
在linux/gpio.h
的{{1}}中,article说:
struct gpiohandle_request
使用/*
* ...
* @fd: if successful this field will contain a valid anonymous file handle
* after a GPIO_GET_LINEHANDLE_IOCTL operation, zero or negative value
* means error
*/
struct gpiohandle_request {
__u32 lineoffsets[GPIOHANDLES_MAX];
__u32 flags;
__u8 default_values[GPIOHANDLES_MAX];
char consumer_label[32];
__u32 lines;
int fd;
};
时, GPIO芯片设备的文件句柄通过GPIO_GET_LINEHANDLE_IOCTL
的第一个参数传递,而另一个文件句柄将如果操作成功,将在ioctl()
中发回。新的gpiohandle_request::fd
应该在fd
或ioctl
的{{1}}中使用。
所以代码应该是
GPIO_GET_LINE_VALUES_IOCTL