open collector

Stop, Blink and Drink

A little bit of the cat got out of the bag some time ago:

6 seconds of AVR flashing

You’re looking at ~24 hours of continuous AVR flashing compressed down into 6 seconds.

While I won’t be releasing the connecting PCB just yet (i’m still beating down a few issues and refining the BOM), I thought it would be good to supply the scripts I used to do the actual time lapse since it was non-obvious from a “the contest entry is due in 72 hours!” perspective.

Parts list

Teensy3: Attached to the system doing the programming

SSD1306: OLED display showing how many times the AVR has been programmed

Bus Pirate 3: Acting as an AVR programmer

Avrrrinator Rev B: Bus Pirate to 2x AVR ISP adapter

BB313 boards: Breakouts for easily attaching AVR ISP cables

ATtiny4313: Bigger tiny AVR for programming

ATtiny85: Smaller tiny AVR for programming

Assorted LEDs: Status indicators/Lighting

Logitech C920 Webcam: Takes all the pictures

Taking a picture

This small bash script invoking the gstreamer chain took on the duty of taking a picture every minute. It then copied everything out via rsync to another machine with tons of spare space.

1
2
3
4
5
6
7
8
9
10
#!/bin/bash

while true; do
gst-launch -e v4l2src ! video/x-raw-yuv,format=\(fourcc\)YUY2,width=1920,height=1080,framerate=5/1 \
! ffmpegcolorspace ! pngenc snapshot=true ! filesink location="frame.png"

RSYNC_PASSWORD="super_secret" rsync -avP frame.png rsync://rsync@storage.somewhere/frame-`date '+%s'`.png

sleep 60;
done

Video out

After all the frames were assembled, I manually went in and pruned a bunch that were completely dark due to the lights being off. Compressing the video down a bunch to 6 seconds took a bit of playing around:

1
mencoder 'mf://*.png' -mf fps=145:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o ~/Desktop/output-yt.avi

Code doing the programming

(Various scripts and pieces of code used to drive the operation.)

This is the script that refreshes the display. It calls avrdude to flash the AVRs and records the return code.

If it is zero, then the success counter for the AVR is incremented.

The current counts are then written to the serial port where the Teensy 3 can handle persisting the display and refreshing it with new results.

Update the Teensy3 display with avrdude results
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
# requires pyserial (pip install pyserial)
import subprocess
import serial

counter_4313 = 0
counter_85 = 0

failures_4313 = 0
failures_85 = 0

ser_port = serial.Serial(port='/dev/tty.usbmodem12341', baudrate=9600)

while True:
    try:
        ret_4313 = subprocess.check_call(['avrdude', '-v', '-p', 'attiny4313', '-c', 'buspirate', '-P',
        '/dev/tty.usbserial-AE01J4Q7', '-U', 'flash:w:blinky313.hex', '-x', 'reset=aux'])
    except subprocess.CalledProcessError:
        ret_4313 = 1

    if ret_4313 == 0:
        print "ATtiny4313"
        counter_4313 += 1
    else:
        failures_4313 += 1

   # Report statistics to the LCD screen
    report = "313:%s\n\n85:%s" % (counter_4313, counter_85)
    ser_port.write(report)
    try:
        ret_85 = subprocess.check_call(['avrdude', '-v', '-p', 'attiny85', '-c', 'buspirate', '-P',
        '/dev/tty.usbserial-AE01J4Q7', '-U', 'flash:w:blinky45.hex', '-x', 'reset=cs'])
    except subprocess.CalledProcessError:
        ret_85 = 1

    if ret_85 == 0:
        print "ATtiny85"
        counter_85 += 1
    else:
        failures_85 += 1

   # We do this twice to make it look more live
    report = "313:%s\n\n85:%s" % (counter_4313, counter_85)
    ser_port.write(report)

At the Teensy 3, the data is received and pumped out to the display. Not the greatest code, but decent enough to run for 24 hours without much of a hiccup!

Note that there are several small issues when using the SSD1306 library with the Teensy 3. I just stomped out the relevant sections after chasing down errors from the compiler (which were unrelated to SPI operation).

Teensyduino + Teensy 3.0 + SSD1306 SPI OLED Display
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*********************************************************************
* Flash Counter!
* Teensy 3.0 attached to a 128x64 SPI-driven OLED display
* Vendor: Adafruit
*
* IF YOU GET COMPILE ERRORS (you likely will!)
* Stomp out the compile errors in Adafruit_SSD1306.cpp line by line
* and everything should be OK (most of them are i2c related).
*
*********************************************************************/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_DC 11      // All pin numbers correspond to    
#define OLED_CS 10  // the 'gray' labels on the welcome to 
#define OLED_CLK 14     // Teensy 3 card
#define OLED_MOSI 12    // SSD1306 labels this as: "Data"
#define OLED_RESET 9

Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Display setup
  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();
  display.setTextColor(WHITE,BLACK);

}

void loop() {

  // Persist the display until we have something to display
  if( Serial.available() > 0 ) {
    display.clearDisplay();
  }
  display.println("AVR Program Count");
  display.println();
  display.setTextSize(2);
  while ( Serial.available() > 0 ) {
    digitalWrite(13, HIGH);
    char c = Serial.read();

    if (c == '\n') {
      display.println();
    } else {
      display.write(c);
    }
    digitalWrite(13, LOW);
  }
  display.display();

  delay(500);
  display.setTextSize(1);
  display.setCursor(0,0);
}

And of course, hexified blink programs. These are for the ATtiny4313 and ATtiny85 respectively. They’re fairly generic, but the one for the 4313 is from the BB313 website.

1
2
3
4
5
6
:020000020000FC
:1000000000C000270FBD03E00EBD002707BB08BBE3
:10001000BE9A00270DBD0CBDC69A0DB51CB50D339B
:10002000E1F7C69800270DBD0CBD0DB51CB50D330D
:0C003000E1F7C69A00270DBD0CBDEFCF14
:00000001FF
1
2
3
4
:020000020000FC
:1000000000C0B99A19E31EBD112714E71DBD0FE703
:0800100000BF112714E018BB2A
:00000001FF

Hardware Volume Controller

(5/11/13) - Hey fantastic reader: This is an old how-to (from 4/2/12!) that existed in its own self-contained repository. Reflecting back, this hack was kind of silly, but i’m porting it here to keep everything in one place.

And if you’re curious about the long-term viability of this build.. it is still kicking. The detents are a little less crisp now, but everything works a treat. (And now, back to your regularly scheduled post re-run!)

It wasn’t too long ago that volume control on a keyboard was a foreign concept. After it became a ‘feature’, that control seemed pretty normal. There is however, a slight modern exception now. Many mechanical keyboards (which have been coming back into style) don’t have them.

overview

In response, I hacked this together. It’s a volume controller which parses a rotary encoder’s input and controls the volume (tested on OS X/Windows/Linux so far).

Parts/Bill of Materials:

  • Altoids Gum sized tin - A slick enclosure. Scratches easily though.

  • Rotary Encoder - I’ve tried a bunch. A lot of them either failed over time, or the ‘clicks’ (detents) became mushy. This one comes with a cool looking knob and is panel mountable too.

  • Adafruit Atmega32u4 Breakout - Brains of the operation. Comes with headers. For this particular project, just keep the headers for a rainy day.

  • Wire - Will need these to hook up the rotary encoder. Stranded wire is preferable since it can bend and flex.

  • Perfboard - While you can go without, the perfboard is nice to relieve the stress on the rotary encoder pins. I haven’t run across an economical source of cuttable copper-clad perf; they’re usually so large that I feel guilty slicing them apart. These seem to be the right size, but are rather thick (I haven’t sliced these apart yet). Use anything that works.

