由于该驱动只涉及简单的I/O口电平变化,驱动比较简单。这里采用杂项设备驱动模型写出该驱动,杂项设备驱动能自动创建设备文件,比起其余两种驱动类型要省事不少。
下面列出前面书写的杂项设备驱动模板(没有必要的安全检测,只有大概框架),蜂鸣器驱动将在下面的例子中改动:
#include#include#include#include#include#define MISC_MINOR 255//打开函数staticint misc_open(struct inode *node, struct file *fp)
{
printk("this dev is open
");
return0;
}
//关闭函数staticint misc_close(struct inode *node, struct file *fp)
{
printk("this dev is close
");
return0;
}
//读函数
ssize_t misc_read(struct file *fp, char __user *buf, size_t size, loff_t *loff)
{
printk("this dev is read
");
return0;
}
//写函数
ssize_t misc_write(struct file *fp, constchar __user *buf, size_t size, loff_t *loff)
{
printk("this dev is write
");
return0;
}
struct file_operations fops={
.owner=THIS_MODULE,
.open=misc_open,
.read=misc_read,
.write=misc_write,
.release=misc_close,
};
struct miscdevice mymisc={
.minor=MISC_MINOR,
.name="mymisc",
.fops=&fops,
};
//驱动初始化staticint __init misc_init(void)
{
if(misc_register(&mymisc))
{
printk("this module is insmod fail
");
return -1;
}
printk("this module is success
");
return0;
}
//驱动卸载staticvoid __exit misc_exit(void)
{
printk("this module is exit
");
}
module_init(misc_init);
module_exit(misc_exit);
MODULE_LICENSE("GPL");
调用函数解释
ioremap
函数原型:void* ioremap(unsigned long phys_addr,unsigned long size)
作用:将实际物理地址映射到地址管理单元
参数:phys_addr实际物理地址,size映射地址大小
返回值:返回该物理地址在地址管理单元中地址,操作改地址等效于操作实际物理地址
安装驱动模块[root@ZC/zhangchao]#ls
Makefile misc.c misc.mod.c misc.o modules.order
Module.symvers misc.ko misc.mod.o misc_app.c
[root@ZC/zhangchao]#insmod misc.ko
[ 25.585000] this module is success
[root@ZC/zhangchao]#ls /dev/mymisc -l
crw-rw---- 1 root root 10, 47 Jan 112:34 /dev/mymisc
[root@ZC/zhangchao]#运行app[root@ZC/zhangchao]#ls
Makefile app misc.ko misc.mod.o misc_app.c
Module.symvers misc.c misc.mod.c misc.o modules.order
[root@ZC/zhangchao]#./app /dev/mymisc
[ 194.775000] this dev is open
[ 194.775000] this dev is read
[ 195.775000] this dev is write
[ 196.775000] this dev is read
[ 197.775000] this dev is write
[ 198.775000] this dev is read
[ 199.775000] this dev is write
[ 200.775000] this dev is close
[root@ZC/zhangchao]#