Skip to content

Instantly share code, notes, and snippets.

@agners
Created May 28, 2021 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agners/2a37e222694b44a6dcf34d268b7b62ce to your computer and use it in GitHub Desktop.
Save agners/2a37e222694b44a6dcf34d268b7b62ce to your computer and use it in GitHub Desktop.
Control CP2102N GPIO by using pyusb
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Stefan Agner
import os
import sys
import time
import usb
CP210X_VENDOR_SPECIFIC = 0xFF
CP210X_WRITE_LATCH = 0x37E1
# CP2102N state latch for GPIOs
# GPIO configuration
# b0000 0000 0000 0000
# |-------- Mask 0->ignore, 1->set
# |------------------ State Control 0->low, 1->high
#
# E.g. use 0x0404 to set GPIO.2 high, 0x0004 to set it low
# PyUSB control endpoint communication, see also:
# https://github.com/pyusb/pyusb/blob/master/docs/tutorial.rst
def ftdi_set_bitmode(dev, bitmask):
bmRequestType = usb.util.build_request_type(usb.util.CTRL_OUT,
usb.util.CTRL_TYPE_VENDOR,
usb.util.CTRL_RECIPIENT_DEVICE)
wIndex = bitmask
dev.ctrl_transfer(bmRequestType, CP210X_VENDOR_SPECIFIC,
wValue=CP210X_WRITE_LATCH, wIndex=wIndex)
def main():
"""Main program"""
dev = usb.core.find(custom_match = \
lambda d: \
d.idVendor==0x10c4 and
d.idProduct==0xea60 and
d.serial_number=="0002")
# Set GPIO.0 high
ftdi_set_bitmode(dev, 0x0101)
time.sleep(1)
# Set GPIO.0 low
ftdi_set_bitmode(dev, 0x0001)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment