picture home | pixelblog | qt_tools

omino code blog

We need code. Lots of code.
entries for category "wbl weird blinking lights"
David Van Brink // Sat 2008.03.8 00:33 // {wbl weird blinking lights}

Retro USB MIDI Device V


Whoo-eee, the MIDI Over USB spec is a bit nightmarish.


Sometimes with a spec, you can just tell what happened: Too many people in the room! The USB MIDI Spec describes some complicated way to express the internal topology of hypothetical musical devices using a tangle of nomenclature involving embedded and external jacks, pins, elements, entities, functions, and converters.

To add insult to ignorance, Chapter 8: Glossary defines useful terms like “Roland GS” and “Yamaha XG”, but remains silent on “jack”, “pin”, “element”, “entity”, “function”, and “converter”.

(To be sure, that’s my old world, at Apple, and Staccato, and my stint on the MIDI Manufacturer’s Association technical board. And if you think you’ve seen engineers argue over pointless details and speculative features, well, I assure you, musicians-who-have-engineering-day-jobs are the worst.)

Ok, the spec is a mess. The best way to figure this out, I think, is to look at something that works, and copy it. Under Mac OS X is a handy tool called USB Prober, installed with XCode.

Unfortunately, USB Prober doesn’t know about MIDI device descriptors. Fortunately, it lets you dump a hex file, and, fortunately, I like to write gobs of Perl code to parse the mess. Here’s the reference-relationship of the MIDI-specific descriptors for two devices which were handy.

The tombstones are USB “endoint descriptors”, and the roundrects are “jack descriptors”, each of which is either EMB or EXT. (Don’t try to attach meanings to EMB or EXT, it only confuses the puzzle. Really.) The Photon X25 gadget has two 5-pin MIDI plugs, and a built-in keyboard.

The Trigger Finger has one built-in drumpad controller, and one 5-pin MIDI plug.

A pattern begins to emerge! Not tidy, and not symmetric, but at least imitable.

And if you just love looking at data, the Perl descriptor dump is presented below.


Tracking Gamed Ankh and the MetaReal World of David Van Brink // Mon 2008.03.10 20:298:29 pm

[…] Ankh in 1984, because i have never seen the box until now, (pic above). The creator turns out to be David Van Brink a hardware hacker amongst other things. only props go out. They dont make em like they used […]

oh, i dont know. what do you think?

David Van Brink // Fri 2008.03.7 08:35 // {wbl weird blinking lights}

Retro USB MIDI Device IV

Why Use USB For This

A pointless little ramble rationalizing the design choices so far…


oh, i dont know. what do you think?

David Van Brink // Fri 2008.03.7 00:23 // {wbl weird blinking lights}

Retro USB MIDI Device III

Microchip’s Reference USB Implementation

Microchip’s PICDEM FS USB Demo Board comes with several working example projects which use its on-board USB port. (On a side note, I’m relieved that Microchip’s developer product names are not significantly better than those foisted by my own employer, Altera.) The board is based on a PIC 18F4550.

Their demo is not really an API or a platform, but it is a starting point that actually works. To understand their approach, let’s dive right in from the top.

void main(void)
    InitializeSystem ();
        USBTasks();         // USB Tasks
        ProcessIO();        // See user\user.c & .h
    } //end while
} //end main

Bravo. That’s just what main should look like!

Two features are immediately clear. First, it is a polled system, and the main loop runs forever. Second, they are using globals to manage their state. (Else, we’d see some kind of arguments passed to the several routines here.) These are both perfectly respectable and traditional approaches for an embedded system.

Their demo communicates with a Windows app:

The demo board sends some analog readings (temperature and trim-pot position) up, periodically, which the app displays. If you click the buttons on the app, the board blinks its LEDs.

Here’s part of ProcessIO, which listens for commands.

void ProcessIO(void)
    if((usb_device_state < CONFIGURED_STATE)||(UCONbits.SUSPND==1)) 

}//end ProcessIO

void ServiceRequests(void)
        counter = 0;
         case UPDATE_LED:
                // LED1 & LED2 are used as USB event indicators.
                if(dataPacket.led_num == 3)
                    mLED_3 = dataPacket.led_status;
                    counter = 0x01;
                }//end if
                else if(dataPacket.led_num == 4)
                    mLED_4 = dataPacket.led_status;
                    counter = 0x01;
                }//end if else
            case RESET:

        }//end switch()
    }//end if
}//end ServiceRequests

So, blink the lights, and, if the USB connection isn’t not running (to speak as the code is written), check for activity and respond to it.

Neat and easy!


Ok. I’ve glossed it up a bit.