Optional (or you already have these if you’re thinking this is a good weekend project):

  • Sugru - I used this stuff to attach the board to the tin. Anything non-conductive works (determine the amount of adhesion based on your projected re-use of these parts).

  • Soldering iron + Solder - Needed to join all the parts together.

  • Mini-B USB cable - This is the cable type that the breakout board accepts.

  • Drill/set of bits - To make a hole so that the encoder can poke out of.

  • Something to cut with - For perfboard cutting, wire stripping, prying the enclosure, etc.

Electronics assembly

Start by cutting perf for the rotary encoder. Put on your safety glasses (and quite possibly a dust mask just to be extra cautious). Cutting perfboard (and other things too!) can cause pieces of it to fly into your eyeballs.

To cut the perfboard by hand, score 5-7 times along the holes that mark the edges of the cut (make sure to dry fit before cutting). I had better cuts by scoring along the entire length of the perf (although this means some perf ends up being wasted).

Once you’re ready to cut, take a pair of shears (dull diagonal cutters work too) and clip a notch where your scored lines meet the edges. This should serve as a guide for your snap (the concept is similar to tearing a notch in a piece of folded paper before ripping it apart cleanly). Slowly bend the perf where the score is and the perf should snap apart. If it resists or seems like it won’t snap along the score line, score some more and repeat.

If that fails, break out a dust mask, a pair of safety glasses (you should already be wearing these!), and just start hacksawing. It won’t be very pretty, but it should work.

The next step is to solder the encoder in. Insert the encoder and tack a leg with solder to hold it in place. Ensure everything is aligned the way you like it (check that there is room for the wiring below), and solder the rest of the pins in.

The wiring can be deceptively tricky. Measure out enough wire so that you can open/close the box. Cut, strip and tin the wires. You’ll need 5 wires.

Here is the wire mapping (looking from top to down at the rotary encoder, with three pins on top and two on the bottom):


Volume Up/Down (three pins, top)

Wire color Pin on Atmega32u4 Pin on encoder
White D0 Left-most pin
Black GND Middle pin
Red D1 Right-most pin

Mute On/Off (two pins, bottom)

Wire color Pin on Atmega32u4 Pin on encoder
Black GND Left-most pin
White B0 Right-most pin

Solder all the wires together. Once the wires are attached to the perf, blob some solder to bridge the wiring and the encoder pins together.

encoder wiring

Enclosure

To drill a hole for the encoder, find a bit size that matches (the datasheet says it is 6mm / .236 inches or just around a 15/64 drill bit (.234 inches)). Measure for dead center on both axes (or like a professor once told me: ‘eyeball it until your OCD stops’). Mark the drill point.

If it makes it easier, it is possible to remove the lid from the body. Simply bend the hinged tabs outward and the lid will slide off. Reverse to fit the lid back on.

You may need to brace the back of the drill area with a block of scrap wood to prevent warping. Drill from the outside in (so that all the unsightly edges are hidden somewhat). Don’t apply too much pressure (you won’t be able to undent things easily).

Once you’re done, dry fit the encoder but don’t screw it into place yet.

enclosure

For the USB port, buttress the breakout board against the bottom of the enclosure and mark an approximate outline. Using a drill, begin drilling into the case (the hole won’t be large enough, but we’ll fix that in a bit). With the hole made, take your shears and carefully pry to make an opening wide enough for the USB plug to poke out. Continue to check the fit while slowly prying. Don’t worry if it looks too ugly. The USB plug covers up most of the mess.

Final assembly

Before adhering the breakout board (permanently, depending on your preference); lets test everything.

Compiling:

Unfortunately I haven’t had all that much luck compiling on OS X (using Homebrew packages), and I haven’t tried on Windows at all. Only Linux has worked so far. All hope is not lost however, you can manually program the breakout with avrdude! Read on to ‘Skipping all of that’.

These are the packages I have installed for Fedora which are needed to compile:

1
$ sudo yum -y install avr-libc avrdude avr-gcc avr-binutils git

Here is a one-liner to install all those dependencies with yum.

1
$ sudo yum -y install avr-libc avrdude avr-gcc avr-binutils git

Next, grab a copy of the LUFA git repository that includes the necessary modifications:

1
2
3
4
5
$ git clone git://github.com/davidk/lufa-lib.git
$ cd lufa-lib
$ git checkout -b atmega32u4-mediacontroller origin/atmega32u4-mediacontroller
$ cd trunk/Projects/MediaController
$ make all

If the compile was successful, connect the breakout board to your computer. Type the following into your console, hit enter, but don’t type in your password yet.

1
$ sudo make program

Going back to the breakout board, hit the white button (a green light should slowly start fading in and out indicating that the breakout is ready to be programmed). Type in your password and watch it go. If avrdude had problems finding your 32u4 breakout, run dmesg and check the output for something along the lines of ttyACM. The last part should be a number. Modify the makefile with the new port and re-run the line.

Here is what my dmesg looks like:

dmesg

Skipping all of that:

If you’re on OS X or Windows.. or just don’t like compiling, get the hex file, press the white bootloader button, and run the following (a working example for OS X):

1
$ avrdude -p atmega32u4 -P /dev/tty.usbmodem621 -c avr109 -U flash:w:MediaController.hex

Change /dev/tty.usbmodem621 as appropriate for your platform. On OS X, if at first /dev/tty.usbmodem612 doesn’t work, use tab-completion to fill in the remaining section. Enter /dev/tty.usb and tap tab to get relevant entries when the bootloader light is active.

Finishing up: Do volume up/down and mute (pushing down on the encoder) work properly? If so, time to finish up! If not, make sure that the board is programmed (it shows up as LUFA Media Controller in dmesg, and similarly under the OS X System Profiler). Also ensure the connections between all the parts are nice and solid.

If everything is finished, open a pack of Sugru (or the adhesive you’re using), and stick things together. Next, poke the rotary encoder through the hole on the lid. Then secure it with the hardware provided and add the nice looking control knob to top it off.

Here is what mine looks like now; it is magnetically attached to the keyboard (no ill effects yet).

completed

Attributions:

This project uses code and examples provided by LUFA (which is MIT licensed). Thats by Dean Camera. The code to read the rotary code comes from a posting by circuitsathome here.

Improvements, chaos, and cost reductions:

From a performance and cost perspective, the breakout used for this project is overkill; building an ATTiny breakout might be more worthwhile. Also, it might be possible to just rip the guts out of an old keyboard and use its media controller functions with some modding.

Tools for 3D Printing: What Do I Get?

Pocket level

A pocket level ensures things are reasonably level before further calibration and fine tuning

These are few of the things i’ve used/and bought over the past few months while owning a 3D printer. If you’re new to the 3D printing world (and making, in general), collecting and/or using some of these will make your life easier.

These are the basics, so you may be able to borrow these from a (friendly) maker and/or tinkerer.

Thread-locking fluid

In the first few months weeks of owning my 3D printer, I made the mistake of assembling my printer without thread-locking fluid. Of course, bolts and screws fell off during long prints causing incalculable amounts of wasted time and filament.

