STM32 USB CDC类在LINUX环境下免驱动通讯

使用lsusb -v命令常看设备信息等主要获取设备号和产品号

  idVendor           0x0483 STMicroelectronics
  idProduct          0x5740 STM32F407

接着使用libusb库可以直接读取接收到的信息  https://libusb.info/

下面是简单的DEMO


#include 
#include  
#include "libusb.h"
#include "sys.h"

#define USB_VID         0x0483          //USB设备的产商ID
#define USB_PID         0x5740         //USB设备的产品ID
#define EPIN_ADDR       0X81
#define EPOUT_ADDR      0X01

static libusb_device_handle *dev_handle = NULL;


static void print_devs(libusb_device **devs)
{
	libusb_device *dev;
	int i = 0, j = 0;
	uint8_t path[8]; 

	while ((dev = devs[i++]) != NULL) {
		struct libusb_device_descriptor desc;
		int r = libusb_get_device_descriptor(dev, &desc);
		if (r < 0) {
			fprintf(stderr, "failed to get device descriptor");
			return;
		}

		printf("%04x:%04x (bus %d, device %d)",
			desc.idVendor, desc.idProduct,
			libusb_get_bus_number(dev), libusb_get_device_address(dev));

		r = libusb_get_port_numbers(dev, path, sizeof(path));
		if (r > 0) {
			printf(" path: %d", path[0]);
			for (j = 1; j < r; j++)
				printf(".%d", path[j]);
		}
		printf("\n");
	}
}

int main(void)
{
	libusb_device **devs;
	int r,ret;
	ssize_t cnt;
	unsigned char buf[100];
	r = libusb_init(NULL);
	if (r < 0)
	return r;
    dev_handle = libusb_open_device_with_vid_pid(NULL, USB_VID, USB_PID);
	if(dev_handle == NULL){
        perror("Cannot open device\n");
    }else{
        printf("Device Opened\n");
    }
	ret = libusb_kernel_driver_active(dev_handle, 0);
	if (ret == 1)
	{
		libusb_detach_kernel_driver(dev_handle, 0);
		printf("driver error\n");
	}
	r=libusb_bulk_transfer(dev_handle,EPIN_ADDR,buf,10,NULL,0);
	if(r<0)
	{
		DBG("%s\n",libusb_error_name(r));
	}
	printf("receive : %s\n",buf);
	

	libusb_exit(NULL);

}
编译命令

g++  main.cpp  -o listdevs -I/usr/include/libusb-1.0 -L/usr/lib -lusb-1.0

运行结果

sudo ./listdevs 

Device Opened
receive : hello

目前只实现了读取接下来实现写

你可能感兴趣的:(STM32 USB CDC类在LINUX环境下免驱动通讯)