天天看點

嵌入式Linux-IMX6ULL-Linux字元裝置驅動開發學習總結

1.首先需要建立加載驅動子產品函數主要用到

        module_init(xxx_init); //注冊子產品加載函數

        module_exit(xxx_exit); //注冊子產品解除安裝函數

那麼就需要建立一個xxx_init函數、一個xxx_exit函數如下所示

/* 驅動入口函數 */
static int __init xxx_init(void)
{
    /* 入口函數具體内容 */
    return 0;
}

/* 驅動出口函數 */
static void __exit xxx_exit(void)
{
    /* 出口函數具體内容 */
}

/* 将上面兩個函數指定為驅動的入口和出口函數 */
module_init(xxx_init);
module_exit(xxx_exit);
           

其中加載驅動子產品可以是用insmod xx.ko modprobe.ko 建議使用modprobe不會存在依賴問題,因為指令可以自動分析依賴,自動加載。而解除安裝子產品可以是rmmod xx.ko modprobe -r xx.ko這裡建議使用rmmod因為後一個有依賴解除安裝,本來隻要解除安裝一個驅動,結果把依賴關系的驅動都解除安裝了就得不償失了。

2.建立注冊和登出函數

        static inline int register_chrdev(unsigned int major, const char *name,

const struct file_operations *fops)

static inline void unregister_chrdev(unsigned int major, const char *name)

static struct file_operations test_fops;                //裝置驅動操作函數注冊結構體

/* 驅動入口函數 */
static int __init xxx_init(void)
{
    /* 入口函數具體内容 */
    int retvalue = 0;
    /* 注冊字元裝置驅動 */
    retvalue = register_chrdev(200, "chrtest", &test_fops);
    if(retvalue < 0){
        /* 字元裝置注冊失敗,自行處理 */
    }

    return 0;
}

/* 驅動出口函數 */
static void __exit xxx_exit(void)
{
    /* 出口函數具體内容 */
    /* 登出字元裝置驅動 */
    unregister_chrdev(200, "chrtest")
}

/* 将上面兩個函數指定為驅動的入口和出口函數 */
module_init(xxx_init);
module_exit(xxx_exit);
           

        注冊号了後可以在 cat /proc/devices  檔案中看到對于的檔案和裝置号

3.實作裝置具體的操作函數一般就是open、release、read、write

        open

/* 打開裝置 */
static int chrtest_open(struct inode *inode, struct file *filp)
{
    /* 使用者實作具體功能 */
    return 0;
}
           

        release

/* 關閉/釋放裝置 */
static int chrtest_release(struct inode *inode, struct file *filp)
{
    /* 使用者實作具體功能 */
    return 0;
}
           

        read

/* 從裝置讀取 */
static ssize_t chrtest_read(struct file *filp, char __user *buf,
size_t cnt, loff_t *offt)
{
    /* 使用者實作具體功能 */
    return 0;
}
           

        write

/* 向裝置寫資料 */
static ssize_t chrtest_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
    /* 使用者實作具體功能 */
    return 0;
}
           

        最後添加到注冊結構體中注冊

static struct file_operations test_fops = {
    .owner = THIS_MODULE,
    .open = chrtest_open,
    .read = chrtest_read,
    .write = chrtest_write,
    .release = chrtest_release,
};
           

4.最後添加license和作者資訊,license必須要加的不然會編譯報錯,作者資訊自由選擇可加可不加

MODULE_LICENSE() //添加子產品 LICENSE 資訊
MODULE_AUTHOR() //添加子產品作者資訊
           

Linux 中每個裝置都有一個裝置号,裝置号由主裝置号和次裝置号兩部分組成,主裝置号表示某一個具體的驅動,次裝置号表示使用這個驅動的各個裝置。主裝置号0~4095

Linux推薦用動态配置設定裝置号,這樣友善管理。

以上就是字元裝置驅動的開發模闆了。

繼續閱讀