Thread locker (or the stuff by its popular brand name: Loctite) keeps a bolt from freeing itself (usually via vibration forces), while allowing it to be removed by hand if needed.

Adding loctite is best done during a printer build. If certain parts are constantly coming loose, working it in as needed will do too.

Part #: 91458A115 (McMaster-Carr, Loctite 243, Blue)

Stuff to make things move

For squeaks, metal on metal noises, or just for things that move and make contact, adding a few drops of lubricant is occasionally needed to keep things in good form.

Some printing guides prefer sprays (especially on vertical areas like Z-axis rods). For several months i’ve been using a liquid lubricant, which contains PTFE (without issue so far). I didn’t intend to use it for my printer, but it ended up working quite well.

Part #: 1155K33 (McMaster-Carr). You get a lot for about $5 (not including shipping of course).

Pocket level

On my particular printer, there is the potential for a lot of things to go out of alignment (either due to stresses at rest, or operator error). A small level is great for getting things into a general ball park for further fine tuning.

The Stabila Pocket Level ($10) is magnetic (the magnetized area isn’t obvious, but it is on the bottom). It also has a very clear window for viewing the bubble, and is slightly more fluid than some of the other bubble levels I have on hand.

While it is a bit expensive for a smaller level (slightly larger levels like torpedo levels are well within or below its price), this is a pretty good quality level that seems like it will last.

It will also (unlike torpedo levels) fit into areas with very little clearance.

What does it look like? Scroll up a bit. :)

Part #: Stabila 11990 Pocket Level - (Amazon)

Cable/zip ties

If your printer looks anything like mine, nearly everything (including the pullies and even some of the linear bearings) are held together by these ties. And sometimes readjusting things means cutting those ties.

For a few bucks you can stop cursing while trying to find a replacement tie.

Part #: 7130K41 (McMaster-Carr). These are the smaller ‘micro’ zip ties, and come in a large enough pack to stave off regret at the amount of zip tie waste you’re bound to generate.

Long screwdriver/racheting driver

Who doesn’t have a screwdriver? (Answer: A person who needs one right now.)

A ratcheting driver makes a surprising difference on a printer.

I’ve been quite happy with a Stanley Ratcheting Screwdriver ($10). The shortened turn in ratchet mode is great when working in tight spaces (where it is hard/annoying to do “full” turns).

This particular driver comes with several extra bits hidden in the endcap and has the ability to become a normal/fixed screwdriver with a twist of the knob.

Normal screwdrivers are more than enough though, and this is really just optional.

Part #: Stanley 69-189 Ratcheting Multi-Bit Screwdriver - (Amazon)

Other accessories

These are parts that I have no specific recommendation for, but once you have them you may wonder what you did without them!

Straight tweezers

At working temperatures, the extruder gets really hot. And print beds do as well. To save yourself from getting actual 3D printing battle scars, get a pair of tweezers to pluck out stray strands of filament.

During warm up, just use the tweezers to pluck at the extruder, or to scrape off a small starting failure/error from the bed that has failed to adhere.

It is likely that you wouldn’t want to use an ESD-style tweezer (they’re often colored black with a matte finish). Mostly this is because some of them have a lightly applied coating that scratches easily. Save the ESD tweezers for sensitive electronics work.

Flush cutters

Cutting filament is kind of an afterthought, but it needs to be done (usually when loading and unloading new/used filament). A pair of throwaway flush cutters will make doing so quick and easy.

