您的位置:首页 > 其它

用一个实例来理解驱动程序编写流程 (自用)

2018-07-04 11:05 67 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35769746/article/details/80909359
#include <linux/module.h>
#include <linux/kernel.h>
#include <asm/io.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
 

//流水灯代码

 

#define  GPM4CON 0x110002e0
#define  GPM4DAT 0x110002e4


static unsigned long*  ledcon = NULL;
static unsigned long*  leddat = NULL;

//自定义write文件操作(不自定义的话,内核有默认的一套文件操作函数)
static  ssize_t  test_write (struct file * filp, const char __user * buff, size_t count, loff_t * offset)
{
    int  value = 0;
    int ret = 0;

    ret = copy_from_user(&value, buff, 4);

 

       //底层驱动只定义基本操作动作,不定义功能

    if(value == 1)
        {
        *leddat  |=  0x0f;
        *leddat  &=  0xfe;
        }
    if(value == 2)
        {
        *leddat  |=  0x0f;
        *leddat  &=  0xfd;
        }
    if(value == 3)
        {
        *leddat  |=  0x0f;
        *leddat  &=  0xfb;
        }
    if(value == 4)
        {
        *leddat  |=  0x0f;
        *leddat  &=  0xf7;
        }
    return 0;
}
 

 

//文件操作结构体初始化

static  struct file_operations  g_tfops = {
                        .owner = THIS_MODULE,
                        .write = test_write,
                        };
        

 

//杂设备信息结构体初始化

static  struct miscdevice  g_tmisc = {
            .minor = MISC_DYNAMIC_MINOR,
            .name = "test_led",
            .fops = &g_tfops,
            };



//驱动入口函数         杂设备初始化
static  int  __init   test_misc_init(void)

    {

        //IO地址空间映射到内核的虚拟地址空间

        ledcon = ioremap(GPM4CON, 4);

        leddat = ioremap(GPM4DAT, 4);

 

         //初始化led

        *ledcon  &=  0xffff0000;
        *ledcon  |=  0x00001111;
        *leddat  |=  0x0f;

 

         //杂设备注册函数

        misc_register(&g_tmisc);
        return 0;
    }
 

 

//驱动出口函数

static  void  __exit  test_misc_exit(void)
    {

        //释放地址映射
        iounmap(ledcon);
        iounmap(leddat);
    }
 

 

//指定模块的出入口函数

module_init(test_misc_init);
module_exit(test_misc_exit);


MODULE_LICENSE("GPL");
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