【发布时间】:2018-04-25 17:11:31
【问题描述】:
我曾经使用 /sys/class/gpio 在用户空间处理 gpio。问题是我需要在内核驱动程序中使用这个 gpio。由于内核驱动的gpio请求,我无法通过/sys/class/gpio操作这个gpio。
但是,在将我的 gpio 声明为设备树中的 gpio 键之后,我能够通过 /dev/input/eventX 使用它。问题是我只能使用此界面(新状态)获取事件,但不能获取初始事件。所以在第一个事件之前,我无法知道我的 gpio 的当前状态。
我试图寻找解决方案 /sys/class/input/eventX 和 /sys/class/input/inputX 没有成功。
更完整的问题在这里:https://www.mail-archive.com/kernelnewbies@kernelnewbies.org/msg18588.html
我使用的当前肮脏的解决方法:Char device + ioctl
diff --git a/drivers/input/keyboard/gpio_keys.c b/drivers/input/keyboard/gpio_keys.c
index 77d7b07..99df807 100644
--- a/drivers/input/keyboard/gpio_keys.c
+++ b/drivers/input/keyboard/gpio_keys.c
@@ -31,6 +31,16 @@
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/spinlock.h>
+#include <linux/cdev.h>
+#include <linux/uaccess.h>
+
+struct keys_dev {
+ struct cdev dev;
+ dev_t dev_no;
+ struct class *cl;
+};
+
+static struct keys_dev keys_inst;
struct gpio_button_data {
const struct gpio_keys_button *button;
@@ -55,6 +65,27 @@ struct gpio_keys_drvdata {
struct gpio_button_data data[0];
};
+
+#define KEYS_DEVICE_NAME "plug_status"
+#define GPIO_USB 1
+
+static long gpio_keys_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
+{
+ int value = -1;
+ int err;
+
+ value = gpio_get_value (GPIO_USB);
+ value = !value;
+ err = copy_to_user((char*)arg, &value, sizeof(int));
+ return value;
+}
+
+static const struct file_operations gpio_keys_fops = {
+ .owner = THIS_MODULE,
+ .unlocked_ioctl = gpio_keys_ioctl,
+};
+
+
/*
* SYSFS interface for enabling/disabling keys and switches:
*
@@ -851,11 +882,40 @@ static struct platform_driver gpio_keys_device_driver = {
static int __init gpio_keys_init(void)
{
+ int r;
+
+ r = alloc_chrdev_region(&keys_inst.dev_no , 0, 1, KEYS_DEVICE_NAME);
+ if (r < 0) {
+ printk(KERN_ERR "alloc_chrdev_region failed!\n");
+ return -ENOMEM;
+ }
+ keys_inst.cl = class_create(THIS_MODULE, KEYS_DEVICE_NAME);
+ if (keys_inst.cl == NULL) {
+ printk(KERN_ERR "Could not create class!\n");
+ return -ENOMEM;
+ }
+
+ if (device_create(keys_inst.cl, NULL, keys_inst.dev_no, NULL, KEYS_DEVICE_NAME) == NULL) {
+ printk(KERN_ERR "Could not create character device!\n");
+ return -ENOMEM;
+ }
+
+ cdev_init(&keys_inst.dev, &gpio_keys_fops );
+ r = cdev_add(&keys_inst.dev, keys_inst.dev_no, 1);
+ if (r < 0) {
+ printk(KERN_ERR "Could not add character device!\n");
+ return -ENOMEM;
+ }
+
return platform_driver_register(&gpio_keys_device_driver);
}
static void __exit gpio_keys_exit(void)
{
+
+ device_destroy(keys_inst.cl, keys_inst.dev_no);
+ class_destroy(keys_inst.cl);
+ unregister_chrdev_region(keys_inst.dev_no, 1);
platform_driver_unregister(&gpio_keys_device_driver);
}
【问题讨论】:
-
这不是对导出功能进行操作的错误或错误。这是完全正常的。这只是因为内核已经请求了 gpio est。我不能使用 /sys/class/gpio。
标签: c linux arm gpio device-tree