Linux驱动开发③--LED流水灯驱动示例

2019-07-13 05:32发布

#include #include #include #include #include #include #include #include #include #include #include #include #include #include #define DEVICE_NAME "FLOWLED" #define LED_MAJOR 246 /* 主设备号*/ #define LED_ON 1 #define LED_OFF 2 struct led_dev { struct cdev cdev; unsigned char value; }; struct led_dev *leddev; static int flowled_open(struct inode *inode, struct file *filp) { printk("flowled_open "); return 0; } static int flowled_release(struct inode *inode, struct file *filp) { printk("flowled_release "); return 0; } static int flowled_write(struct file *file, const char *buffer,size_t count, loff_t *ppos) { // printk("%s",buffer); printk("flowled_write:%d ",count); return count; } static int flowled_read(struct file *file, char *buffer,size_t count, loff_t *ppos) { printk("flowled_read "); // *ppos = 0; // buffer[0] = 'a'; // buffer[1] = 'b'; // buffer[2] = 0; return 3; } int flowled_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) { return 0; } static struct file_operations flowled_fops = { .owner = THIS_MODULE, .open = flowled_open, .read = flowled_read, .write = flowled_write, .release = flowled_release, }; static int __init flowled_init(void) { int result,err; printk("flowled_init "); //申请设备号 dev_t devno = MKDEV(LED_MAJOR, 2); if(LED_MAJOR) result = register_chrdev_region(devno, 1, DEVICE_NAME); /*动态申请设备结构体的内存*/ leddev = kmalloc(sizeof(struct led_dev), GFP_KERNEL); if (!leddev) { result = -ENOMEM; goto fail_malloc; } //硬件初始化,推荐在open中实现 //sep4020_flowled_setup(); //字符设备注册 cdev_init(&(leddev->cdev), &flowled_fops); leddev->cdev.owner = THIS_MODULE; err = cdev_add(&leddev->cdev, devno, 1);// 创建设备文件 return 0; fail_malloc: unregister_chrdev_region(devno, 1); return result; } static void __exit flowled_exit(void) { //删除设备文件 cdev_del(&leddev->cdev); kfree(leddev); unregister_chrdev(LED_MAJOR, DEVICE_NAME); printk("flowled_exit "); } module_init(flowled_init); //向Linux系统记录设备初始化的函数名称 module_exit(flowled_exit); //向Linux系统记录设备退出的函数名称 MODULE_LICENSE("GPL"); MODULE_AUTHOR("tangquan"); MODULE_DESCRIPTION("simple char driver!");