且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将VB.Net应用程序与USB端口连接

更新时间:2023-02-08 18:01:33

您将USB端口视为标准串行端口港口.创建 SerialPort类的实例 [
You treate the USB port as it is was a standard serial port. Create an instance of the SerialPort class[^], and handle the incoming data:
    SerialPort sensor = new SerialPort("COM6");
    sensor.BaudRate = 9600;
    sensor.Parity = Parity.None;
    sensor.StopBits = StopBits.One;
    sensor.DataBits = 8;
    sensor.Handshake = Handshake.None;
    sensor.DataReceived += new SerialDataReceivedEventHandler(Sensor_DataReceived);
    sensor.Open();
    Console.WriteLine("Press any key to continue...");
    Console.WriteLine();
    Console.ReadKey();
    sensor.Close();
    ....


private static void Sensor_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
    SerialPort sensor = (SerialPort)sender;
    string data = sensor.ReadExisting();
    Console.Write(data);
    }


那是因为您试图像对待串行端口或并行端口一样将USB端口视为端口.看看USB代表什么:通用串行总线. USB不是端口,而是BUS,与计算机内部的扩展槽不同.

您与连接到端口的设备进行交互,而不是与端口本身进行交互.您如何执行此操作取决于设备公开的接口.该设备很可能将自己作为串行端口仿真公开,您可以像使用SerialPort类的任何其他串行端口设备一样使用它.

但是,如果您的设备不这样做,则必须从设备制造商那里获取SDK,以使您的代码与之交互. Phidg​​ets设备(http://www.phidgets.com)就是这种情况.
That''s because you''re trying to treat the USB port as a port like you would a serial or parallel port. Look at what USB stands for: Universal Serial BUS. A USB is not a port, but a BUS, not unlike the expansion slots inside your computer.

You interface with the device attached to the port, not the port itself. How you do this depends on what interface the device exposes. It''s entirely possible that the device exposes itself as serial port emulation and you can get at it just like any other serial port device using the SerialPort class.

However, if your device doesn''t do that, you''ll have to get an SDK from the manufacturer of the device to let your code interface with it. This is the case with Phidgets devices (http://www.phidgets.com).