It probably isn’t a good idea to use new or flush cutters you love. Certain plastics like PLA are fairly hard, which may cause faster wear and tear on cutters. Then again, decent cutters can be had for a good price nowadays (Xcelite cutters are pretty decent! Mouser Part #: 578-175M).

Detachable/Reusable spool

Using filament freestyle without any sort of management is a recipe for disaster over time. Many of my early troubles were due to buying spool-less, (but wound filament) and trying to wing it without a spool.

If I went to sleep, got a drink or otherwise looked away for a bit, the filament would somehow find a way to tangle, feed incorrectly, or do nasty things like snap (after tensing up due to tangling).

After resorting to hacks, (like turning the filament bag itself into a spool holder), I got kind of fed up and decided to just get a reusable spool.

A decent one for small quantities (1 lb, or 454 grams for everyone else), consists of a spool that can have the side detached (usually via screws) and filament loaded in.

I’ve found that the filament doesn’t necessarily have to be completely flush with the hub for small quantities (perhaps 1/2 a pound or less), just ‘enclosed’ by the spool walls.

Some good features to look out for are pre-drilled holes to put the filament ends into, and a standard diameter/width size (if you’ll be using multiple spools with a particular spool feeding system/holder).

For most spool setups, they should be mounted on some sort of holder where the filament can be pulled into the extruder smoothly (and consistently).

Spool holder

There are plenty of examples on Thingiverse of spool holders. Some can be purchased for $8 and some can be made out of PVC pipe. Don’t forgo this for too long, as it is a pretty good addition to your printing kit if it isn’t already built-in to your printer.

Tongue-and-Groove Pliers

Otherwise known as Channellocks (which is also the name of the company that created them), these pliers are pretty great to have around, either to remove a print with brute force (if necessary, and if your print allows for it), or for tightening things.

If you don’t have these already, they can be cheaply had at many stores (McMaster-Carr also sells them), and are useful for other things around your home as well.

Calipers

This is usually required by every “Welcome to your brand new 3D printer!” guide. You’ll need one to calibrate things like extrusion amounts (when loading new filament) and to bring physical objects into CAD for printing.

Be sure to do extra research on the different types of calipers out there, as quality can vary a lot between types (veiner vs digital) and brands (Mitutoyo vs dollar store type).

Blue Painter’s Tape

A spool of something like 1/4” 3M Blue Painters’ Tape will work very well as a surface for your PLA print to adhere to (as long as the first few layers are pressed down into the tape proper). The larger width also makes resurfacing fairly easy.

(ABS users will want to look into Kapton/Polyimide tape or squares)

Best of luck in your printing adventures!

cheers

Errata / Changes

05/09/13: Clarifications and basic fixes

Printable Divider for the 10164 Storage Drawer

Storage drawer divider

This is a 3D printable small drawer divider for the Akro-Mils 10164 parts cabinet.

The clear drawers themselves have a nice little slot for partitioning, so this divider fits right in and sits snugly without bowing out the drawer.

While there are several dividers that come attached to the back of the cabinet (which are manually de-paneled by the end consumer), they’re very limited in quantity.

So if you have a 3D printer of some sort, or want to play with the model enough to make it ‘go’ on a laser cutter/CNC, give this a shot.

Keep in mind that this will not fit the larger drawers like on the 10144.

Download the STL file here.

To prevent ambiguities, the license for this (simple work) is WTFPL. Feel free to remix it, and do as you wish without reading walls of text.

cheers

The Avrrrinator (Revision A)

Bus Pirate Case, Translucent Blue, Improved

A simple Bus Pirate v3 to AVR adapter. This was made to simplify wiring between the v3 Bus Pirate and an AVR ISP header. Tested with the BB313, and ATTiny4313/85s.

Add a 3 pin header and a jumper to power the target AVR from the Bus Pirate (for normal operation, programming, etc).

Check out the ”Other work in this field” section below for other adapters as well (some of them support multiple protocols and programmers).

Make one for yourself

Grab a zip file of the entire repository by clicking here.

The .brd file is in the hardware/revA folder.

From there, you can generate your own Gerber files using Eagle and send them off, or use a service which processes the Eagle board file for you.

If you don’t already have a preferred fabricator, please give OSHPark a shot. OSHPark will take the .brd file, panel it and return your boards in a few weeks. It is also run by a very awesome person.

See the ”Bill of Materials” section for information on parts.

Notes & next revision improvements

The silkscreen is really small in some areas. This will be changed in a future run. If making one for yourself, feel free to change the silkscreen text sizes around, and add a miniature dinosaur.

Bill of Materials

PCB

1x: Avrrrinator PCB

Headers/Jumper

These parts are from Mouser:

1x: 151-8033-E - Red jumper for power selection

1x: 517-9612066404AR - 6 pin ISP header

1x: 649-68004-236 - Strip of header (enough for both the 10 pin Bus Pirate header and the 3 pin power select switch)

Cables

If you don’t already have the necessary cables, pick these up. Both are needed since one connects to the Bus Pirate, and the other connects to the AVR:

These parts are from Adafruit:

1x: 10-pin Socket/Socket IDC cable (6”)

1x: 6-pin Socket/Socket IDC cable (6”)

Optional parts

1x: 538-90130-1110 (Mouser) - BP box connector. This hasn’t been tested or soldered in, but it appears to fit comfortably within the layout of the board.

Resources

Bus Pirate AVR Programming

Other work

Dangerous Prototypes’ PIC+AVR programmer

A Bus Pirate Breakout Board for different protocols (which includes an ISP header)

3D Printed Bus Pirate v3.6 Case (DP6037)

Bus Pirate Case, Translucent Blue, Improved

Source files and general instructions for printing can be found here.

The Bus Pirate is a pretty fantastic device for sniffing around and working with new circuits. It can even act as an AVR programmer.

After using one to fiddle with a few circuits, a case became necessary after seeing its value. While there are cases that can be purchased[1], a 3D printer was laying around waiting to be used.

Finding only a case outline (which proved to be extremely useful as a jumping off point) on Thingiverse, one needed to be made for the newer Bus Pirate.

After several hours (mostly spent re-calibrating the 3D printer, untangling filament, and playing musical notes with the timing belts), the printer popped out several iterations of cases.

The first few worked well, but were dependent on PLA ‘rods and spikes’ (scrap filament cut and heated on a hotbed to straighten) and press-fitting to hold the top and bottom halves together. The USB header was also unexposed, which caused leveling issues (since it was higher than the rest of the board).

Printed Bus Pirate Case, Reject

Going forward with several revisions, and many rejects later (about 12!), a decent case started appearing. Instead of PLA rods, a few 8mm long M3 machine screws and M3 hex nuts were used. They’re not very common, but the M3s seem to fit rather well while providing a good degree of stability.

The assembly order from the bottom: M3 screw, bottom plate, PCB, hex nut, top plate.

While the top looks unsecured, it must actually be screwed/threaded in from the bottom with a decent amount of force.

Printed Bus Pirate Case, Front

Polyimide tape was used on the back to protect the pins from being shorted out. The reason for not covering them in CAD is because they can be useful to probe with a multimeter at times.

Printed Bus Pirate Case, Back

Files are posted here (CC-BY-SA; via original author), but may change in the future if I ever get around to beating the thing into a different shape.

If you have an idea for a change, or can design a better one go for it!

Updates & Errata

1-1-13: For many printers with a perfectly flat print bed (borosilicate glass, metal, etc), it may be advantageous to mirror the output on one axis so that the top gets printed perfectly flat.

With a borosilicate glass bed:

Bus Pirate Case, mirrored shiny front

The exported STL file has been added to the GitHub repository. Look for dp6037-top-axis-flipped.stl when grabbing it (or click that link).

1-2-13: Yellow? Who prints stuff in yellow? Don’t you have blue?

After a bit of recalibrating, this is what the case looks like in translucent blue. Not very high quality, but passable:

Bus Pirate Case, Translucent Blue

1-3-13: Here is a better front panel (printed after mending the Z-axis into alignment), which will probably be the last update (in this series of days).

Bus Pirate Case, Translucent Blue, Improved

1-4-13: Added a link to source files at top and shortened/corrected more text to sound less silly.

Notes & References

[1] Note that buying an acrylic case is really the way to go. They sell for about $3).. but if you have a 3D printer, it probably needs to earn its keep anyway.

Thanks & Resources

cheers!

OHS Summit Bag

Adafruit had an Open Hardware Summit bag (of swag) to give away some time ago, and I was fast enough to win it on their Saturday night show (it was an easy answer: “eyebeam”). For a few weeks, it has sat patiently next to my fire extinguisher, and I never really got the chance to look through it.

So whats in the bag? (This is in no particular order, since i’m just reaching in to grab things.)

  • Parallax S2 Robot Badge

  • Map & location of 23 lunch spots in NY near Eyebeam

  • Miniature black umbrella branded: “Stay Open” / “Support Open Source Hardware” in bright green

  • A SMD LED Arduino shield by Joey

  • TI MSP340 Launchpad (labeled with Open Hardware Summit 2012 on the bottom)

  • Oven mitt (this is actually useful since I bake, and yes, I will probably be the only person ever to win an oven mitt from Adafruit :)

  • Yellow printed robot from Ultimaker (very high quality 3D print; it definitely puts my current 3D printer to shame)

  • Finger Sock monkey with a cape (not surprisingly, someone has already called ‘dibs’ on it)

  • Fedora 17 Live DVD

  • 2x LPC114FN28 32-bit ARM Cortex-M0 chips (32kB flash, 4kB RAM, 12MHz internal RC osc) with a breakout board offer

  • “Useful item #364” from Cosm (nifty bridge(?) interconnect)

  • 2x E is for Electronics from Adafruit. Whoever colored in Frequency on one of them did a really good job. :)

  • Box of 8 Crayola Crayons

  • Sparkfun Resistor Kit: 25 5% carbon film resistors for 0, 1.5, 4.7, 10, 47, 110, 220, 330, 470, 680, 1k, 2.2k, 3.3k, 4.7k, 10k, 22k, 47k, 100k, 330k, 1M. Has a resistor color code guide on the back.

  • Adafruit Open Source Hardware iron on patch (sticker on the back says Adafruit with their 10% discount code)

  • SOIC to through-hole converter PCB (oddly, I might have an immediate use for these since I have a few samples from Linear)

  • 9x Dorkboards “a bare bones arduino clone.”

  • 4 LittleBits fridge magnets

  • Rubber band gun business card (neat!)

  • NYU Poly branded pen, with a squishy style grip

  • Small flathead screw driver

  • PCB keychain (leaf shaped, from Seeed)

  • OHS program with background on speakers and schedule

  • Something I didn’t expect: Phil’s OHS badge. Its still arranged ‘pt’ with a little extra dot on the upper right. Very cool.

The swag also included the usual businessy cards. A small sample (I think i’ve misplaced a few):

  • ITP Tich NYU with a blurb on the back about their two-year graduate program (color me convinced)

  • Evil Mad Science, “Purveyors of fine DIY and open source hardware.” (hi Zener!)

  • Make magazine offer

  • Circuits.io “Design HW in your browser”

  • nimbits.com (sensor data logging) advert

  • Industry City Distillery (they have tours and a vodka tasting, neat)

  • Built-to-Spec (which has the instructions for the rubber band business card)

  • OSHWA membership flyer

  • Directions to the new MakerBot store

  • freeSOC with a little blurb about drag-n-drop design for hardware

