欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

usb驱动程序设计

程序员文章站 2022-07-11 18:54:25
...
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/usb.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/slab.h>

//传输变量 
#define BULKOUT_BUFFER_SIZE 512
char *bulkout_buffer;
//usb设备定义
struct usb_device *udev; 
//保存端点 
__u8 bulk_out_endaddr; 

static struct usb_device_id dnw_id_table[] = {
	//获取USB设备ID 
	{ USB_DEVICE(,) },//通过lsusb获取 
	{}
};

static int dnw_open(struct inode* inode, struct file *file)
{
	//申请拷贝空间 
	bulkout_buffer = kmalloc(BULKOUT_BUFFER_SIZE,GFP_KERNEL);
	return 0;	
}

static int dnw_release(struct inode* inode, struct file *file)
{
	//释放拷贝空间 
	kfree(bulkout_buffer);
	return 0;
}

static ssize_t dnw_write(struct file *file, const char __user *buf, size_t len, loff_t *pos)
{
	size_t to_write;
	size_t total_write = 0;
	size_t act_len;
	while(len>0)
	{
		to_write = min((size_t)len,BULKOUT_BUFFER_SIZE);
		copy_from_user(bulkout_buffer+total_write,buf);
	
		usb_bulk_msg(udev,usb_sndbulkpipe(udev,bulk_out_endaddr),bulkout_buffer,to_write,&act_len,3*HZ);//(2)获取端点信息 
		
		len -= to_write;
		total_write += to_write;
	}
	
	return total_write;
}

static struct file_operations dnw_ops =
{
	.owner =	THIS_MODULE,
	.write =	dnw_write,
	.open =		dnw_open,
	.release =	dnw_release,
};

static struct usb_class_driver dnw_class = {
	.name = "dnw%d";
	.fops = &dnw_ops;
	.minor_base = 100;
};


static int usb_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
	int i = 0;
	//接口设置描述
	struct usb_host_interface *interface;
	/* 端点描述符 */
	struct usb_endpoint_descriptor *endpoint;
	
	interface = intf->cur_altsetting;
	
//	interface->desc.bNumEndpoints;
	
	/* 获取端点0描述符 */
//	endpoint = &interface->endpoint[0].desc;
	
	for(i=0;i<interface->desc.bNumEndpoints;i++)
	{
		endpoint = &interface->endpoint[i].desc;
		//判断bulk_out端点 
		if(usb_endpoint_is_bulk_out(endpoint))	
		{
			bulk_out_endaddr = endpoint->bEndpointAddress;
			break;
		}
	} 
	
	usb_register_dev(intf,&dnw_class);	
	
	usb_get_dev( interface_to_usbdev(intf) );
} 

static void dnw_disconnect(struct usb_interface *intf)
{
	usb_deregister_dev(intf,&dnw_class);
}

//usb结构体初始化 
static struct usb_driver dnw_driver = {
	.name		= "dnw",   /* 驱动名 */
	.probe		= dnw_probe, /* 捕获函数 */
	.disconnect	= dnw_disconnect, /* 卸载函数 */
	.id_table	= dnw_id_table, /* 设备列表 */
}; 

int dnw_init()
{
	//usb注册 
	usb_register(&dnw_driver);
	return 0;
} 

void dnw_exit()
{
	usb_deregister(&dnw_driver);
}

module_init(dnw_init);
module_exit(dnw_exit);
//支持协议 
MODULE_LICENSE("GPL");