项目:字符设备驱动 - LED 与按键

嵌入式入门经典项目:编写一个字符设备驱动,控制 LED 并读取按键状态。

一、目标

二、设备树

mygpio {
    compatible = "myvendor,mygpio";
    led-gpios = <&gpio1 5 GPIO_ACTIVE_HIGH>;
    key-gpios = <&gpio1 6 GPIO_ACTIVE_LOW>;
};

三、驱动代码

// drivers/char/mygpio.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/gpio/consumer.h>
#include <linux/of.h>

#define DEV_NAME "mygpio"

static dev_t devno;
static struct cdev my_cdev;
static struct class *my_class;

struct mygpio_priv {
    struct gpio_desc *led;
    struct gpio_desc *key;
};

static struct mygpio_priv priv;

static int mygpio_open(struct inode *inode, struct file *filp)
{
    return 0;
}

static ssize_t mygpio_read(struct file *filp, char __user *buf,
                           size_t count, loff_t *ppos)
{
    int val = gpiod_get_value(priv.key) ? 1 : 0;
    char kbuf[2] = { val + '0', '\n' };

    if (copy_to_user(buf, kbuf, 2))
        return -EFAULT;
    return 2;
}

static ssize_t mygpio_write(struct file *filp, const char __user *buf,
                            size_t count, loff_t *ppos)
{
    char kbuf[8];
    int led_val;

    if (count >= sizeof(kbuf)) return -EINVAL;
    if (copy_from_user(kbuf, buf, count)) return -EFAULT;
    kbuf[count] = '\0';

    if (kstrtoint(kbuf, 10, &led_val) != 0)
        return -EINVAL;

    gpiod_set_value(priv.led, led_val ? 1 : 0);
    return count;
}

static const struct file_operations mygpio_fops = {
    .owner  = THIS_MODULE,
    .open   = mygpio_open,
    .read   = mygpio_read,
    .write  = mygpio_write,
};

static int mygpio_probe(struct platform_device *pdev)
{
    priv.led = devm_gpiod_get(&pdev->dev, "led", GPIOD_OUT_LOW);
    if (IS_ERR(priv.led)) return PTR_ERR(priv.led);

    priv.key = devm_gpiod_get(&pdev->dev, "key", GPIOD_IN);
    if (IS_ERR(priv.key)) return PTR_ERR(priv.key);

    alloc_chrdev_region(&devno, 0, 1, DEV_NAME);
    cdev_init(&my_cdev, &mygpio_fops);
    cdev_add(&my_cdev, devno, 1);

    my_class = class_create(THIS_MODULE, DEV_NAME);
    device_create(my_class, NULL, devno, NULL, DEV_NAME);

    dev_info(&pdev->dev, "mygpio probed\n");
    return 0;
}

static int mygpio_remove(struct platform_device *pdev)
{
    device_destroy(my_class, devno);
    class_destroy(my_class);
    cdev_del(&my_cdev);
    unregister_chrdev_region(devno, 1);
    return 0;
}

static const struct of_device_id mygpio_of[] = {
    { .compatible = "myvendor,mygpio" },
    { }
};
MODULE_DEVICE_TABLE(of, mygpio_of);

static struct platform_driver mygpio_driver = {
    .probe  = mygpio_probe,
    .remove = mygpio_remove,
    .driver = {
        .name           = "mygpio",
        .of_match_table = mygpio_of,
    },
};
module_platform_driver(mygpio_driver);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("You");
MODULE_DESCRIPTION("GPIO LED and key driver");

四、Makefile

obj-m += mygpio.o

五、编译并加入内核

# 单独编译
make -C /path/to/linux M=$PWD modules
cp mygpio.ko /path/to/rootfs/

# 编入内核
cp mygpio.c drivers/char/
echo "obj-y += mygpio.o" >> drivers/char/Makefile
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-

六、用户态测试

// test.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(void)
{
    int fd = open("/dev/mygpio", O_RDWR);
    if (fd < 0) { perror("open"); return 1; }

    // 点亮 LED
    write(fd, "1", 1);

    // 读按键
    char buf[8];
    read(fd, buf, sizeof(buf));
    printf("key state: %c\n", buf[0]);

    // 关闭 LED
    write(fd, "0", 1);

    close(fd);
    return 0;
}
arm-linux-gnueabihf-gcc -o test test.c
cp test /path/to/rootfs/root/

七、目标板测试

# 加载
insmod mygpio.ko
ls /dev/mygpio

# 测试
/test

# 内核日志
dmesg | tail

八、QEMU 模拟

QEMU vexpress-a9 默认没 GPIO 控制器,但可改模拟板或用 sysbus 自定义。

更简单的方法:用 i.MX 6ULL QEMU:

# Buildroot 或 NXP 官方提供 imx6ull QEMU 模拟
# 见 wiki 链接

或在真实开发板上跑。

九、扩展

ioctl 版本

#define MYGPIO_IOC_MAGIC 'g'
#define MYGPIO_SET_LED      _IOW(MYGPIO_IOC_MAGIC, 1, int)
#define MYGPIO_GET_KEY      _IOR(MYGPIO_IOC_MAGIC, 2, int)
#define MYGPIO_BLINK        _IOW(MYGPIO_IOC_MAGIC, 3, int)

static long mygpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
    int val;
    if (_IOC_TYPE(cmd) != MYGPIO_IOC_MAGIC) return -ENOTTY;
    switch (cmd) {
    case MYGPIO_SET_LED:
        if (get_user(val, (int __user *)arg)) return -EFAULT;
        gpiod_set_value(priv.led, !!val);
        break;
    case MYGPIO_GET_KEY:
        val = gpiod_get_value(priv.key) ? 1 : 0;
        if (put_user(val, (int __user *)arg)) return -EFAULT;
        break;
    default:
        return -ENOTTY;
    }
    return 0;
}

中断支持(按键按下唤醒)

static irqreturn_t key_irq(int irq, void *dev_id)
{
    // 唤醒等待队列
    return IRQ_HANDLED;
}

static int mygpio_probe(...)
{
    int irq = gpiod_to_irq(priv.key);
    int ret = devm_request_threaded_irq(&pdev->dev, irq, NULL,
                                         key_thread,
                                         IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
                                         "mygpio-key", &priv);
    // ...
}