赞
踩
前面我们讲了linux驱动框架linux驱动(一)驱动框架,对驱动的基本框架有了了解。现在我们来说一说字符设备驱动,我们一般讲驱动分为三类,字符设备、块设备、网络设备。字符设备和块设备是按照传输时的基本单位来划分的,字符设备就是传输时是按字符来传输的,比如串口、GPIO、SPI等。字符设备如硬盘等按照块传输的设备,块设备和网络设备的驱动我们跟多是做移植的工作,字符设备种类繁多且不算复杂,所以就会自己来写。
- int major = 250;
- int minor = 0;
- int devno;
- devno = MKDEV(major, minor);
(2) 申请注册设备号
- dev_t devno;
- int major = 250;
- int minor = 0;
- int count = 1;
- struct cdev cdev; //设备对象
-
- int demo_open(struct inode *inodep, struct file * filep) // 打开设备
- {
-
- return 0;
- }
- int demo_release(struct inode * inodep, struct file * filep) // 关闭设备
- {
- return 0;
- }
- ssize_t demo_read(struct file * filep, char __user * buffer, size_t size, loff_t * offlen)
- {
- return size;
- }
- ssize_t demo_write(struct file *filep, const char __user *buffer, size_t size, loff_t * offlen)
- {
- return size;
- }
- long demo_ioctl(struct file * filep, unsigned int cmd, unsigned long arg)
- {
- return 0;
- }
- struct file_operations fops = {
- .owner = THIS_MODULE,
- .open = demo_open,
- .release = demo_release,
- .read = demo_read,
- .write = demo_write,
- .unlocked_ioctl = demo_ioctl,
- };
- #include <linux/init.h>
- #include <linux/module.h>
- #include <linux/kernel.h>
- #include <linux/cdev.h>
- #include <linux/fs.h>
-
- MODULE_LICENSE("GPL");
-
- dev_t devno;
-
- int major = 250;
- int minor = 0;
- int count = 1;
-
- struct cdev cdev;
-
- int demo_open(struct inode *inodep, struct file * filep) // 打开设备
- {
- printk("%s,%d\n", __func__, __LINE__);
- return 0;
- }
-
- int demo_release(struct inode * inodep, struct file * filep) // 关闭设备
- {
- printk("%s,%d\n", __func__, __LINE__);
- return 0;
- }
-
- struct file_operations fops = {
- .owner = THIS_MODULE,
- .open = demo_open,
- .release = demo_release,
- };
-
- static int __init demo_init(void)
- {
- int ret = 0;
-
- printk("%s,%d\n", __func__, __LINE__);
-
- devno = MKDEV(major, minor);
- printk("devno:%d\n", devno);
-
- ret = register_chrdev_region(devno, count, "xxx");
- if(ret)
- {
- printk("Failed to register_chrdev_region.\n");
- return ret;
- }
-
- cdev_init(&cdev, &fops);
- cdev.owner = THIS_MODULE;
-
- ret = cdev_add(&cdev, devno, count);
- if(ret)
- {
- printk("Failed to cdev_add.\n");
- unregister_chrdev_region(devno, count);
- return ret;
- }
-
- return 0;
- }
-
- static void __exit demo_exit(void)
- {
- printk("%s,%d\n", __func__, __LINE__);
- cdev_del(&cdev);
- unregister_chrdev_region(devno, count);
- }
-
- module_init(demo_init);
- module_exit(demo_exit);
这里只实现了简单的open close,框架嘛对吧 其余的根据功能实现就是了。insmod之后,可以看到/proc/devices下有了个名字为xxx的设备号
- #include <stdio.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <fcntl.h>
-
-
-
-
- int main(int argc, const char *argv[])
- {
- int fd;
-
-
- fd = open("/dev/hello", O_RDWR);
- if(fd < 0)
- {
- perror("Failed to open.");
- return -1;
- }
- else
- {
- printf("open success.\n");
- }
-
-
- getchar();
-
-
- close(fd);
-
-
-
-
- return 0;
- }
编译后看一下执行结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。