Kevin Cuzner's Personal Blog

Electronics, Embedded Systems, and Software are my breakfast, lunch, and dinner.

Writing reusable USB device descriptors with some XML, Python, and C

A recent project required me to reuse (once again) my USB HID device driver. This is my third or fourth project using this and I had started to find it annoying to need to hand-modify a heavily-commented, self-referencing array of uint8_t's. I figured there must be a better way, so I decided to try something different.

In this post I will present a script that turns this madness, which lives in a separate file:

  2 * Device descriptor
  3 */
  4static const USB_DATA_ALIGN uint8_t dev_descriptor[] = {
  5    18, //bLength
  6    1, //bDescriptorType
  7    0x00, 0x02, //bcdUSB
  8    0x00, //bDeviceClass (defined by interfaces)
  9    0x00, //bDeviceSubClass
 10    0x00, //bDeviceProtocl
 11    USB_CONTROL_ENDPOINT_SIZE, //bMaxPacketSize0
 12    0xc0, 0x16, //idVendor
 13    0xdc, 0x05, //idProduct
 14    0x11, 0x00, //bcdDevice
 15    1, //iManufacturer
 16    2, //iProduct
 17    0, //iSerialNumber,
 18    1, //bNumConfigurations
 21static const USB_DATA_ALIGN uint8_t hid_report_descriptor[] = {
 22    HID_SHORT(0x04, 0x00, 0xFF), //USAGE_PAGE (Vendor Defined)
 23    HID_SHORT(0x08, 0x01), //USAGE (Vendor 1)
 24    HID_SHORT(0xa0, 0x01), //COLLECTION (Application)
 25    HID_SHORT(0x08, 0x01), //  USAGE (Vendor 1)
 26    HID_SHORT(0x14, 0x00), //  LOGICAL_MINIMUM (0)
 27    HID_SHORT(0x24, 0xFF, 0x00), //LOGICAL_MAXIMUM (0x00FF)
 28    HID_SHORT(0x74, 0x08), //  REPORT_SIZE (8)
 29    HID_SHORT(0x94, 64), //  REPORT_COUNT(64)
 30    HID_SHORT(0x80, 0x02), //  INPUT (Data, Var, Abs)
 31    HID_SHORT(0x08, 0x01), //  USAGE (Vendor 1)
 32    HID_SHORT(0x90, 0x02), //  OUTPUT (Data, Var, Abs)
 33    HID_SHORT(0xc0),       //END_COLLECTION
 37 * Configuration descriptor
 38 */
 39static const USB_DATA_ALIGN uint8_t cfg_descriptor[] = {
 40    9, //bLength
 41    2, //bDescriptorType
 42    9 + 9 + 9 + 7 + 7, 0x00, //wTotalLength
 43    1, //bNumInterfaces
 44    1, //bConfigurationValue
 45    0, //iConfiguration
 46    0x80, //bmAttributes
 47    250, //bMaxPower
 48    /* INTERFACE 0 BEGIN */
 49    9, //bLength
 50    4, //bDescriptorType
 51    0, //bInterfaceNumber
 52    0, //bAlternateSetting
 53    2, //bNumEndpoints
 54    0x03, //bInterfaceClass (HID)
 55    0x00, //bInterfaceSubClass (0: no boot)
 56    0x00, //bInterfaceProtocol (0: none)
 57    0, //iInterface
 58        /* HID Descriptor */
 59        9, //bLength
 60        0x21, //bDescriptorType (HID)
 61        0x11, 0x01, //bcdHID
 62        0x00, //bCountryCode
 63        1, //bNumDescriptors
 64        0x22, //bDescriptorType (Report)
 65        sizeof(hid_report_descriptor), 0x00,
 66        /* INTERFACE 0, ENDPOINT 1 BEGIN */
 67        7, //bLength
 68        5, //bDescriptorType
 69        0x81, //bEndpointAddress (endpoint 1 IN)
 70        0x03, //bmAttributes, interrupt endpoint
 71        USB_HID_ENDPOINT_SIZE, 0x00, //wMaxPacketSize,
 72        10, //bInterval (10 frames)
 73        /* INTERFACE 0, ENDPOINT 1 END */
 74        /* INTERFACE 0, ENDPOINT 2 BEGIN */
 75        7, //bLength
 76        5, //bDescriptorType
 77        0x02, //bEndpointAddress (endpoint 2 OUT)
 78        0x03, //bmAttributes, interrupt endpoint
 79        USB_HID_ENDPOINT_SIZE, 0x00, //wMaxPacketSize
 80        10, //bInterval (10 frames)
 81        /* INTERFACE 0, ENDPOINT 2 END */
 82    /* INTERFACE 0 END */
 85static const USB_DATA_ALIGN uint8_t lang_descriptor[] = {
 86    4, //bLength
 87    3, //bDescriptorType
 88    0x09, 0x04 //wLANGID[0]
 91static const USB_DATA_ALIGN uint8_t manuf_descriptor[] = {
 92    2 + 15 * 2, //bLength
 93    3, //bDescriptorType
 94    'k', 0x00, //wString
 95    'e', 0x00,
 96    'v', 0x00,
 97    'i', 0x00,
 98    'n', 0x00,
 99    'c', 0x00,
100    'u', 0x00,
101    'z', 0x00,
102    'n', 0x00,
103    'e', 0x00,
104    'r', 0x00,
105    '.', 0x00,
106    'c', 0x00,
107    'o', 0x00,
108    'm', 0x00
111static const USB_DATA_ALIGN uint8_t product_descriptor[] = {
112    2 + 14 * 2, //bLength
113    3, //bDescriptorType
114    'L', 0x00,
115    'E', 0x00,
116    'D', 0x00,
117    ' ', 0x00,
118    'W', 0x00,
119    'r', 0x00,
120    'i', 0x00,
121    's', 0x00,
122    't', 0x00,
123    'w', 0x00,
124    'a', 0x00,
125    't', 0x00,
126    'c', 0x00,
127    'h', 0x00
130const USBDescriptorEntry usb_descriptors[] = {
131    { 0x0100, 0x0000, sizeof(dev_descriptor), dev_descriptor },
132    { 0x0200, 0x0000, sizeof(cfg_descriptor), cfg_descriptor },
133    { 0x0300, 0x0000, sizeof(lang_descriptor), lang_descriptor },
134    { 0x0301, 0x0409, sizeof(manuf_descriptor), manuf_descriptor },
135    { 0x0302, 0x0409, sizeof(product_descriptor), product_descriptor },
136    { 0x2200, 0x0000, sizeof(hid_report_descriptor), hid_report_descriptor },
137    { 0x0000, 0x0000, 0x00, NULL }

Into these comment blocks which can live anywhere in the source and are somewhat more readable:

  2 * <descriptor id="device" type="0x01">
  3 *  <length name="bLength" size="1" />
  4 *  <type name="bDescriptorType" size="1" />
  5 *  <word name="bcdUSB">0x0200</word>
  6 *  <byte name="bDeviceClass">0</byte>
  7 *  <byte name="bDeviceSubClass">0</byte>
  8 *  <byte name="bDeviceProtocol">0</byte>
  9 *  <byte name="bMaxPacketSize0">USB_CONTROL_ENDPOINT_SIZE</byte>
 10 *  <word name="idVendor">0x16c0</word>
 11 *  <word name="idProduct">0x05dc</word>
 12 *  <word name="bcdDevice">0x0010</word>
 13 *  <ref name="iManufacturer" type="0x03" refid="manufacturer" size="1" />
 14 *  <ref name="iProduct" type="0x03" refid="product" size="1" />
 15 *  <byte name="iSerialNumber">0</byte>
 16 *  <count name="bNumConfigurations" type="0x02" size="1" />
 17 * </descriptor>
 18 * <descriptor id="lang" type="0x03" first="first">
 19 *  <length name="bLength" size="1" />
 20 *  <type name="bDescriptorType" size="1" />
 21 *  <foreach type="0x03" unique="unique">
 22 *    <echo name="wLang" />
 23 *  </foreach>
 24 * </descriptor>
 25 * <descriptor id="manufacturer" type="0x03" wIndex="0x0409">
 26 *  <property name="wLang" size="2">0x0409</property>
 27 *  <length name="bLength" size="1" />
 28 *  <type name="bDescriptorType" size="1" />
 29 *  <string name="wString"></string>
 30 * </descriptor>
 31 * <descriptor id="product" type="0x03" wIndex="0x0409">
 32 *  <property name="wLang" size="2">0x0409</property>
 33 *  <length name="bLength" size="1" />
 34 *  <type name="bDescriptorType" size="1" />
 35 *  <string name="wString">LED Wristwatch</string>
 36 * </descriptor>
 37 * <descriptor id="configuration" type="0x02">
 38 *  <length name="bLength" size="1" />
 39 *  <type name="bDescriptorType" size="1" />
 40 *  <length name="wTotalLength" size="2" all="all" />
 41 *  <count name="bNumInterfaces" type="0x04" associated="associated" size="1" />
 42 *  <byte name="bConfigurationValue">1</byte>
 43 *  <byte name="iConfiguration">0</byte>
 44 *  <byte name="bmAttributes">0x80</byte>
 45 *  <byte name="bMaxPower">250</byte>
 46 *  <children type="0x04" />
 47 * </descriptor>
 48 */
 51 * <include>usb_hid.h</include>
 52 * <descriptor id="hid_interface" type="0x04" childof="configuration">
 53 *  <length name="bLength" size="1" />
 54 *  <type name="bDescriptorType" size="1" />
 55 *  <index name="bInterfaceNumber" size="1" />
 56 *  <byte name="bAlternateSetting">0</byte>
 57 *  <count name="bNumEndpoints" type="0x05" associated="associated" size="1" />
 58 *  <byte name="bInterfaceClass">0x03</byte>
 59 *  <byte name="bInterfaceSubClass">0x00</byte>
 60 *  <byte name="bInterfaceProtocol">0x00</byte>
 61 *  <byte name="iInterface">0</byte>
 62 *  <children type="0x21" />
 63 *  <children type="0x05" />
 64 * </descriptor>
 65 * <descriptor id="hid" type="0x21" childof="hid_interface">
 66 *  <length name="bLength" size="1" />
 67 *  <type name="bDescriptorType" size="1" />
 68 *  <word name="bcdHID">0x0111</word>
 69 *  <byte name="bCountryCode">0x00</byte>
 70 *  <count name="bNumDescriptors" type="0x22" size="1" associated="associated" />
 71 *  <foreach type="0x22" associated="associated">
 72 *    <echo name="bDescriptorType" />
 73 *    <echo name="wLength" />
 74 *  </foreach>
 75 * </descriptor>
 76 * <descriptor id="hid_in_endpoint" type="0x05" childof="hid_interface">
 77 *  <length name="bLength" size="1" />
 78 *  <type name="bDescriptorType" size="1" />
 79 *  <inendpoint name="bEndpointAddress" define="HID_IN_ENDPOINT" />
 80 *  <byte name="bmAttributes">0x03</byte>
 81 *  <word name="wMaxPacketSize">USB_HID_ENDPOINT_SIZE</word>
 82 *  <byte name="bInterval">10</byte>
 83 * </descriptor>
 84 * <descriptor id="hid_out_endpoint" type="0x05" childof="hid_interface">
 85 *  <length name="bLength" size="1" />
 86 *  <type name="bDescriptorType" size="1" />
 87 *  <outendpoint name="bEndpointAddress" define="HID_OUT_ENDPOINT" />
 88 *  <byte name="bmAttributes">0x03</byte>
 89 *  <word name="wMaxPacketSize">USB_HID_ENDPOINT_SIZE</word>
 90 *  <byte name="bInterval">10</byte>
 91 * </descriptor>
 92 * <descriptor id="hid_report" childof="hid" top="top" type="0x22" order="1" wIndexType="0x04">
 93 *  <hidden name="bDescriptorType" size="1">0x22</hidden>
 94 *  <hidden name="wLength" size="2">sizeof(hid_report)</hidden>
 95 *  <raw>
 96 *  HID_SHORT(0x04, 0x00, 0xFF), //USAGE_PAGE (Vendor Defined)
 97 *  HID_SHORT(0x08, 0x01), //USAGE (Vendor 1)
 98 *  HID_SHORT(0xa0, 0x01), //COLLECTION (Application)
 99 *  HID_SHORT(0x08, 0x01), //  USAGE (Vendor 1)
100 *  HID_SHORT(0x14, 0x00), //  LOGICAL_MINIMUM (0)
101 *  HID_SHORT(0x24, 0xFF, 0x00), //LOGICAL_MAXIMUM (0x00FF)
102 *  HID_SHORT(0x74, 0x08), //  REPORT_SIZE (8)
103 *  HID_SHORT(0x94, 64), //  REPORT_COUNT(64)
104 *  HID_SHORT(0x80, 0x02), //  INPUT (Data, Var, Abs)
105 *  HID_SHORT(0x08, 0x01), //  USAGE (Vendor 1)
106 *  HID_SHORT(0x90, 0x02), //  OUTPUT (Data, Var, Abs)
107 *  HID_SHORT(0xc0),       //END_COLLECTION
108 *  </raw>
109 * </descriptor>
110 */

In most of my projects before this one I would have something like the first script shown above sitting in a file by itself, declaring a bunch of uint8_t arrays and a usb_descriptors[] table constant that would be consumed by my USB driver as it searched for USB descriptors. A header file that exposes the usb_descriptors[] table would also be found in the project. Any USB descriptor that had to be returned by the device would be found in this table. To make things more complex, descriptors like the configuration descriptor have to declare all of the device interfaces and so pieces and parts of each separate USB interface component would be interspersed inside of other descriptors.

I've been using this structure for some time after writing my first USB driver after reading through the Teensy driver. This is probably the only structural code that has made it all the way from the Teensy driver into all of my other code.

With this new script I've written there's no more need for manually computing how long a descriptor is or needing to modify the configuration descriptor every time a new interface has been added. All the parts of a descriptor are self-contained in the source file that defines a particular interface and can be easily moved around from project to project.

All the code for this post lives here:

` <>`__

The IoTree: An internet-connected tree

For this Christmas I decided to do something fun with my Christmas tree: Hook it up to the internet. Visit the IoTree here (available through the 1st week of January 2019):

The complete source can be found here:


The IoTree is an interface that allows anyone to control the pattern of lights shown on the small Christmas tree on my workbench. It consists of the following components:

  • My Kinetis KL26 breakout board ( This controls a string of 50 WS2811 LEDs which are zip-tied to the tree.
  • A Raspberry Pi (mid-2012 vintage) which parses pattern commands coming from the cloud into LED sequences which are downloaded to the KL26 over SPI. It also hosts a webcam and periodically throws the image back up to the cloud so that the masses can see the results of their labors.
  • A cloud server which hosts a Redis instance and python application to facilitate the user interface and communication down to the Raspberry Pi.

I'm going to go into brief detail about each of these pieces and some of the challenges I had with getting everything to work.

Bootloader for ARM Cortex-M0: No VTOR

In my most recent project I selected an ARM Cortex-M0 microcontroller (the STM32F042). I soon realized that there is a key architectural piece missing from the Cortex-M0 which the M0+ does not have: The vector table offset register (VTOR).

I want to talk about how I overcame the lack of a VTOR to write a USB bootloader which supports a semi-safe fallback mode. The source for this post can be found here (look in the "bootloader" folder):

Cross-platform driverless USB: The Human Interface Device

During my LED Wristwatch project, I decided early on that I wanted to do something different with the way my USB stuff was implemented. In the past, I have almost exclusively used libusb to talk to my devices in terms of raw bulk packets or raw setup requests. While this is ok, it isn't quite as easy to do once you cross out of the fruited plains of Linux-land into the barren desert of Windows. This project instead made the watch identify itself (enumerate) as a USB Human Interface Device (HID).

What I would like to do in this post is a step-by-step tutorial for modifying a USB device to enumerate as a human interface device. I'll start with an overview of HID, then move on to modifying the USB descriptors and setting up your device endpoints so that it sends reports, followed by a few notes on writing host software for Windows and Linux that communicates to devices using raw reports. With a little bit of work, you should be able to replace many things done exclusively with libusb with a cross-platform system that requires no drivers. Example code for this post can be found here:


One thing to note is that since I'm using my LED Watch as an example, I'm going to be extending using my API, which I describe a little bit here. The main source code files for this can be found in common/src/usb.c and common/src/usb_hid.c.


Bare metal STM32: Writing a USB driver

A couple years ago I wrote a post about writing a bare metal USB driver for the Teensy 3.1, which uses Freescale Kinetis K20 microcontroller. Over the past couple years I've switched over to instead using the STM32 series of microcontrollers since they are cheaper to program the "right" way (the dirt-cheap STLink v2 enables that). I almost always prefer to use the microcontroller IC by itself, rather than building around a development kit since I find that to be much more interesting.


One of my recent (or not so recent) projects was an LED Wristwatch which utilized an STM32L052. This microcontroller is optimized for low power, but contains a USB peripheral which I used for talking to the wristwatch from my PC, both for setting the time and for reflashing the firmware. This was one of my first hobby projects where I designed something without any prior breadboarding (beyond the battery charger circuit). The USB and such was all rather "cross your fingers and hope it works" and it just so happened to work without a problem.

In this post I'm going to only cover a small portion of what I learned from the USB portion of the watch. There will be a further followup on making the watch show up as a HID Device and writing a USB bootloader.

Example code for this post can be found here:


(mainly in common/src/usb.c and common/include/usb.h)

My objective here is to walk quickly through the operation of the USB Peripheral, specifically the Packet Memory Area, then talk a bit about how the USB Peripheral does transfers, and move on to how I structured my code to abstract the USB packetizing logic away from the application.

The LED Wristwatch: A (more or less) completed project!

About 2009 I saw an article written by Dr. Paul Pounds in which he detailed a pocketwatch he had designed that fit inside a standard pocketwatch case and used LEDs as the dial. While the article has since disappeared, the youtube video remains. The wayback machine has a cached version of the page. Anyway, the idea has kind of stuck with me for a while and so a year or so ago I decided that I wanted to build a wristwatch inspired by that idea.

Although the project started out as an AVR project, I decided after my escapades with the STM32 in August that I really wanted to make it an STM32 project, so around November I started making a new design that used the STM32L052C8 ARM Cortex-M0+ ultra-low power USB microcontroller. The basic concept of the design is to mock up an analog watch face using a ring of LEDs for the hours, minutes, and seconds. I found three full rings to be expecting a bit much if I wanted to keep this small, so I ended up using two rings: One for the hours and another for combined minutes and seconds (the second hand is recognized by the fact that it is "moving" perceptibly).

In this post I'm going to go over my general design, some things I was happy with, and some things that I wasn't happy with. I'll make some follow-up posts for the following topics:

The complete design files can be found here:

IMG_20170409_222521.jpg IMG_20170415_194157.jpg

Quick-n-dirty data acquisition with a Teensy 3.1

The Problem

I am working on a project that involves a Li-Ion battery charger. I've never built one of these circuits before and I wanted to test the battery over its entire charge-discharge cycle to make sure it wasn't going to burst into flame because I set some resistor wrong. The battery itself is very tiny (100mAH, 2.5mm thick) and is going to be powering an extremely low-power circuit, hopefully over the course of many weeks between charges.


After about 2 days of taking meter measurements every 6 hours or so to see what the voltage level had dropped to, I decided to try to automate this process. I had my trusty Teensy 3.1 lying around, so I thought that it should be pretty simple to turn it into a simple data logger, measuring the voltage at a very slow rate (maybe 1 measurement per 5 seconds). Thus was born the EZDAQ.

All code for this project is located in the repository at ` <>`__

Setting up the Teensy 3.1 ADC

I've never used the ADC before on the Teensy 3.1. I don't use the Teensy Cores HAL/Arduino Library because I find it more fun to twiddle the bits and write the makefiles myself. Of course, this also means that I don't always get a project working within 30 minutes.

The ADC on the Teensy 3.1 (or the Kinetis MK20DX256) is capable of doing 16-bit conversions at 400-ish ksps. It is also quite complex and can do conversions in many different ways. It is one of the larger and more configurable peripherals on the device, probably rivaled only by the USB module. The module does not come pre-calibrated and requires a calibration cycle to be performed before its accuracy will match that specified in the datasheet. My initialization code is as follows:

 1//Enable ADC0 module
 4//Set up conversion precision and clock speed for calibration
 5ADC0_CFG1 = ADC_CFG1_MODE(0x1) | ADC_CFG1_ADIV(0x1) | ADC_CFG1_ADICLK(0x3); //12 bit conversion, adc async clock, div by 2 (<3MHz)
 6ADC0_CFG2 = ADC_CFG2_ADACKEN_MASK; //enable async clock
 8//Enable hardware averaging and set up for calibration
10while (ADC0_SC3 & ADC_SC3_CAL_MASK) { }
11if (ADC0_SC3 & ADC_SC3_CALF_MASK) //calibration failed. Quit now while we're ahead.
12    return;
13temp = ADC0_CLP0 + ADC0_CLP1 + ADC0_CLP2 + ADC0_CLP3 + ADC0_CLP4 + ADC0_CLPS;
14temp /= 2;
15temp |= 0x1000;
16ADC0_PG = temp;
17temp = ADC0_CLM0 + ADC0_CLM1 + ADC0_CLM2 + ADC0_CLM3 + ADC0_CLM4 + ADC0_CLMS;
18temp /= 2;
19temp |= 0x1000;
20ADC0_MG = temp;
22//Set clock speed for measurements (no division)
23ADC0_CFG1 = ADC_CFG1_MODE(0x1) | ADC_CFG1_ADICLK(0x3); //12 bit conversion, adc async clock, no divide

Following the recommendations in the datasheet, I selected a clock that would bring the ADC clock speed down to <4MHz and turned on hardware averaging before starting the calibration. The calibration is initiated by setting a flag in ADC0_SC3 and when completed, the calibration results will be found in the several ADC0_CL* registers. I'm not 100% certain how this calibration works, but I believe what it is doing is computing some values which will trim some value in the SAR logic (probably something in the internal DAC) in order to shift the converted values into spec.

One thing to note is that I did not end up using the 16-bit conversion capability. I was a little rushed and was put off by the fact that I could not get it to use the full 0-65535 dynamic range of a 16-bit result variable. It was more like 0-10000. This made figuring out my "volts-per-value" value a little difficult. However, the 12-bit mode gave me 0-4095 with no problems whatsoever. Perhaps I'll read a little further and figure out what is wrong with the way I was doing the 16-bit conversions, but for now 12 bits is more than sufficient. I'm just measuring some voltages.

Since I planned to measure the voltages coming off a Li-Ion battery, I needed to make sure I could handle the range of 3.0V-4.2V. Most of this is outside the Teensy's ADC range (max is 3.3V), so I had to make myself a resistor divider attenuator (with a parallel capacitor for added stability). It might have been better to use some sort of active circuit, but this is supposed to be a quick and dirty DAQ. I'll talk a little more about handling issues spawning from the use of this resistor divider in the section about the host software.

Quick and dirty USB device-side driver

For this project I used my device-side USB driver software that I wrote in this project. Since we are gathering data quite slowly, I figured that a simple control transfer should be enough to handle the requisite bandwidth.

 1static uint8_t tx_buffer[256];
 4 * Endpoint 0 setup handler
 5 */
 6static void usb_endp0_handle_setup(setup_t* packet)
 8    const descriptor_entry_t* entry;
 9    const uint8_t* data = NULL;
10    uint8_t data_length = 0;
11    uint32_t size = 0;
12    uint16_t *arryBuf = (uint16_t*)tx_buffer;
13    uint8_t i = 0;
15    switch(packet->wRequestAndType)
16    {
17...USB Protocol Stuff...
18    case 0x01c0: //get adc channel value (wIndex)
19        *((uint16_t*)tx_buffer) = adc_get_value(packet->wIndex);
20        data = tx_buffer;
21        data_length = 2;
22        break;
23    default:
24        goto stall;
25    }
27    //if we are sent here, we need to send some data
28    send:
29...Send Logic...
31    //if we make it here, we are not able to send data and have stalled
32    stall:
33...Stall logic...

I added a control request (0x01) which uses the wIndex (not to be confused with the cleaning product) value to select a channel to read. The host software can now issue a vendor control request 0x01, setting the wIndex value accordingly, and get the raw value last read from a particular analog channel. In order to keep things easy, I labeled the analog channels using the same format as the standard Teensy 3.1 layout. Thus, wIndex 0 corresponds to A0, wIndex 1 corresponds to A1, and so forth. The adc_get_value function reads the last read ADC value for a particular channel. Sampling is done by the ADC continuously, so the USB read doesn't initiate a conversion or anything like that. It just reads what happened on the channel during the most recent conversion.

Host software

Since libusb is easy to use with Python, via PyUSB, I decided to write out the whole thing in Python. Originally I planned on some sort of fancy gui until I realized that it would far simpler just to output a CSV and use MATLAB or Excel to process the data. The software is simple enough that I can just put the entire thing here:

 1#!/usr/bin/env python3
 3# Python Host for EZDAQ
 4# Kevin Cuzner
 6# Requires PyUSB
 8import usb.core, usb.util
 9import argparse, time, struct
11idVendor = 0x16c0
12idProduct = 0x05dc
13sManufacturer = ''
14sProduct = 'EZDAQ'
16VOLTS_PER = 3.3/4096 # 3.3V reference is being used
18def find_device():
19    for dev in usb.core.find(find_all=True, idVendor=idVendor, idProduct=idProduct):
20        if usb.util.get_string(dev, dev.iManufacturer) == sManufacturer and \
21                usb.util.get_string(dev, dev.iProduct) == sProduct:
22            return dev
24def get_value(dev, channel):
25    rt = usb.util.build_request_type(usb.util.CTRL_IN, usb.util.CTRL_TYPE_VENDOR, usb.util.CTRL_RECIPIENT_DEVICE)
26    raw_data = dev.ctrl_transfer(rt, 0x01, wIndex=channel, data_or_wLength=256)
27    data = struct.unpack('H', raw_data)
28    return data[0] * VOLTS_PER;
30def get_values(dev, channels):
31    return [get_value(dev, ch) for ch in channels]
33def main():
34    # Parse arguments
35    parser = argparse.ArgumentParser(description='EZDAQ host software writing values to stdout in CSV format')
36    parser.add_argument('-t', '--time', help='Set time between samples', type=float, default=0.5)
37    parser.add_argument('-a', '--attenuation', help='Set channel attentuation level', type=float, nargs=2, default=[], action='append', metavar=('CHANNEL', 'ATTENUATION'))
38    parser.add_argument('channels', help='Channel number to record', type=int, nargs='+', choices=range(0, 10))
39    args = parser.parse_args()
41    # Set up attentuation dictionary
42    att = args.attenuation if len(args.attenuation) else [[ch, 1] for ch in args.channels]
43    att = dict([(l[0], l[1]) for l in att])
44    for ch in args.channels:
45        if ch not in att:
46            att[ch] = 1
48    # Perform data logging
49    dev = find_device()
50    if dev is None:
51        raise ValueError('No EZDAQ Found')
52    dev.set_configuration()
53    print(','.join(['Time']+['Channel ' + str(ch) for ch in args.channels]))
54    while True:
55        values = get_values(dev, args.channels)
56        print(','.join([str(time.time())] + [str(v[1] * (1/att[v[0]])) for v in zip(args.channels, values)]))
57        time.sleep(args.time)
59if __name__ == '__main__':
60    main()

Basically, I just use the argparse module to take some command line inputs, find the device using PyUSB, and spit out the requested channel values in a CSV format to stdout every so often.

In addition to simply displaying the data, the program also processes the raw ADC values into some useful voltage values. I contemplated doing this on the device, but it was simpler to configure if I didn't have to reflash it every time I wanted to make an adjustment. One thing this lets me do is a sort of calibration using the "attenuation" values that I put into the host. The idea with these values is to compensate for a voltage divider in front of the analog input in order so that I can measure higher voltages, even though the Teensy 3.1 only supports voltages up to 3.3V.

For example, if I plugged my 50%-ish resistor divider on channel A0 into 3.3V, I would run the following command:

1$ ./ezdaq 0
2Time,Channel 0

We now have 1.799 for the "voltage" seen at the pin with an attenuation factor of 1. If we divide 1.799 by 3.3 we get 0.545 for our attenuation value. Now we run the following to get our newly calibrated value:

1$ ./ezdaq -a 0 0.545 0
2Time,Channel 0

This process highlights an issue with using standard resistors. Unless the resistors are precision resistors, the values will not ever really match up very well. I used 4 1meg resistors to make two voltage dividers. One of them had about a 46% division and the other was close to 48%. Sure, those seem close, but in this circuit I needed to be accurate to at least 50mV. The difference between 46% and 48% is enough to throw this off. So, when doing something like this with trying to derive an input voltage after using an imprecise voltage divider, some form of calibration is definitely needed.



After hooking everything up and getting everything to run, it was fairly simple for me to take some two-channel measurements:

1$ ./ezdaq -t 5 -a 0 0.465 -a 1 0.477 0 1 > ~/Projects/AVR/the-project/test/charge.csv

This will dump the output of my program into the charge.csv file (which is measuring the charge cycle on the battery). I will get samples every 5 seconds. Later, I can use this data to make sure my circuit is working properly and observe its behavior over long periods of time. While crude, this quick and dirty DAQ solution works quite well for my purposes.