Thats about it. It will probably be a very long time till I actually use some of the interesting pieces of H/W in the bag, but at least I have a few new projects queued up!

Raspberry Flavored Time (a NTP Server on Your Pi, Tethered to a GPS Unit)

GPS module connected to a Raspberry Pi (for accurate time keeping):

Adafruit Ultimate GPS v3

A primer on time

Watch this brief video by Bill Hammack, aka engineerguy on YouTube. It covers the complexities of keeping very accurate time in a short video!

Where NTP fits in

Being on synchronized time is pretty important. Is your office clock faster or slower than the one on your watch? What about your phone? What if you turn it off for a month? A year?

In other to get time from very accurate sources, some devices and services use the Network Time Protocol (NTP for short) to keep their time synchronized. Your device is probably using NTP as you read this!

How it works: Periodically, your computer will connect to servers that speak NTP. After getting the time, your system does some math (to account for transmission delays, and bad clocks), and adjusts the system clock. This periodic synchronization keeps a clock from drifting too far behind, or too far ahead from the world standard.

By itself though, NTP does not provide accurate time information. This the job of a dedicated reference clock.

A reference clock is a precise source of time, and these are connected to a computer which transmit their data over a network using NTP.

In our case, we can (ab)use a GPS unit as a reference device (in GPS, accurate positioning requires very accurate time). While not a lab quality reference clock, it has enough accuracy for most applications.

Strata

In NTP parlance, time systems are arranged into different strata. Each level (starting from zero), determines how far away you are from a clock source. [1]

Stratum 0: Cesium/Rubidium-based clocks, radio and GPS clocks. Depending on precision, these can be very, very, very accurate (and really expensive too)!

Stratum 1: Computers attached to Stratum 0 sources. They expose the data from Stratum 0 to the world.

Stratum 2: Collector of stratum 1 time over a network. May punt bad stratum 1 clocks (e.g. stop listening to them).

Stratum N: N level away from 0, does the same as 2.

Stratum 16: Considered to be unsynchronized.

Most consumers of NTP data collect information from stratum 2 (or higher) sources.

For instance, Apple’s time.apple.com server is a stratum 2 time source. It might be connected to a bunch of stratum 1 time sources. In turn, the stratum 1 computers would be connected to a gaggle of stratum 0 reference clocks.

Being a stratum 2 source, it figures out which stratum 1 time source(s) it can trust and aggregates all the data between those. Using a bit of math, it figures out which sources seem bad, and kicks those results to the curb.

1
2
3
4
% ntpq -p
     remote           refid      st 
====================================
*time.apple.com  17.168.198.148   2 

GPS Clock-o-Bot

That brings us to setting up our own GPS-sourced clock. Why?

  • Perhaps you are stuck on a remote island without a reliable Internet connection.

  • You have some sort of experiment that needs to have great timing.

  • You’re going to use the GPS hookup for something else entirely (like a phone home device), and want the meat on how to do that. (Sure!)

  • You feel like abusing a NTP server for some reason, or policy prevents you from getting accurate time through the Internet.

  • Having your own time server is cool.

  • Say this in an Australian accent, or with an accent that features a high rising terminal so it sounds more awesome: “Why the heck not!”

Difficulties

Beyond this point, this becomes a slightly advanced article. You’ll most likely be comfortable with a bit of prior Raspberry Pi/Linux/Electronics experience under your belt.

I try to explain steps throughly, and provide links to external sources which should help even if you are a beginner.

Parts List

All of these parts are available from one vendor, so you don’t have to order and coordinate shipping times. The vendor used here is Adafruit. They’re well regarded with very reasonable policies and good people.

  • Raspberry Pi - The brains of the project! Raspberry Pis sell out fast, so buying from another vendor may be the only possible way of acquiring one.

  • Adafruit Ultimate GPS Breakout, v3 a very compact GPS unit with 1PPS output. (Note: If you have a v1 or v2, you can still get a 1PPS signal – you’ll need to solder a small wire to the exposed pad. See the PDF documentation for a pinout.)

Hardware voltage warning: If you are using another GPS, please mind the GPIO pin voltages as they are only 3.3v tolerant. There is no over-voltage protection on the board. This means a bad connection could easily kill a pin or worse.

  • Wires - If you will be using the Pi Cobbler below along with a standard breadboard, the wires should just be solid core wire. If you will be wiring the GPS up directly (using the provided header), they should probably be Female/Female jumpers.

  • Ethernet Cable - Or wireless adapter to connect. Definitely check old router boxes for this.

  • SD Card - For loading a distribution. You probably have one of these already lying around.

  • Power Adapter - The power adapter should terminate to a micro USB cable (these are the slimmer “phone charger” cables). Be sure to look for an adapter with a current rating of around 850mA (or more).

Optional

Distribution

Starting from scratch, you will need Occidentalis, a fork of Raspbian.

Download by following a few links here.

After downloading, write the image to the SD card.

If you have forgotten how to write images (it happens even to the best of us), try this guide on elinux.org.

Initial Setup

After flashing your SD card, insert the card and boot the Raspberry Pi by plugging it in.

Edit /boot/cmdline.txt, along with /etc/inittab to free up the UART (which shows up on /dev/ttyAMA0) so that the NMEA “serial” data can be read on the Pi.

1
2
3
4
5
6
7
8
$ sudo nano /boot/cmdline.txt

# Remove these in cmdline.txt:
# `console=ttyAMA0,115200`
# and `kgdboc=ttyAMA0,115200`.
# Mine looks like this:

dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

Hold CTRL+o and hit [Enter] to save. Then hold CTRL+x to exit.

Next, edit /etc/inittab and comment out, or remove the last line in this file (page down till you see it):

1
2
3
$ sudo nano /etc/inittab
#Spawn a getty on Raspberry Pi serial line
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

Once you are done, power off the Pi and begin connecting things to it!

1
2
3
4
$ sudo poweroff

# Remove the power connector when only the PWR LED remains lit/screen
# goes blank and begin attaching things.

Connect the following pins (Raspberry Pi is on the right, GPS on the left):

Here is a really boring pin out diagram:

GPS     RPI
---     ---
RX  --> TXD
TX  --> RXD
PPS --> GPIO #23
GND --> GND
VIN --> 5V0 

Wiring for the Adafruit Ultimate GPS v3 (RX->TXD isn’t connected):

Adafruit Ultimate GPS v3