When you first plug in the demo board, running the USB firmware, Windows says, “Found new hardware, Microchip USB Demo Board“, and demands that you install a driver for it. Not the worst thing, but annoying. That’s because the demo uses its own unique and specific protocol to communicate between the app and the board. Nothing wrong with that, it is a perfectly respectable approach for a vertical application.

I was wondering where it got Microchip USB Demo Board. Oddly, searching the source for that text failed. Ah. Ugh:

rom struct{byte bLength;byte bDscType;word string[33];}sd002={
'M','i','c','r','o','c','h','i','p',' ','U','S','B',' ','D','e','m','o',' ','B','o','a','r','d',' ','(','C',')',' ','2','0','0','7'};

Yes, you’re seeing it right. This is part of the USB descriptor. It’s little-endian unicode, preceded by a length, and all quite cleverly contrived to sit in ROM ready for spooling straight out to the host.

But no fun at all to edit!

Resisting Perfection

My initial urge is to open up a blank editor, and start implementing a complete general purpose USB platform. That’s what I usually do in my code, create platforms for some domain… but I shall resist in this case. The goal is to get the these old buttons to send musical notes…


…and that’s all!

So, I took their 15 C files, and pasted them into usbAll.c. Then I took their 15 H files, and put them into usbAll.h. There. Nice and tidy. I can ignore their ugly globals, and benefit from their 3 years of bug fixes (like “Dont hang if host asks for more data than we said was available”).

I’ll just extract and generalize a little at a time, when it makes my work easier.

Starting with:

   CStringToUsbDescriptor("Omino USB MIDI Controller v0.1");

Next up, Why USB for this project?

oh, i dont know. what do you think?

David Van Brink // Mon 2008.03.3 22:36 // {wbl weird blinking lights}

Retro USB MIDI Device II

USB in Three Longish Paragraphs

Universal Serial Bus is a specification for an inexpensive medium-bandwidth wired communication system between a host and several devices. The direction of communication is always host-centric: “Out” means data from the host to a device, and “In” means data going to the host from a device.

Each device is organized in terms of configurations, interfaces, and endpoints. A device is identified by its name, and vendor and product IDs (VID and PID). You can buy a VID from usb.org. The device may offer one more configurations; if there’s more than one, the host will tell it which to use. Each configuration is composed of several interfaces. An interface declares its name, and its class and subclass, for example, Audio/MIDI. Each interface is then composed of some number of endpoints. An endpoint is a communications channel within the bus, between the host and a device, much akin to port numbers on an IP stack.

When the host notices a new device, by a clever system of electrical sensing and pulldown resistors and such, it sends a few query packets to endpoint zero, which is always reserved for this “enumeration” query process. The queries are all requests for descriptors, either a device descriptor or a configuration descriptor (which contains interface and endpoint descriptors within), and so on. Quite often these descriptors are slugs of ROM data on the device. If it recognizes the class and subclass of one of the interfaces, the host might send additional class-specific setup commands. Also, the host may engage in more intimate communication, such as allowing the device to control the on-screen cursor, or offering it to the user as an available printer. Some interface classes are “well known” and have drivers built into the host. Speakers and keyboards are both supported intrinsically by desktop computer hosts. More obscure devices, however, require a special driver to be installed.


It feels a bit ornate, but it does have plenty of flexibility.

Apparently, neither Windows nor Mac OS X provides a fully general-purpose USB API, but, rather, requires customized drivers for each device class. Oh, a few are built in, like “human interface device” for mouse and keyboard and others. But it would be straightforward to provide truly generic API like:

   void ReadUsbEndpoint(EndpointHandle, char *buffer, int bufferSize, int *bytesGot);
   void WriteUsbEndpoint(EndpointHandle, char *buffer, int bytesToWrite);

Obviously, one would be well-advised to understand the device before conversing with it. But at present, one is required to write low-level drivers for, clearly, high level data manipulation.

Fortunately, my project is to create a MIDI controller. The MIDI class and subclass (01/03) is well-supported intrinsically on Mac OS X and Windows. It’ll “just work”.

USB References

http://www.usb.org/developers/docs/ has the spec. Chapter 9 documents the standard descriptors. This is the main chapter of interest to a software developer.

http://www.usb.org/developers/devclass_docs/ has some of the class-specific specs, including the Streaming MIDI spec.

http://www.colinkraft.com/macusbhid/macusbhid.php contains the laments of another lost would-be usb developer, and some tips for Mac OS X API’s.

Next up, Microchip’s reference implementation for USB.

Aaron // Tue 2008.03.4 10:4910:49 am

Very nice! Keep it coming!

