【Linux驱动模块】三、SR501-内核线程实现中断
【Linux驱动模块】三、SR501-内核线程实现中断
本文最后更新于317 天前,其中的信息可能已经过时,如有错误请发送邮件到273925452@qq.com
Avatar
在前一篇的修改设备树的基础上,加入了内核线程替代GPIO中断

程序

sr501_drv.c

#include <linux/module.h>
#include <linux/poll.h>

#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/kmod.h>
#include <linux/gfp.h>
#include <linux/gpio/consumer.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/timer.h>
#include <linux/of.h>
#include <linux/gpio.h>
#include <linux/kthread.h>

/* 主设备号                                                                 */
static int major = 0;
static struct class *sr501_class;
static struct gpio_desc *sr501_gpio;        //GPIO结构体操作指针
static wait_queue_head_t sr501_wq;          //等待队列
struct task_struct *task;                   //进程
struct task_struct *sr501_kthread;          //进程

/* 环形缓冲区 */
#define BUF_LEN 128
static int g_sr501[BUF_LEN];
static int r, w;  //缓冲区读和写的索引

struct fasync_struct *sr501_fasync;

#define NEXT_POS(x) ((x+1) % BUF_LEN)

/* 缓冲区是否为空 */
static int is_sr501_buf_empty(void)
{
    return (r == w);
}

/* 缓冲区是否为满 */
static int is_sr501_buf_full(void)
{
    return (r == NEXT_POS(w));
}


/* 向缓冲区放入数据 */
static void put_sr501(int sr501_val)
{
    if (!is_sr501_buf_full()) /* 缓冲区没有满 */
    {
        g_sr501[w] = sr501_val; // key放入缓冲区
        w = NEXT_POS(w);    //更新写索引
    }
}

/* 从缓冲区取出数据 */
static int get_sr501(void)
{
    int sr501_val = 0;
    if (!is_sr501_buf_empty()) // 缓冲区数据不为空
    {
        sr501_val = g_sr501[r]; // 取出缓冲区数据
        r = NEXT_POS(r);    //更新读索引
    }
    return sr501_val;
}

/* 创建等待队列sr501_wq  */
// static DECLARE_WAIT_QUEUE_HEAD(sr501_wq);


/* 实现对应的open/read/write等函数,填入file_operations结构体                   */
static ssize_t gpio_drv_read (struct file *file, char __user *buf, size_t size, loff_t *offset)
{
    //printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
    int err;
    int sr501_val; // int类型占用4字节

    /* 缓冲区数据为空 且 为非阻塞模式 -> 返回错误码*/
    if (is_sr501_buf_empty() && (file->f_flags & O_NONBLOCK))
        return -EAGAIN;

    /* 阻塞等待缓冲区数据非空 */
    wait_event_interruptible(sr501_wq, !is_sr501_buf_empty());

    /* 从缓冲区取出数据 */
    sr501_val = get_sr501();

    /* 把数据拷贝到用户空间 */
    err = copy_to_user(buf, &sr501_val, sizeof(sr501_val));

    return 4;
}



/*  轮询  */ 
static unsigned int gpio_drv_poll(struct file *fp, poll_table * wait)
{

    /* 1.函数会不断检查GPIO端口的状态,如果状态满足等待条件,则结束等待
       2.如果等待时间超过指定时间,则返回超时错误。
      wait:等待时间
     */
    poll_wait(fp, &sr501_wq, wait);

    return is_sr501_buf_empty() ? 0 : POLLIN | POLLRDNORM;
}

/* 异步通知 */
static int gpio_drv_fasync(int fd, struct file *file, int on)
{
    /* 该函数用于注册或取消注册异步通知。如果注册成功,则返回0;否则返回-EIO。*/
    if (fasync_helper(fd, file, on, &sr501_fasync) >= 0)
        return 0;
    else
        return -EIO;
}


/* 定义自己的file_operations结构体                                              */
static struct file_operations sr501_fops = {
    .owner = THIS_MODULE,
    .read = gpio_drv_read,
    .poll = gpio_drv_poll,
    .fasync = gpio_drv_fasync, // 异步通知
};

static int sr501_thread_func(void *data)
{
    int sr501_val;
    int pre = -1;
    while(1)
    {
        sr501_val = gpiod_get_value(sr501_gpio);

        if (pre != sr501_val)
        {
            printk("%s %s line %d sr501_val = %d\n", __FILE__, __FUNCTION__, __LINE__, sr501_val);
            sr501_val = 0x80 | sr501_val;

            put_sr501(sr501_val);             // 将sr501值放入环形缓冲区
            wake_up_interruptible(&sr501_wq); // 唤醒任何在sr501_wq上等待的进程
            pre = sr501_val;
        }
        set_current_state(TASK_INTERRUPTIBLE);
        schedule_timeout(HZ);
        if(kthread_should_stop()) {
            set_current_state(TASK_RUNNING);
            break;
        }
    }

    return 0;
}



/*   从platform_device获得GPIO
 *    把file_operations结构体告诉内核:注册驱动程序
 */