For the v2, with a wire soldered onto the 1PPS pad (the 1PPS wire goes to the blue one off image, which then leads to GPIO #23):

Adafruit Ultimate GPS v2

If you need background on where GPIO pin 23 is located when connecting directly, see this page at elinux.org. Otherwise, GPIO #23 is just #23 if you’re using the Pi Cobbler.

Once everything is connected and you’ve verified everything twice, connect the power.

1PPS

You may be wondering about the PPS pin!

While NMEA data is good enough for synchronizing time to within a few hundred milliseconds, it can be bad for applications that require precision timing, or just plain bad if you’re obsessed with getting precise time.

This is where the PPS pin we connected earlier comes into play. 1PPS or One Pulse Per Second, is a signal that says “here is the precise start of a second!” A PPS signal is usually accurate to a few nanoseconds give or take whatever is in the path between sender and receiver.

1PPS signal

Alone, 1PPS can only tell you the precise start of a second, so anything that wants to set time accurately needs both NMEA data and 1PPS information.

To effectively utilize 1PPS, we’ll have to patch the kernel and add support.

Switching The Kernel

Doing this isn’t particularly hard. However, keep in mind that it will overwrite any special modifications you’ve already done to the kernel, and will break on upgrades to the kernel.

In order to keep things simple, I have a repository with pre-made kernel modules and kernel image. If you’d like to view the source this is based on, click here. [2]

To grab the pre-compiled kernel and modules:

1
2
$ sudo apt-get install git
$ git clone https://github.com/davidk/adafruit-raspberrypi-linux-pps.git

Back up and copy the kernel image:

1
2
3
$ cd adafruit-raspberrypi-linux-pps
$ sudo mv /boot/kernel.img /boot/kernel.img.orig
$ sudo cp kernel.img /boot

Move the modules over:

1
$ sudo mv modules/* /lib/modules

Finally, add the pps-gpio module to /etc/modules.

1
2
# Run this command in a sub-shell so appending works
$ sudo sh -c "echo 'pps-gpio' >> /etc/modules"

Automatically Making Links In /etc/udev

By default, our setup isn’t usable by the NTP server since it expects data to be present at specific locations. By adding a few rules to udev, we can automatically make symbolic links (aliases, shortcuts, etc) from our NMEA serial and 1PPS data, to a place where NTP can read and interpret it.

If we didn’t create these rules, the NTP driver would get no data to process.

1
2
3
4
5
6
$ sudo nano /etc/udev/rules.d/80-gps-to-ntp.rules
# Change MODE of ttyAMA0 so it is readable by NTP and provide a symlink to
# /dev/gps0
KERNEL=="ttyAMA0", SUBSYSTEM=="tty", DRIVER=="", SYMLINK+="gps0", MODE="0666"
# Symlink /dev/pps0 to /dev/gpspps0
KERNEL=="pps0", SUBSYSTEM=="pps", DRIVER=="", SYMLINK+="gpspps0", MODE="0666"

Hold CTRL+o to write the file, tap [Enter] and then hold CTRL+x to exit.

Installing and Configuring NTP

To install NTP, we abuse the default install a bit since the repository version doesn’t really pick up on 1PPS. It will also take some time to do all of this since we’re compiling from scratch.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ sudo apt-get install ntp
$ sudo apt-get remove ntp
$ sudo apt-get update
$ sudo apt-get install libcap-dev
$ sudo apt-get install pps-tools
$ wget http://www.eecis.udel.edu/~ntp/ntp_spool/ntp4/ntp-dev/ntp-dev-4.2.7p319.tar.gz
$ tar -xvf ntp-dev-4.2.7p319.tar.gz
$ cd ntp-dev-4.2.7p319

$ ./configure --prefix=/usr --enable-all-clocks --enable-parse-clocks \
--enable-SHM --enable-debugging --sysconfdir=/var/lib/ntp --with-sntp=no \
--with-lineeditlibs=edit --without-ntpsnmpd --disable-local-libopts \
--disable-dependency-tracking && make
$ sudo make install

Be sure to edit /etc/init.d/ntp and change the DAEMON line:

1
2
3
$ sudo nano /etc/init.d/ntp
DAEMON=/usr/bin/ntpd
#DAEMON=/usr/sbin/ntpd

Once you have been dropped back to the terminal, edit /etc/ntp.conf and add the following (be sure to change the broadcast line if it differs for you):

1
2
3
4
5
6
7
8
9
$ sudo nano /etc/ntp.conf

# http://www.eecis.udel.edu/~mills/ntp/html/drivers/driver20.html explains
# these settings
# Slightly modified, but credit to:
# Paul Kennedy @ (http://www.raspberrypi.org/phpBB3/viewtopic.
# php?f=41&t=1970&start=80)
server 127.127.20.0 mode 17 minpoll 3 iburst true prefer
fudge 127.127.20.0 flag1 1 time2 0.496

For a general setup with an Internet connected Pi, leaving these uncommented is generally considered good practice.

1
2
3
4
server 0.debian.pool.ntp.org iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst

What do the bits in the server line do? [3]

server 127.127.20.0 mode 17 minpoll 3 iburst true prefer

  • 127.127.20.0: Specify the GPS_NMEA driver.

  • mode 17: This sets the line speed (bit 4, dec: 16) to 9600 bps. Additionally, $GPRMC is processed (bit 0, dec: 1). We get a total sum of 17 when adding the decimal parts together (hence “mode 17”).

  • minpoll: Minimum polling interval for NTP messages in a power of 2. Here, 3 = 8 seconds.

  • iburst: If a server is unreachable, send a burst of eight packets instead of one.

  • true: Let the server survive NTP’s algorithmic weeding.

  • prefer: If we have a choice among good hosts (post-determination, etc), use this one for syncing.

fudge 127.127.20.0 flag1 1 time2 0.496

The fudge options are driver dependent. [4]

  • 127.127.20.0: Specify the GPS_NMEA driver.

  • flag1 1: Activate PPSAPI, and process the PPS signals we get.

  • time2: Compensate slightly for transmission delays. Instructions for tuning this are located on the driver home page. Specifically, look for 7 (bit) / 128 (decimal) in the mode section.

A complete explanation of the flags used is provided at the website above. You can also just click here to be taken there as well.

Reboot

Now that the kernel is updated, udev makes links properly, and NTP is installed+configured.. all that is left to do is pray to your local noodly appendage (or other $x of choice) and reboot.

1
$ sudo reboot

Checking the time

Once you’re back up, wait for your GPS to lock (give it a view of the sky to make this process faster).

When your GPS is locked to a sufficient number of satellites (the Adafruit GPS module will blink intermittently), type ntpq -p into your Raspberry Pi’s console, and you’ll get something like this:

1
2
3
4
$ ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
oGPS_NMEA(0)     .GPS.            0 l    8    8  377    0.000   -0.025   0.002

Unit Calibration (skip if not using Adafruit’s GPS module)

To get the best out of the Adafruit GPS unit, we will tune it so that it outputs only the sentences we need. In particular, we’re interested only in the $GPRMC lines.

Before continuing, ensure that the RX (GPS) to TXD (Raspberry Pi) line is connected. Add an extra wire if it isn’t.

Note that these changes are not permanent; they will be lost during a power cycle (install a battery to prevent this from happening), or reverted using another command. [5]

1
$ echo -e '$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n' > /dev/ttyAMA0

This command squelches all of the other NMEA sentences and only outputs $GPRMC, making everything tick a little more efficiently. To verify that the proper sentences are being output, run:

# Tap CTRL+C to exit
$ cat /dev/ttyAMA0
$PGTOP ....
$GPRMC ....

In certain cases, it may take several tries in order to get the unit to recognize the command properly.

If you’re interested in playing around with the outputs, check out this PDF, and use this checksum calculator to get the value at the end (this means that if we change the line above, the *29 value changes when the command changes.. so we would need to calculate a new checksum!).

Lights!

On a system with ntpdate (a Linux or OS X system usually has this utility), we can query the Raspberry Pi to get and/or set the time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$ ntpdate -vdq 192.168.1.101
24 Dec 04:13:42 ntpdate[8390]: ntpdate 4.2.6p5@1.2349-o Fri Apr 27 08:36:47 UTC 2012 (1)
Looking for host 192.168.1.101 and service ntp
host found : 192.168.1.101
transmit(192.168.1.101)
receive(192.168.1.101)
transmit(192.168.1.101)
receive(192.168.1.101)
transmit(192.168.1.101)
receive(192.168.1.101)
transmit(192.168.1.101)
receive(192.168.1.101)
server 192.168.1.101, port 123
stratum 1, precision -19, leap 00, trust 000
refid [GPS], delay 0.02612, dispersion 0.00000
transmitted 4, in filter 4
reference time:    d482c575.72b3b105  Mon, Dec 24 2012  4:13:41.448
originate timestamp: d482c57c.9e9ef4c5  Mon, Dec 24 2012  4:13:48.619
transmit timestamp:  d482c57c.9d24334c  Mon, Dec 24 2012  4:13:48.613
filter delay:  0.02621  0.02617  0.02612  0.02620 
         0.00000  0.00000  0.00000  0.00000 
filter offset: 0.005206 0.005221 0.005233 0.005197
         0.000000 0.000000 0.000000 0.000000
delay 0.02612, dispersion 0.00000
offset 0.005233

24 Dec 04:13:48 ntpdate[8390]: adjust time server 192.168.1.101 offset 0.005233 sec

If the last line says “Server dropped: Leap not in sync” – it may take some time for trust in the time to be established. This tends to be on the order of minutes; if it happens, wait around 26 to 30 minutes and try again.

Integration

Ideally, this itself would be automated somehow. Each system has a time setting that allows you to set the time sync source.

OS X

Click the time at the top right, and click Date & Time Preferences. Type in your Raspberry Pi’s address next to “Set date and time automatically.”

Linux

If using a desktop, this tends to be handled in a GUI menu. If not, check to see if you have, or can install a NTP daemon. Then edit ntp.conf (usually located in the /etc/ directory) and set the server stanza as appropriate.

Windows

Windows users can also right click the time, click the Adjust Date/Time option, click on Internet Time (tab), then Change settings, and type their Raspberry Pi’s address into the box. Click Update now for effect.

Thanks & Updates

This will be a perpetually updating post as I fine-tune and discover new things to do.

Special thanks to everyone in this thread over on the Raspberry Pi forums who paved the way for this lengthy documentation.

Note: No consideration (except for great customer service) was given to me by Adafruit for writing this. I did win an unrelated prize a few days ago that I should dig into though (OHS bag of swag).

11/12/12: Thanks to @karldyson for reporting that PPS was not being picked up properly by the repository packages. Looks like that bug is still there!

12/24/12: Added information on calibrating Adafruit’s GPS module (including references) and updated offset in configuration. Clobbered the introduction and added more spelling errors/walls of text to confuse/clarify things a bit.

1/15/13: Changed the hardware voltage warning (fixed non-serious typo). Also tried to un-break formatting for note #5 and redirected help to a more proper place.

02/05/13: Added a reminder to connect the proper line before working on the Adafruit GPS module.

02/06/13: The DAEMON line in /etc/init.d/ntp had a typo, and should be /usr/bin/ntpd (due to the prefix used).

03/03/13: Thanks to both Sven Wunder and @davidmonro_ for reporting that pps-tools needs to be installed during a compile of NTP from source. Sven has a detailed report here.

05/09/13: Collapsed the configure line (it was tested to be cut and paste friendly), and reduced the amount of make by one.

Extra Information on NTP

This includes a discussion about how a proper NTP setup should look like (having three servers to sync time is a good idea).

Notes & References

  1. http://en.wikipedia.org/wiki/Network_Time_Protocol#Clock_strata
  2. The kernel fork I used and modified is available here. Look under the ppsgpio branch. You can clone it or download the entire thing by clicking around.
  3. http://doc.ntp.org/4.2.6p5/confopt.html
  4. http://www.eecis.udel.edu/~mills/ntp/html/drivers/driver20.html
  5. Note that this disables select sentences, so if you’ll be re-purposing your Adafruit GPS unit in the future, you may use this command to reset it to its default sentences:
1
$ echo -e '$PMTK314,-1*04\r\n' > /dev/ttyAMA0

If that fails, removing the battery and unhooking the power for your unit will usually revert it to its old behavior.

Further Help

If you need help, send me a tweet. I am @bytecounter on Twitter. For longer issues with massive logs, try booking something here.

cheers!

AVR Programming With Adafruit’s Atmega32u4

Introduction

This guide will help you build your own LUFA AVRISP-MKII clone using the Adafruit Atmega32u4 breakout board.

Build Materials

Linux

You will need Linux as a base for programming and compiling the LUFA project’s code. Using another operating system is possible, but won’t be covered here (sorry!) If you don’t have a dedicated Linux installation, try a Linux live CD and install the packages below to program.

Installation of AVR tools are provided for the Ubuntu and Fedora Linux distributions.

Adafruit Atmega32u4 breakout

A modified LUFA CDC bootloader comes pre-installed on these. This allows the chip to be programmed without an external programmer (at the cost of some memory space).

Atmega32u4 with ISP and programming reset line connected

For programming breakout boards, a 6-pin cable is attached to the programmer. A wire is hooked up to B4 (which connects to the target AVR’s RESET pin).

Note that without modification, the RESET line will trigger on the 6-pin cable as a part of the programming process through B4. Since the 6-pin cable connects RESET between both target and programmer, the programmer itself will reset when B4 is asserted (which ends the attempt). This gets worked around a little bit later by splicing into the wire.

This method is mostly optional, but useful since some breakouts are only programmed easily through the header.

Breadboard, wires, and maybe a ZIF socket

It is also possible to use a breadboard to program a chip. A completed layout looks something like this.

Breadboard Atmega32u4 ISP programmer targeting ATmega328P

There are problems with this setup:

  1. Removing the programmed chip may be difficult/annoying. A ZIF (zero insertion force) socket may be appropriate if programming a large quantity of chips.

  2. Depending on fuse settings, the recovery clock (or, as seen in the picture, a resonator) may be needed in order to program the chip properly. Breakout boards usually have some sort of clock source installed.

For most, it may be better to program using a dedicated PCB that has the 6-pin header broken out. This might be an Arduino for Atmega328Ps, or the BB313 for ATTiny chips.

Here are the necessary connections from the Atmega32u4 breakout to the chip being programmed (if using a breadboard):

Connections for breadboard

32u4 -to-> Target chip
B1   ----> SCK    (Arduino Digital Pin: 13)
B3   ----> MISO   (Arduino Digital Pin: 12)
B2   ----> MOSI   (Arduino Digital Pin: 11)
B4   ----> RESET  (Arduino Analog  Pin: A6)

GND  ----> GND    (Note: 1)
VCC  ----> VCC    (Note: 1)

Recovery Clock    (Note: 2)
B5   ----> XTAL1  (not needed for Arduino boards)


1. There may be extra tie in points for these.
   Check the datasheet to be sure.
2. The recovery clock can be used if your fuses are set incorrectly.

   If using the recovery clock, be sure to set the programing speed to 125KHz
   1/125000Hz = 8x10^-6 seconds (or 8 microseconds, since 1 microsecond -> 1x10^-6 seconds)  
   For avrdude add this as a parameter to set the microsecond bitclock period: 
            -B 8 
  • Optional (for a more compact setup): 6-pin IDC cable

A 6-pin cable will stop the programmer from becoming a bundled mess of wires. This works since most of the necessary pins (MISO/SCK/VCC/MOSI/GND) are broken out to the header. However, since both RESET lines are connected, the programmer itself will be reset if connected without modification.

Modified 6-pin IDC cable

Here is an example of the 6-pin cable which has been cut with a sharp knife. The line to cut is the 5th wire, starting from the red line as shown in the picture. If you aren’t sure, verify with a multimeter that the line is indeed the one used for RESET.

To verify: With your spare Arduino or other breakout board, just plug a wire into the RESET line (connected to a lead on your multimeter in continuity test mode – aka ‘beep beep beep’ mode), and connect the 6-pin header (red stripe to small dot, or box connector “tab” to the proper place). Poke the small wires coming out of the box to check. You may need to press with a bit of force.

Probing 6-pin IDC cable

For the absolutely paranoid, pulling apart the box connector may be a good idea.

Other ways around cutting up your cable: fuse manipulation, designing your own PCB (as some have), cutting header pins, etc. If you end up using this particular method, soldering up a detachable wire to the cable’s RESET (then connecting to the programmer’s B4 pin) might be a worthwhile project.

  • Female/Female jumper wire(s) (Female/Male, Male/Male, etc)

A wire to connect the reset line (B4) and other pins. You might need a single piece of male header to tie the jumper wire to your destination board. The RESET line is triggered using this connection.

Finding your board

Linux

I’m using Linux, so when I plug in the board this shows up after typing dmesg into a terminal:

1
2
3
4
5
[15138.776119] usb 3-1: new full-speed USB device number 51 using xhci_hcd
[15138.791800] usb 3-1: New USB device found, idVendor=239a, idProduct=0001
[15138.791806] usb 3-1: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[15138.791808] usb 3-1: Product: AVR CDC Bootloader
[15138.793350] cdc_acm 3-1:1.0: ttyACM0: USB ACM device

ttyACM0: USB ACM device on the last line is where data gets accepted. There are a myriad of other ways to figure that out, but parsing dmesg will tell us if it failed to enumerate somehow.

Download LUFA (Linux)

The next step from here is to download the files necessary to load the programmer. Run the following (after acquiring git [1]).

1
2
3
4
5
6
7
$ git clone https://github.com/davidk/lufa.git
Cloning into 'lufa'... 
remote: Counting objects: 52669, done. 
remote: Compressing objects: 100% (10637/10637), done. 
remote: Total 52669 (delta 42901), reused 51050 (delta 41412) 
Receiving objects: 100% (52669/52669), 9.49 MiB | 497 KiB/s, done. 
Resolving deltas: 100% (42901/42901), done. 

This is a small fork of Dean Camera’s LUFA project (a framework for developing USB-enabled AVRs). Of interest is Dean’s clean-room copy of the AVRISP-MKII programmer, which turns the Atmega32u4 breakout into a programmer for other AVRs (egg, meet chicken). Run the following from outside the lufa directory.

1
2
3
4
5
$ cd lufa/Projects/AVRISP-MKII/
$ git checkout atmega32u4-avrisp
  Branch atmega32u4-avrisp set up to track remote branch 
  atmega32u4-avrisp from origin.
  Switched to a new branch 'atmega32u4-avrisp'

Once you’re in the branch, ensure that your avr utilities are installed.

For Fedora users:

1
$ sudo yum install avr-binutils avr-gcc avr-libc avrdude

Ubuntu users:

1
$ sudo aptitude install gcc-avr avr-libc avrdude

Programming (check to see if your boot light is fading in and out, if not, press the white button and run the following):

1
$ sudo make avrdude AVRDUDE_PROGRAMMER=avr109 AVRDUDE_PORT=/dev/ttyACM0

Connect the programmer

If it all went well, you now have a programmer.

ISP programming Arduino Uno

Remember: The single red wire goes from B4 to the Arduino’s RESET pin.

Start your engines

At this point, all the hard work is done! Before programming, make sure that the RESET line is connected to B4. avrdude can be used to program a board by running it as such:

1
2
3
4
5
# For Atmega328P chips
$ sudo avrdude -patmega328p -cavrispmkii -Pusb -Uflash:w:Blink.cpp.hex

# For an Attiny4313
$ sudo avrdude -pattiny4313 -cavrispmkii -Pusb -Uflash:w:blinky.hex

An example session (targeting an Attiny4313 with the blink program from the bb313 website):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 $ sudo avrdude -pattiny4313 -cavrispmkii -Pusb -Uflash:w:blinky.hex
 [sudo] password for davidk: hunter2

 avrdude: AVR device initialized and ready to accept instructions

 Reading | ################################################## | 100% 0.00s

 avrdude: Device signature = 0x1e920d
 avrdude: NOTE: FLASH memory has been specified, an erase cycle will be performed
      To disable this feature, specify the -D option.
 avrdude: erasing chip
 avrdude: reading input file "blinky.hex"
 avrdude: input file blinky.hex auto detected as Intel Hex
 avrdude: writing flash (60 bytes):

 Writing | ################################################## | 100% 0.02s

 avrdude: 60 bytes of flash written
 avrdude: verifying flash memory against blinky.hex:
 avrdude: load data flash data from input file blinky.hex:
 avrdude: input file blinky.hex auto detected as Intel Hex
 avrdude: input file blinky.hex contains 60 bytes
 avrdude: reading on-chip flash data:

 Reading | ################################################## | 100% 0.02s

 avrdude: verifying ...
 avrdude: 60 bytes of flash verified

 avrdude: safemode: Fuses OK

 avrdude done.  Thank you.

programming a bb313

Programming without using ‘sudo’ or root (Linux)

Running avrdude as root is kind of excessive, even temporarily. To run it as a normal user, we can eck out the following to make it work properly:

First run groups to get the list of groups your user currently belongs to:

1
2
$ groups
davidk dialout wheel

This determines what we set in the GROUP=”” field below (in this case i’ve picked wheel):

1
2
3
4
$ sudo su
# echo 'ATTR{idVendor}=="03eb", ATTR{idProduct}=="2104", GROUP="wheel", MODE="0666"'
>> /etc/udev/rules.d/60-avrispmkii.rules
# udevadm trigger

Thanks

Special thanks to Dean Camera, who saw that I was making changes to my fork on Github (which is a mirror of his SVN repo) and stopped by my lowly branch to suggest a small change. Good guy (he did it again too, on an unrelated branch).

Problem?

Tack on something here. I will try to help or spin you in the right direction. If you use twitter, i’m @bytecounter.

Reference(s)

[1] Get git via your preferred package manager, or check out http://git-scm.com.

Updates

01/15/13: Added information on using avrdude in a non-root fashion for Linux. Also threw in some magic to make console stuff pretty.

Music

A bit of Ruby to start things off (I guess I should say ‘test’ in here too).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env ruby

class Music
  attr_accessor :id, :artist, :title, :album
end

songs = Array.new

ARGV.each do |m|
  f = File.open(m)
  while (l = f.gets)
    info = l.split(';')

    if info.length > 0
      song = Music.new
      song.id = info[0]
      song.title = info[1]
      song.artist = info[2]
      song.album = info[3]
      songs << song
    end
  end
  f.close()
end

songs.each do |s|
  puts "#{s.artist} - #{s.title} - #{s.album}"
end