Universal Life Church // Thu 2008.03.6 12:0912:09 pm

“Obviously, one would be well-advised to understand the device before conversing with it. But at present, one is required to write low-level drivers for, clearly, high level data manipulation.”

I’m not sure I follow. Don’t you need to know the config of a device before writing code for it?

David Van Brink // Thu 2008.03.6 15:473:47 pm

“Don’t you need to know the config of a device before writing code for it?”


It’s just that the communication *could* be done from user-level API rather than driver-level. I wish Mac and Win provided such an API.

Today, if you have a vertical application with some custom USB hardware, you will likely need to write a custom driver in addition to your custom application, just to talk to your widget.

(Unless you piggyback on serial, or HID, or some other existing protocol.)

oh, i dont know. what do you think?

David Van Brink // Sun 2008.03.2 22:56 // {wbl weird blinking lights}

Retro USB MIDI Device I

Last year I got a little bit serious with the WBLs. Serious enough to have some boards made. My little 2″ square, 5-LED platform has proved handy for halloween costumes and desert beacons.


But now I’d like to tackle something a little bit more ambitious: A completely custom USB/MIDI input device.

My SO works for Lick Observatories, and occasionally comes across interesting discarded equipment and gear, like this:


I thought it would make a wonderful little music controller or sequencer. Retro and such. And it’s even labeled right on the front: SEQ NO.


I took a USB class at Microchip’s training center in Santa Clara. Never done that before. Nice way to spend a day, actually. First half was lecture about USB in general, second half we did some exercises with MPLAB IDE, and a demo board with USB and a PIC 18F4550 chip. Their training rep, David Stokes, did a fine job with both, very pragmatic. Relatively L-I-T-E light, but enough to feel comfortable poking around with the rest. Got to keep the board and the programmer.

Next up, a short explanation of USB.

oh, i dont know. what do you think?

David Van Brink // Sun 2007.08.19 23:27 // {wbl weird blinking lights}

Beacon WBL

This next WBL is for a very specific purpose: finding one’s way home at night. It is of course intended for stationary deployment at an encampment in the flat, flat desert. It consists of 32 high brightness LEDs, in four groups of 8, blinking in patterns.

This was exciting, as I finally got to use a “transistor” in a project. Long ago, Dolphin (a man of many talents & avocations, but, alas, no public web presence) sent me some doodles explaining how to blink lots of LEDs from a pic chip.

                           (12V)            (5V)   
 +-[- Car Battery +]-[FUSE]-+-[5V regulator]--[V+   PIC*  Out   V-]---RTN
 |                          |        |                      |
RTN                         |       RTN                     |
             +--[10u Tant]--+                               > Rb = 220, 1/4W
             |              +-VVVVV-->|-->|-->|--+          > (~3.5V total 
            RTN             |                    |          > drop at 15mA)
                            +-VVVVV-->|-->|-->|--+          |
                            |                    |          |
                            +-VVVVV-->|-->|-->|--+        __b__
                                                 |         / \
                                                 +------c-/   V-e-----RTN

Ah, we don’t illustrate like that any more, hmm?

I implemented his circuit. Radio Shack had a packet with 15 “2n2222-like transistors” for a buck or two; it had 2n2222’s, 2n4401’s, and 2n3904’s in it. They all seem to work the same, in this application. I assembled the circuit shown below, except with the transistor driver duplicated four times attached to the PIC12F509.

And here’s the beacon, running happily, if not for very long, on a 9v battery. The picture doesn’t really express how bright the thing is. Piercing. I set it on the driveway and it was impressively bright from a block away. I bet it will be visible for a mile or more on the playa. A car battery will be able to power it for about a month of evenings…

The nifty modules are sold by Sure Electronics on eBay for $3 including shipping from China. Look for “Fantastic High Brightness LED Cluster”. Just add 9 or 12 volts straight in.

oh, i dont know. what do you think?

David Van Brink // Sat 2007.08.11 21:30 // {solar garden light wbl weird blinking lights}

WBL: Production For Use

Solar Powered WBL

Here is my first completed solar-powered WBL.

I took the solar garden light apart and carved away much of the plastic around the battery and circuit board. This is epoxied and screwed to a plastic jar lid; the underside has a rectangular hole to replace the cheap rechargeable AA cell. The solar cell is placed on a “chip-tube” signpost, and angled slightly upward.

It’s been running reliably, nightly, for a few weeks now. (Zener diode did the trick! No more burnouts.)

Here it is at night, after a full day’s charge. It’s a 15 second time exposure, you have to imagine it blinking inside the plastic peanut-butter jar.

Recycle, Reuse

