本文以USB鼠标讲解USB设备驱动。
驱动程序中调用usb_register(struct usb_driver *)函数时,先判断USB总线驱动程序是否支持usb_driver里定义的id_table,若支持,调用usb_driver的probe函数。
所以首先要定义并初始化usb_driver结构体:
static struct usb_driver usbmouse_as_key_driver = { .name = "usbmouse_as_key", .probe = usbmouse_as_key_probe, .disconnect = usbmouse_as_key_disconnect, .id_table = usbmouse_as_key_id_table, };
static struct usb_device_id usbmouse_as_key_id_table[] = { {USB_INTERFACE_INFO(USB_INTERFACE_CLASS_HID, USB_INTERFACE_SUBCLASS, USB_INTERFACE_PROTOCOL_MOUSE)}, {}, };
static struct urb *uk_urb; static int usbmouse_as_key_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf);/* 由接口获得设备 */ struct usb_host_interface *interface;/*设置描述符 */ struct usb_endpoint_descripter *endpoint;/* 端点描述符 */ int pipe; interface = intf->cur_alterseting;/* 获得设置描述符 */ endpoint = &interface->endpoint[0].desc;/* 获得端点描述符 */ /* 分配设置input_dev */ uk_dev = input_allocate_device(); set_bit(EV_KEY, uk_dev->evbit); set_bit(EV_REP, uk_dev->evbit); set_bit(KEY_L, uk_dev->keybit); set_bit(KEY_S, uk_dev->keybit); set_bit(KEY_ENTER, uk_dev->keybit); input_register_device(uk_dev); /* 构造数据传输3要素 */ /* 源 */ pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);//生成一个中断管道,然后把得到的管道赋到了urb上 /* 长度 */ len = endpoint->wMaxPacketSize; /* 目的 */ uk_buf = usb_buffer_alloc(0, GFP_KERNEL); /* 使用三要素设置URB 填充中断urb */ usb_fill_int_urb(uk_urb, dev, pipe, usb_buf, len, usbmouse_as_key_irq, NULL, endpoint->bInterval); uk_urb->transer_dma = usb_buf_phys; uk_urb->transfer_flags |= URB_NO_TRANSFER_DMA_REP; usb_submit_urb(uk_urb, GFP_KERNEL);/* 将urb递交给USB核心 */ return 0; } static void usbmouse_as_key_disconnect(struct usb_interface *intf) { struct usb_device *dev = interface_to_usbdev(intf); //printk("disconnect usbmouse!\n"); usb_kill_urb(uk_urb); usb_free_urb(uk_urb); usb_buffer_free(dev, len, usb_buf, usb_buf_phys); input_unregister_device(uk_dev); input_free_device(uk_dev); } static void usbmouse_as_key_irq(struct urb *urb) { static unsigned char pre_val; /* USB鼠标数据含义 * data[0]: bit0-左键, 1-按下, 0-松开 * bit1-右键, 1-按下, 0-松开 * bit2-中键, 1-按下, 0-松开 * */ if ((pre_val & (1<<0)) != (usb_buf[0] & (1<<0))) { /* 左键发生了变化 */ input_event(uk_dev, EV_KEY, KEY_L, (usb_buf[0] & (1<<0)) ? 1 : 0); input_sync(uk_dev); } if ((pre_val & (1<<1)) != (usb_buf[0] & (1<<1))) { /* 右键发生了变化 */ input_event(uk_dev, EV_KEY, KEY_S, (usb_buf[0] & (1<<1)) ? 1 : 0); input_sync(uk_dev); } if ((pre_val & (1<<2)) != (usb_buf[0] & (1<<2))) { /* 中键发生了变化 */ input_event(uk_dev, EV_KEY, KEY_ENTER, (usb_buf[0] & (1<<2)) ? 1 : 0); input_sync(uk_dev); } pre_val = usb_buf[0]; usb_submit_urb(uk_urb, GFP_KERNEL);/* 重新提交URB */ }
原文地址:http://www.cnblogs.com/zpehome/p/3822328.html