A good workflow and build system with OpenSCAD and Makefiles

This is just a quick post, the blog isn’t dead, I’ve just been busy. I’ve put together a reasonable OpenSCAD workflow that works for me and might work for others.

OpenSCAD is a 3D solid modeling program that performs computational geometry and is frequently used for describing models for 3D printing. It is a description language (and the program for compiling it) for solid shapes, procedurally generating them from primitive shapes like cubes, spheres, etc and mathematical operations such as unions and differences. Being fully text-based, it begs to live in version control and is usable through a CLI, leading to being able to be fully scripted. I started using OpenSCAD with the LED watch project and have since developed a fairly simple build system. It consists of two pieces:

  1. Special comments in a top-level OpenSCAD file designating which modules to build into STL files.
  2. A makefile

I’ll start with the Makefile. It’s really straightforward and identical for each of my projects:

In my top-level scad file, I then mark my top-level modules with a special comment:

The way this works is pretty straightforward. Just run “make” with no arguments:

  1. The makefile scans the top-level and creates a list of the names of the modules to be built into stl files. The suffix “.scad” is appended to each module, forming a list the top-level “all” targets
  2. For each of these targets, it generates an scad file that includes the top-level file and instantiates the target module
  3. When invoking openscad to build the stl from the target’s scad file, a makefile deps file is generated by openscad. This file is included in the makefile so that later, when a dependency of the particular module changes, the stl will be updated according to the Makefile logic.

Armed with an STL, we can now go ahead and print. Typically, I put a fully assembled version of the top-levels in the top-level instantiation (since that isn’t instantiated when including the file in the target’s scad file) and point OpenSCAD directly to the top-level when editing.

The only non-automated part of this which is hard to check into version control is slicing the model. However, that’s typically dictated per-print (and varies with wear and tear on the printer, the filament or resin used, etc), so I’m less motivated to figure out a good way to track it.

I have several examples of this workflow on github:

AVR TPI Programming With usbasp For Dummies

There is an odd famine of information about this particular subject available in text form. If you google “usbasp tpi” and things like it, you’ll find posts on the avr forums filled with incorrect information and schematics. This post is an attempt to remedy this.

I intend to show exactly the following, no more and no less:

  1. What is TPI?
  2. How to reprogram your usbasp to be capable of TPI.
  3. How to wire up a TPI-only microcontroller (such as the ATTiny20) to the usbasp’s ISP interface.
  4. Why you might pick one of these newer devices, rather than sticking with the tried-and-true ISP AVRs.

Continue reading

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:

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

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:


Continue reading

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

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 (http://github.com/kcuzner/kl2-dev). 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.

Continue reading

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):


Continue reading

Building a USB bootloader for an STM32

As my final installment for the posts about my LED Wristwatch project I wanted to write about the self-programming bootloader I made for an STM32L052 and describe how it works. So far it has shown itself to be fairly robust and I haven’t had to get out my STLink to reprogram the watch for quite some time.

The main object of this bootloader is to facilitate reprogramming of the device without requiring a external programmer. There are two ways that a microcontroller can accomplish this generally:

  1. Include a binary image in every compiled program that is copied into RAM and runs a bootloader program that allows for self-reprogramming.
  2. Reserve a section of flash for a bootloader that can reprogram the rest of flash.

Each of these ways has their pros and cons. Option 1 allows for the user program to use all available flash (aside from the blob size and bootstrapping code). It also might not require a relocatable interrupt vector table (something that some ARM Cortex microcontrollers lack). However, it also means that there is no recovery without using JTAG or SWD to reflash the microcontroller if you somehow mess up the switchover into the bootloader. Option 2 allows for a fairly fail-safe bootloader. The bootloader is always there, even if the user program is not working right. So long as the device provides a hardware method for entering bootloader mode, the device can always be recovered. However, Option 2 is difficult to update (you have to flash it with a special program that overwrites the bootloader), wastes unused space in the bootloader-reserved section, and also requires some features that not all microcontrollers have.

Because the STM32L052 has a large amount of flash (64K) and implements the vector-table-offset register (allowing the interrupt vector table to be relocated), I decided to go with Option 2.

Example code for this post can be found here:



Continue reading

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.


Continue reading

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.

LED Wristwatch with USB

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.

Continue reading

Arranging components in a circle with Kicad

I’ve been using kicad for just about all of my designs for a little over 5 years now. It took a little bit of a learning curve, but I’ve really come to love it, especially with the improvements by CERN that came out in version 4. One of the greatest features, in my opinion, is the Python Scripting Console in the PCB editor (pcbnew). It gives (more or less) complete access to the design hierarchy so that things like footprints can be manipulated in a scripted fashion.

In my most recent design, the LED Watch, I used this to script myself a tool for arranging footprints in a circle. What I want to show today was how I did it and how to use it so that you can make your own scripting tools (or just arrange stuff in a circle).

The python console can be found in pcbnew under Tools->Scripting Console.

Step 1: Write the script

When writing a script for pcbnew, it is usually helpful to have some documentation. Some can be found here, though I mostly used “dir” a whole bunch and had it print me the structure of the various things once I found the points to hook in. The documentation is fairly spartan at this point, so that made things easier.

Here’s my script:

There are several arguments to this function: a list of reference designators ([“D1”, “D2”, “D3”] etc), the angle at which the first component should be placed, the position in mils for the center of the circle, and the radius of the circle in mils. Once the function is invoked, it will find all of the components indicated in the reference designator list and arrange them into the desired circle.

Step 2: Save the script

In order to make life easier, it is best if the script is saved somewhere that the pcbnew python interpreter knows where to look. I found a good location at “/usr/share/kicad/scripting/plugins”, but the list of all paths that will be searched can be easily found by opening the python console and executing “import sys” followed by “print(sys.path)”. Pick a path that makes sense and save your script there. I saved mine as “placement_helpers.py” since I intend to add more functions to it as situations require.

Step 3: Open your PCB and run the script

Before you can use the scripts on your footprints, they need to be imported. Make sure you execute the “Read Netlist” command before continuing.

The scripting console can be found under Tools->Scripting Console. Once it is opened you will see a standard python (2) command prompt. If you placed your script in a location where the Scripting Console will search, you should be able to do something like the following:

Now, pcbnew may not recognize that your PCB has changed and enable the save button. You should do something like lay a trace or some other board modification so that you can save any changes the script made. I’m sure there’s a way to trigger this in Python, but I haven’t got around to trying it yet.


Hopefully this brief tutorial will either help you to place components in circles in Kicad/pcbnew or will help you to write your own scripts for easing PCB layout. Kicad can be a very capable tool and with its new expanded scripting functionality, the sky seems to be the limit.

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:


Continue reading