The whole point of this “production for use” series of WBLs is to use discarded materials. Old bendy straws and styrofoam packing peanuts are evident above. It turns out that, for this project, translucent objects take on quite a mystique! Straws, salsa-cups from lunch, discarded syringe holders, thin styrofoam sheets, pudding and applesauce cups, and even burnt-out incancdescent bulbs are all figuring in. But plastic bottles are the best.

Here’s the frustrating part: trying to get the labels off. Ironically, Odwalla bottles use some kind of impervious glue, shown here glinting in the sunlight and clinging accidentally to dirt. And nail polish remover labeling is (perhaps unsurprisingly) immune to nail polish remover. But the Elmer’s glue labels? They just fall off when poked.

I’ve tried soaking in water, rubbing alcohol, and “goo gone” with various levels of success. More research is needed on this aspect of reuse.

Myles // Wed 2007.12.12 07:487:48 am

to remove any lable from a container, paint with household ammonia, then cover with some plastic wrap. Wait 10 minutes or less, the lable will peel off. This also works with stickers on cars.

David Van Brink // Mon 2007.12.17 10:0710:07 am

Awesome! Thanks for the tip! I will try the Ammonia Method & report back.

oh, i dont know. what do you think?

David Van Brink // Wed 2007.07.11 23:16 // {wbl weird blinking lights}

My First Board-Bringup: the wbl05a

Since I want to build a handful of WBLs — that is, weird blinking light devices — and have settled, more or less, on using the PIC 12F509 as a platform and have grown weary of clipping little wires and soldering them to radioshack breadboards it was time to try out custom circuit boards. All the cool kids are doing clever laser printer hacks to make printed circuit boards but, well, I have a day job and no desire to mess with acids and stuff. The parts-load for LEDs alone is enough, thank you, I don’t want a chemistry set too. So I ordered some boards from Pad2Pad in late June. They just arrived today.

These are 1.6″ x 1.6″. It took a couple of retries before the autorouting algorithm in Pad2Pad’s free software both succeeded and happened to avoid the areas outside my hexagon. (I wanted the option to shave off the corners, though more likely I’ll drill holes there for mounting.)

On to board bringup. That’s jargon for “make the board go” that I’ve overheard my hardware friends say. There’s only about 15 connections on the board, so it was easy to verify that the circuit was probably what I wanted.

Next, to stuff the board. That’s hardware-guy jargon for “put the parts together.” This must be old hat to real hardware folk, but I was pretty pleased to think of a way to hold in all the little two-pin headers for soldering.

And a resistor pack and an 8-pin socket and… I guess it’s a pretty simple board. Still, thankfully it worked perfectly the first time.


This will be fun.

(Cost: $100.80+$15 shipping, for 19 boards, 2 layer with silkscreen & solder mask. 3 week delivery.)

Daniel Jalkut // Thu 2007.07.12 08:208:20 am

Wow! I love how you claim not to be a hardware guy. Leave some claiming for the rest of us :)

weird of wbl // Wed 2007.08.8 06:056:05 am

“we are not a hardware company”

how come I don’t get automatic emails when these postings happen? more to the point, where is my free sample?

weird of wbl // Wed 2007.08.8 06:066:06 am

oh and btw, this is beautiful- I’ve been messing with PICs as well… haven’t ordered any boards yet, just using prototype, but then again, soldering isn’t popular around fresh DNA

oh, i dont know. what do you think?

David Van Brink // Mon 2007.07.9 23:57 // {wbl weird blinking lights}


I’ve been, aah, shopping for parts a bit lately. Here’s some of the places I’ve shopped and my impressions.

Parts: Santa Cruz Electronics
Walk-in, Santa Cruz, California, USA

I want to like them, I want to support our local independent shoppe, but tragically their components aisle is poorly stocked and terribly cramped and disorganized. It’s fun to find dusty hanging cards with an 1802 processor, or a 27c64, but apparently they can’t be bothered to restock the 7805’s. And of course they have nothing so exotic as a PIC chip or a high brightness white LED. They’re ok to pick up a quick spool of wire or the odd DB-9 connector or what not, and I found some expensive zener diodes of almost the value I needed.

Parts: Digi-Key
Ships from USA.

An old classic; in high school I ordered parts from their paper catalog: got little touch switches and trim pots to make a 555-based monophonic organ. All online now, of course. Although they do carry nearly everything — including my own company’s FPGA parts! — I find their online catalog a bit tricky sometimes… I know there must be a ZIF socket available for less that $30 but darned if their search lets me find it. Same for two pin molex receptacles…

Seems to take about 9 days to arrive at cheapest shipping option.

Parts: Mouser
Ships from USA.

