写一段USB代码
时间: 2023-07-10 11:06:07 浏览: 93
USB接口读写数据的程序
3星 · 编辑精心推荐
以下是一个简单的USB设备驱动程序,用于Linux操作系统中的USB鼠标:
```
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/hid.h>
// 定义USB设备的厂商ID和产品ID
#define USB_VENDOR_ID 0x046d
#define USB_PRODUCT_ID 0xc52b
// USB设备驱动程序的初始化函数
static int usb_mouse_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
// 打印设备信息
printk(KERN_INFO "USB Mouse (%04X:%04X) plugged\n", id->idVendor, id->idProduct);
// 获取USB设备
struct usb_device *dev = interface_to_usbdev(interface);
// 打印设备描述符
printk(KERN_INFO "USB Mouse: bcdUSB = %04X, bDeviceClass = %02X, bDeviceSubClass = %02X, bDeviceProtocol = %02X\n",
dev->descriptor.bcdUSB, dev->descriptor.bDeviceClass, dev->descriptor.bDeviceSubClass, dev->descriptor.bDeviceProtocol);
// 打印接口描述符
printk(KERN_INFO "USB Mouse: bInterfaceClass = %02X, bInterfaceSubClass = %02X, bInterfaceProtocol = %02X\n",
interface->cur_altsetting->desc.bInterfaceClass, interface->cur_altsetting->desc.bInterfaceSubClass, interface->cur_altsetting->desc.bInterfaceProtocol);
return 0;
}
// USB设备驱动程序的退出函数
static void usb_mouse_disconnect(struct usb_interface *interface)
{
// 打印设备信息
printk(KERN_INFO "USB Mouse disconnected\n");
}
// 定义USB设备的ID
static struct usb_device_id usb_mouse_id_table[] = {
{ USB_DEVICE(USB_VENDOR_ID, USB_PRODUCT_ID) },
{ }
};
MODULE_DEVICE_TABLE(usb, usb_mouse_id_table);
// 定义USB设备驱动程序结构体
static struct usb_driver usb_mouse_driver = {
.name = "usb_mouse",
.probe = usb_mouse_probe,
.disconnect = usb_mouse_disconnect,
.id_table = usb_mouse_id_table,
};
// 设备驱动程序模块初始化函数
static int __init usb_mouse_init(void)
{
int result;
// 注册USB设备驱动程序
result = usb_register(&usb_mouse_driver);
if (result)
printk(KERN_INFO "USB Mouse driver registration failed\n");
else
printk(KERN_INFO "USB Mouse driver registered\n");
return result;
}
// 设备驱动程序模块退出函数
static void __exit usb_mouse_exit(void)
{
// 注销USB设备驱动程序
usb_deregister(&usb_mouse_driver);
printk(KERN_INFO "USB Mouse driver unregistered\n");
}
// 设备驱动程序模块注册
module_init(usb_mouse_init);
module_exit(usb_mouse_exit);
// 模块许可证
MODULE_LICENSE("GPL");
```
阅读全文