xiongyihui / notes

Notes
https://xiongyihui.github.io/notes/
3 stars 0 forks source link

XMOS Device Control via USB #9

Open xiongyihui opened 6 years ago

xiongyihui commented 6 years ago

XMOS's Device Control is used to configure and control an XMOS device from a host over USB, SPI, I2C or xSCOPE. We are making a USB microphone array, so USB is used here.

A host running Windows, Linux or macOS can access the device using libusb. For Windows, the usb device requires a driver. Fortunately, there is a handy tool called Zadig which can help us install a driver for the device.

We can use libusb's python library pyusb to access the device. Here is a snippet:


import usb.core
import usb.util

class UsbControlDevice:
    TIMEOUT = 100

    def __init__(self, dev):
        self.dev = dev

    def write(self, data):

        self.dev.ctrl_transfer(
            usb.util.CTRL_OUT | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE,
            0, 0x0, 0x1C, data)

    def read(self):
        return self.dev.ctrl_transfer(
            usb.util.CTRL_IN | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE,
            0, 0x80, 0x1C, 4, self.TIMEOUT)

    def version(self):
        return self.dev.ctrl_transfer(
            usb.util.CTRL_IN | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE,
            0, 0x80, 0, 1, self.TIMEOUT)

    def close(self):
        """
        close the interface
        """
        # usb.util.dispose_resources(self.dev)
        pass

def find(vid=0x20b1, pid=0x0011):
    dev = usb.core.find(idVendor=vid, idProduct=pid)
    if not dev:
        return

    return UsbControlDevice(dev)

dev = find()
print dev.version()
dev.write([0] * 4 + [1, 0, 0, 0] + [0] * 4)
print dev.read()