MCP220 interfacing test
July 2018Description
Example code for controlling the GPIO ports on an MCP2200 device as used in the Denkovi 4 port USB relay board.
Confirmed working on Windows 7, Debian Sid and Ubuntu ARM.
Operation
To use this device, first we have to locate it. Once located, it is then claimed from the kernel and we connect to the HID endpoint provided by the device.
Commands sent to this device are 16 bytes long. The first byte is the command, and the 12th and 13th bytes are used for I/O control. The HID interface manual from Microchip describes this in detail.
Source
#!/usr/bin/python3
##
## Interfacing with the MCP2200 GPIO via USB HID. Plays with the first four GPIO ports.
##
## Used for controlling 4 port USB relay board from Denkovi.
##
import usb.core
import usb.util
import time
## find it
dev = usb.core.find(idVendor = 0x04d8, idProduct = 0x00df)
if dev is None:
print('Not found')
else:
print('Found')
## set the endpoint (output)
endpoint = dev[0][(2,0)][1]
## claim the device from the kernel
try:
if dev.is_kernel_driver_active(2):
dev.detach_kernel_driver(2)
usb.util.claim_interface(dev, 2)
print('Claimed device')
## if it fails, give it back
except:
usb.util.release_interface(dev, 2)
if not dev.is_kernel_driver_active(2):
dev.attach_kernel_driver(2)
print('Returned device')
## set device parameters (GPIOs are outputs, default off, etc)
## see http://ww1.microchip.com/downloads/en/DeviceDoc/93066A.pdf
print('Configuring device')
data = [0]*16
data[0] = 0x10
dev.write(endpoint.bEndpointAddress, data)
data = [0]*16
data[0] = 0x08 ## command
while True:
## everything off
data[11] = 0x00
data[12] = 0xFF
dev.write(endpoint.bEndpointAddress, data)
print('All off')
time.sleep(1)
## cycle through the outputs, turning them on one by one
data[12] = 0x00
data[11] = 0x01
dev.write(endpoint.bEndpointAddress, data)
print('Output one')
time.sleep(0.25)
data[11] = 0x02
dev.write(endpoint.bEndpointAddress, data)
print('Output two')
time.sleep(0.25)
data[11] = 0x04
dev.write(endpoint.bEndpointAddress, data)
print('Output three')
time.sleep(0.25)
data[11] = 0x08
dev.write(endpoint.bEndpointAddress, data)
print('Output four')
time.sleep(1)
## then turn two and four off
data[11] = 0x00
data[12] = 0x0A
print('Two+four off')
dev.write(endpoint.bEndpointAddress, data)
time.sleep(1)
Also available on Github