第一、二期銜接——3.2 字符驅動設備—LED設備驅動的框架改進

字符驅動設備之LED設備驅動的改進

  • 硬件平臺:韋東山嵌入式Linxu開發板(S3C2440.v3)
  • 軟件平臺:運行於VMware Workstation 12 Player下UbuntuLTS16.04_x64 系統
  • 參考資料:《嵌入式Linux應用開發手冊》
  • 開發環境:Linux 2.6.22.6 內核、arm-linux-gcc-3.4.5-glibc-2.3.6工具鏈


爲了讓程度可以自動創建設備節點,不需要手動去新建設備節點,進行如下改進。

一、改進first_drv_init()函數

1、讓系統自動分配設備號

原程序中:major我們需要linux自動給我們分配主設備號,所以改爲0
修改後:major = register_chrdev(0, "first_drv", &first_drv_fops);

2、讓系統自動創建創建設備節點

添加如下類,用來保存信息

static struct class *firstdrv_class;
static struct class_device	*firstdrv_class_dev

first_drv_init()函數中添加如下語句:

firstdrv_class = class_create(THIS_MODULE, "firstdrv");
firstdrv_class_dev = class_device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */

這樣,系統將會自動創建設備名爲firstdrv,主設備號爲major,次設備號爲0,節點目錄爲/dev/xyz的設備節點。

二、改進first_drv_exit()函數

上述操作中已經自動創建設備節點,下面來自動卸載設備節點

static void first_drv_exit(void)
{
	unregister_chrdev(major, "first_drv"); // 卸載

	class_device_unregister(firstdrv_class_dev);
	class_destroy(firstdrv_class);
}

三、添加命令

MODULE_LICENSE("GPL");

四、結果

1、總程序

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>

static struct class *firstdrv_class;
static struct class_device	*firstdrv_class_dev;

static int first_drv_open(struct inode *inode, struct file *file)
{
	printk("first_drv_open\n");
	return 0;
}

static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
	printk("first_drv_write\n");
	return 0;
}

static struct file_operations first_drv_fops = {
    .owner  =   THIS_MODULE,    /* 這是一個宏,推向編譯模塊時自動創建的__this_module變量 */
    .open   =   first_drv_open,     
	.write	=	first_drv_write,	   
};


int major;
static int first_drv_init(void)
{
	major = register_chrdev(0, "first_drv", &first_drv_fops); // 註冊, 告訴內核

	firstdrv_class = class_create(THIS_MODULE, "firstdrv");
	firstdrv_class_dev = class_device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */
	
	return 0;
}

static void first_drv_exit(void)
{
	unregister_chrdev(major, "first_drv"); // 卸載

	class_device_unregister(firstdrv_class_dev);
	class_destroy(firstdrv_class);
}

module_init(first_drv_init);
module_exit(first_drv_exit);

MODULE_LICENSE("GPL");

2、加載驅動

可以看到此時系統自動幫我們創建的設備號,並且在/dev目錄下,自動創建了設備節點xyz

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章