static int sr501_probe(struct platform_device *pdev)
{

    /* 设备树中定义有: sr501-gpios=<...>;    */
    /*
        该行代码的作用:从设备树中获取与 pdev 关联的设备上的 "sr501" GPIO 线。
        &pdev->dev: 指向 struct device 结构体的指针,这个结构体描述了一个设备
        gpiod_get():从设备树(Device Tree)中查找并获取一个 GPIO 控制器上的 GPIO 线。
    */
        sr501_gpio = gpiod_get(&pdev->dev, "sr501", 0);  //获得硬件信息
        if (IS_ERR(sr501_gpio))
        {
            dev_err(&pdev->dev, "Failed to get GPIO for sr501\n");    
            return PTR_ERR(sr501_gpio);
        }
        gpiod_direction_input(sr501_gpio);   //设置为输入状态

        sr501_kthread = kthread_run(sr501_thread_func, NULL, "sr501d");   //创建进程
    
    /* 注册file_operations     */
    major = register_chrdev(0, "sr501_chrdev", &sr501_fops); /* /dev/gpio_desc */

    sr501_class = class_create(THIS_MODULE, "sr501_class");
    if (IS_ERR(sr501_class))
    {
        dev_err(&pdev->dev, "Failed to create class\n");
        unregister_chrdev(major, "sr501_chrdev");
        return PTR_ERR(sr501_class);
    }

    device_create(sr501_class, NULL, MKDEV(major, 0), NULL, "sr501"); /* /dev/sr501 */

    dev_info(&pdev->dev, "sr501 initialized successfully\n");

    return 0;
}

static int sr501_remove(struct platform_device *pdev)
{
    // int i;
    // int count = sizeof(gpios) / sizeof(gpios[0]);

    printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);

    device_destroy(sr501_class, MKDEV(major, 0));
    class_destroy(sr501_class);
    unregister_chrdev(major, "sr501_chrdev");

    gpiod_put(sr501_gpio); //释放GPIO引脚

    return 0;
}

/* 定义设备树匹配表,用于识别和支持特定的LED驱动器 */
static const struct of_device_id sr501_match_table[] = {
    /* 匹配字符串 "fire,sr501" 用于标识 */
    {.compatible = "fire,sr501"},
    /* 空项作为匹配表的结束标志 */
    {},
};

/*  定义platform_driver */
static struct platform_driver sr501_driver = {
    .probe =  sr501_probe,   // 设置探测函数,当设备被探测到时调用
    .remove = sr501_remove, // 设置移除函数,当设备被移除时调用

    /* 设置<驱动程序的名称>和<设备树匹配表> */
    .driver = {
        .name = "sr501",         // 字符设备名
        .of_match_table = sr501_match_table, // 设置设备树匹配表,用于设备的匹配
    },
};

/* 在入口函数 */
static int __init sr501_drv_init(void)
{
    int err;
    init_waitqueue_head(&sr501_wq);  // 初始化等待队列
    err = platform_driver_register(&sr501_driver);

    

    return err;
}

/* 有入口函数就应该有出口函数:卸载驱动程序时,就会去调用这个出口函数
 */
static void __exit sr501_drv_exit(void)
{
    kthread_stop(sr501_kthread);
    platform_driver_unregister(&sr501_driver);

    printk("===== exit =====\n");
}


/* 7. 其他完善:提供设备信息,自动创建设备节点                                     */

module_init(sr501_drv_init);
module_exit(sr501_drv_exit);

MODULE_LICENSE("GPL");


sr501_test.c


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <poll.h>
#include <signal.h>

static int fd;

/*
 * ./SR501_test /dev/sr501
 *
 */
int main(int argc, char **argv)
{
    int val;
    int    flags;

    /* 1. 判断参数 */
    if (argc != 2) 
    {
        printf("Usage: %s <dev>\n", argv[0]);
        return -1;
    }


    /* 2. 打开文件 */
    fd = open(argv[1], O_RDWR);
    if (fd == -1)
    {
        printf("can not open file %s\n", argv[1]);
        return -1;
    }

    while(1) 
    {
        if (read(fd, &val, 4) == 4)
            printf("get sr501: 0x%x\n", val);
        else
            printf("get sr501: -1\n");
    }

    /*如果发生意外,就阻塞程序*/
    /*获取文件描述符 fd 当前的打开方式,并将结果保存在变量 flags 中。
     */
    flags = fcntl(fd, F_GETFL);

    /* 设置文件描述符 fd 的打开方式
    flags & ~O_NONBLOCK: 将 flags 中的非阻塞模式标志位清除,即关闭非阻塞模式
    */
    fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); 


    close(fd);
    
    return 0;
}


Makefile


# 1. 使用不同的开发板内核时, 一定要修改KERN_DIR
# 2. KERN_DIR中的内核要事先配置、编译, 为了能编译内核, 要先设置下列环境变量:
# 2.1 ARCH,          比如: export ARCH=arm64
# 2.2 CROSS_COMPILE, 比如: export CROSS_COMPILE=aarch64-linux-gnu-
# 2.3 PATH,          比如: export PATH=$PATH:/home/book/100ask_roc-rk3399-pc/ToolChain-6.3.1/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin 
# 注意: 不同的开发板不同的编译器上述3个环境变量不一定相同,
#       请参考各开发板的高级用户使用手册

KERN_DIR =  /home/book/100ask_imx6ull-sdk/Linux-4.9.88 # 板子所用内核源码的目录

all:
    make -C $(KERN_DIR) M=`pwd` modules 
    $(CROSS_COMPILE)gcc -o sr501_test sr501_test.c
clean:
    make -C $(KERN_DIR) M=`pwd` modules clean
    rm -rf modules.order  sr501_test

# 参考内核源码drivers/char/ipmi/Makefile
# 要想把a.c, b.c编译成ab.ko, 可以这样指定:
# ab-y := a.o b.o
# obj-m += ab.o



obj-m += sr501_drv.o

💡商业转载请联系作者获得授权,非商业转载请注明出处。
协议(License):署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)。
使用这些免费资源的时候应遵守版权意识,切勿非法利用,售卖,尊重原创内容知识产权。未经允许严禁转载。

评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