1.套路
1.搭建一个框架,具体为:
a.定义结构体second_drv_fops:
static struct file_operations second_drv_fops = {
.owner = THIS_MODULE, /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
.open = second_drv_open,
.write = second_drv_write,
};
然后完善相关函数:
static int second_drv_open(struct inode *inode, struct file *file)
{
return 0;
}
static ssize_t second_drv_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
{
return 0;
}
static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
return 0;
}
b.定义入口函数、出口函数并修饰:
static int second_drv_init(void)
{
major = register_chrdev(0, "second_drv", &second_drv_fops); // 注册, 告诉内核
return 0;
}
static int second_drv_exit(void)
{
major = unregister_chrdev(0, "second_drv", &second_drv_fops); // 注册, 告诉内核
return 0;
}
module_init(second_drv_init);
module_exit(second_drv_exit);
c.给内核提供更多的信息以自动创建驱动目录(驱动节点):
static struct class *seconddrv_class;
static struct class_device *seconddrv_class_dev;
/* 而后入口/出口函数可以改为: */
static int second_drv_init(void)
{
major = register_chrdev(0, "second_drv", &second_drv_fops); // 注册, 告诉内核
seconddrv_class = class_create(THIS_MODULE, "seconddrv");
seconddrv_class_dev = class_device_create(seconddrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */
return 0;
}
static int second_drv_exit(void)
{
major = unregister_chrdev(0, "second_drv", &second_drv_fops); // 注册, 告诉内核
class_device_unregister(seconddrv_class_dev);
class_destroy(seconddrv_class);
return 0;
}
d.之后就和写单片机的程序一样了,不过地址用的是虚拟地址,需要映射。
在open函数里初始化寄存器,在read函数里返回引脚状态,在入口函数里进行地址映射,在出口函数里解除映射关系。