A lot like Digi-Key but I find their online catalog a bit easier to navigate. Prices nearly identical. Shipping options include US First Class Postal Mail which doesn’t include tracking information, but sure does arrive fast! Ordered Monday, received Thursday.

Parts: Futurlec
Ships from Thailand.

I found them searching for protoboards. They had some nice cheap medium-sized boards at a good price so I gave them a shot. Also, those elusive 2-pin through-hole pcb mount molex receptacles, at four cents each. Their online catalog is very tinkerer-friendly, with pictures sometimes and, I don’t know, somehow just easy to navigate. Probably not as complete as Mouser or Digi-Key, and pricier on some things. They took forever to ship, but answered my email queries very fast (“Your order will go out after we get our next batch of LM2931’s.”) One package arrived certified mail, which is all right since I work near the post office and could easily pick it up. The other normal mail, in my mailbox at home. Took nearly a month.

Parts: Sure Electronics
Ships from China.

Truly, ebay is our greymarket gateway to the world! Sure Electronics carries all the groovy LEDs, including 3 Watt RGB LEDs for $4 a pop. And a bag of 100 white LEDs for $3.99, or 100 UV LEDs for $4.99. Also “variety packs” off 50 machined IC sockets for a few dollars, and dc-dc power supplies (I really want to power all my 5v pic projects at burning man from a single car battery, yee ha), and some rather nifty tiny-but-useful protoboards. Kind of a random smattering, really, but fun. Occasionally endearing Mandaringlish*. Some products are BuyItNow, others with bidding. Double the price to include shipping, and it’s still tasty stuff. Ships pretty fast, considering it is from China. Two or three weeks, say. Sometimes certified, sometimes mailboxed.

*For example: “Both ways could generate 3A continuous output and work stably. Output voltage could be selected from 3.3/5/9/12/15 by encode switches, and could be fine adjusted through multi turn potentiometers. If in need, just change some resistor value, you could get other output value.”

PC Board Fabrication: Pad-2-Pad


This is an online PC board manufactory. I’ll be reporting on them soon. They have a free downloadable PC board design tool. It’s very easy to use, and will do autorouting. Also, it will compute the price and place the order for you. The software is only for Windows but runs acceptable using Virtual PC on my PowerBook G4 laptop. About $120 for 15 of a 2″x2″ board, with two layers and soldermask and silkscreening.

weird of wbl // Wed 2007.08.8 07:017:01 am

futurlec, for me, are great- maybe because their have a distribution office in NYC…

oh, i dont know. what do you think?

David Van Brink // Sun 2007.07.1 20:30 // {code wbl weird blinking lights}


Today’s post consists of several short unrelated items. Enjoy.

Brief Item 1: Avoiding bent pins

The programmer uses a zero-insertion-force socket. But popping the chip into the breadboard or a circuit board’s socket presents hazards. Solution: leave chip in straight-pinned machined sockets.

Brief Item 2: Yup, children still love blinking lights

My nieces were visiting, but my stamina for such things is pretty low. Friday was going to be my “Stay out, Uncle’s working tonight (sorry sis)” night. But then… five year old Amelia said she wanted to help make blinking lights. When duty calls it must be answered.

Brief Item 3: So that’s how it works

Our irrigation timer broke. Battery powered timer that turns a valve every couple of hours. I have no tale of heroic analysis and repair; we just bought a new one ($30@Home Depot). But as I was dropping the old one in the trash, common sense kicked in, and I took it apart first. I’m no mechanical engineer, but I think I can see what’s going on here. Little fast motor, big slow water valve.

Brief Item 4: Random numbers from a PIC chip

I can’t be bothered with complicated algorithms, so I just say, in an 8-bit kind of way, R := R * 5 + cycleCounter or whatever strikes my fancy that moment. The cycle counter input helps give you bigger than a 256-step sequence, but it can still get stuck in a loop. On a PIC chip, though, you can just let the watchdog timer time out now and again, it’s on a different and unsynchronized clock. Shakes it up a bit. (Some later chips let you run Timer 2 from the separate clock, so you can get that un-syncing feeling without a reset.)

Brief Item 5: Some electronic art inspirations

Jack Dollhausen’s site

Jack Dollhausen has been doing this stuff since 1968. I’m glad I didn’t know about him til now, I might not have bothered to learn how to blink lights at all.

Jeremy Lutes’ site

Jeremy Lutes has done some beautiful playa-bound electronic art, right here in the twentyfirst century. (And I sure hope he expands his web site, soon, too!)

And that’s the way it is.

oh, i dont know. what do you think?

(c) 2003-2011 omino.com / contact poly@omino.com