USB device send/receive data

后端 未结 2 1761
半阙折子戏
半阙折子戏 2021-02-02 03:04

I have implemented function to detect USB device. It works and now i need to send/read data.

I started look over a lot of obj-c sources and found only one

2条回答
  •  孤城傲影
    2021-02-02 03:50

    The article you reference has a function called WriteToDevice. One of its parameters is

    UInt8 writeBuffer[]
    

    This writeBuffer, the data that you want to send, is a C array of bytes:

    uint8_t msgLength = 3;
    uint8_t writeBuffer[msgLength];
    writeBuffer[0] = 0x41; // ASCII 'A'
    writeBuffer[1] = 0x42; // ASCII 'B'
    writeBuffer[2] = 0x43; // ASCII 'C'
    

    What bytes do you need to send? That really depends on the device at the other end -- the technical data from the manufacturer should tell you that. To pass the C-array as NSData, which is probably what pData is, you'd use:

    NSData *data = [NSData dataWithBytes:&writeBuffer length:3];
    

    The (z)wLenDone is probably what I called the msgLength, 3. C-array's have no knowledge of their own length, so most functions require the length as a separate parameter.

    As for receiving data, I would guess that happens in the matchingCallback: you use the iterator to receive the bytes and then parse them.

    ANSWER TO COMMENT:

    I'm not familiar with C#, and I'm no expert at this stuff, but maybe this will help:

    var package = new UsbSetupPacket( 
    (byte)(UsbCtrlFlags.Direction_In |
           UsbCtrlFlags.Recipient_Device | 
           UsbCtrlFlags.RequestType_Standard),  // Index
    6,                      // length of data, second phase
    0x200,                  // Request
    0,                      // RequestType
    (short)length);         // Value
    

    A few observations: know nothing of C#, but should not the package be typed to struct? RequestType is 0, so you will receive no response -- is that what you want? Or did you want to send UsbCtrlFlags.RequestType_Standard as the fourth parameter? Why send the length as a value?

    Anyway, what you do now is send the package to the USB device and see what happens.

提交回复
热议问题