Skip to content

Xmega DFU Bootloader – Changing the Sensing Pin

The DFU bootloaders that Atmel supplies, as Intel HEX files, for its Xmegas have pre-determined pins used to sense whether or not to skip the bootloader and start the application, or to register the device to the host PC via USB. These are slightly hidden on the Atmel website and the source code requires IAR to compile it (and an easy port to AVR-GCC is thought to be impossible on size grounds). A number of threads on AVRFreaks have discussed this matter, including: “Building bootloader for ATXMega16A4U from” and “Where’s the DFU bootloader?“. I didn’t fancy installing IAR, but was intrigued by comments about dis-assembling the HEX files and tweaking bytes. The process was not explained, but in spite of starting off totally “in the dark”, an evening of fumbling and fiddling got me through to a result that worked. This post explains the process, in case anyone else wants to do the same. It is also my notes-to-self for when I forget!


The Atmel application note AVR1916 has essential background info and the associated zip file contains the Intel HEX files for different xmega chips. The zip file also contains source code but: a) this needs IAR (see intro); b) it is deeply hard to follow!

Atmel AVR1916: USB DFU Boot Loader for Atmel XMEGA: pdf zip

The zip file is not so easy to find by google/bing; you pretty much have to go to the Atmel site, find the xmega section, go to documents, and select “application notes” from the drop-down.


There are probably lots of options, but I used:

  • avr-objdump, which is part of the avr-gcc toolchain. I used a recent toolchain download from the Atmel site. If you use Atmel Studio, look in {install directory}\Atmel Toolchain\AVR8 GCC\Native\3.4.1061\avr8-gnu-toolchain\bin.
  • Tiny Hexer by Markus Stephany. This is available from numerous places on the web, although not from the author’s original site .


In what follows, I am dealing with an ATxmega32A4U. The method should translate to other chips very easily. I am ONLY concerned with changing which pin is sensed on a hardware reset to determine whether to start the application or wait for USB communication of a new application.

From a command window, execute:

avr-objdump -m avr -D file.hex >> disassembly.txt

That looks somewhat daunting to a non-assembler hobbyist person like me but it turns out not to be quite as bad as all that. The key thing to note is that we’re looking for references to a single I/O pin. Which pin it is may be found in AVR1916.

Default pin configuration table from AVR1916.

Default boot-sensing pin configuration table from AVR1916.

So, for my target it is Port C, pin 3. Consulting the xmega manual…

Base IO memory map addresses for the GPIO ports.

Base IO memory map addresses for the GPIO ports.

IO port memory map offsets (apply to all ports, simply add to the base address for the port to get the address of the appropriate register)

IO port memory map offsets (apply to all ports, simply add to the base address for the port to get the address of the appropriate register)

So, setting the direction for port C will address 0×0640 (offset is 0) and PIN3CTRL will be at 0×0653 (offset is 0×13).

To cut a long story short, the important lines in the disassembly are:

    800a:    f0 92 40 06     sts    0x0640, r15
    8010:    00 93 53 06     sts    0x0653, r16
    801c:    00 91 48 06     lds    r16, 0x0648
    8020:    03 ff           sbrs    r16, 3
    80de:    f0 92 53 06     sts    0x0653, r15

As an exercise, work out which registers are being accessed. The STS and LDS commands are direct store and load instructions. SBRS is “skip if bit in register is set”. In this case we can see bit 3 is being used, which is as it should be, and the value in register 16 is the IN value for the port.

Suppose we want to change the sensing pin to be Port D pin4 (physically pin 24 on a 44 pin xmega). This indicates a base address of 0×0660 and changing the instructions to:

STS  0x0660, R15
STS  0x0674, R16
LDS  R16, 0x0668
SBRS R16, 4
STS  0x0674, R15

Open Tiny Hexer and import the Intel Hex file appropriate to your chip from the AVR1916 zip file. Now it is just a case of changing the hex representation of the appropriate bytes. Note that the byte order of 0×0640 is reversed in the disassembly and in the HEX file. Here are some screenshots of Tiny Hexer after changing the required bytes:


Now export from Tiny Hexer as Intel HEX, saving with a new name (!).

At this point, it is a good idea to run avr-objdump again, on the new HEX file, to make sure that it still makes sense to an AVR. I also did a file-diff on the new vs original disassembled files. The results are as follows, although there is also a block of FF that got inserted between code blocks. This has no effect, and simply reflects the fact that Tiny Hexer exported a continuous block rather than two blocks with a space in between.

Compare PC3 PD4 a

Compare PC3 PD4 b

Looks like I got it right! Only the instructions I wanted to change got changed, and the flash memory addresses came out correct for a bootloader.

All that remains is to program this onto the chip with your programmer of choice (I use the Olimex AVR-ISP-MK2 clone since my Dragon utterly fails to even get the device ID 95% of the time), making sure the BOOTRST flag is correctly set if it is a new chip. Erase the chip, program and go!

A Cheat

If you can find two HEX DFU bootloader files for the same target chip, but with different sensing pins, a quick thing to do is to disassemble both and do a diff. I bet they will be from the same basic source code, and will quickly reveal which instructions need changing. Confession: that is how I got started on this problem.

Uploading Using DFU

To be honest, I think FLIP is a bit rubbish, and using the command line batchisp.exe is a pain in the arse. I’ve found dfu-programmer to be much nicer to play with (although the 0.7.1 version does contain a bug that fails to account for the xmega bootloader living in separate flash and so reduces the available flash for applications; this is fixed in 0.7.2 but is not released AFAIK at the time of writing).

I use dfu-programmer from Atmel Studio as an “external tool” via a small “bat file” command script.

In Atmel studio, point the external tool command at the .bat file and add the following into the “arguments” slot:

"$(ProjectDir)Debug\$(ItemFileName).hex" atxmega32a4u

To work, you do need to select the project file with the same name as the hex file before invoking the tool.

My .bat file just contains:

@echo off
REM supply the hex file location as 1st argument e.g. "dfu-programmer script argument blink.hex",
REM supply the target device as the 2nd arg e.g. atxmega32a4u

ECHO Erase, flash %1 and application launch.
ECHO Device = %2
ECHO ==========================================================

SET PATH=%PATH%;C:\Users\Adam\Desktop\dfu-programmer
dfu-programmer %2 erase --force
dfu-programmer %2 flash %1 --debug 2
dfu-programmer %2 launch --no-reset
ECHO -----------------------------------------------------------

Further Adventure?

I have not done this, but see this line:

    800e:    08 e1           ldi    r16, 0x18    ; 24

That is setting the value of register 16, which is immediately stored to PIN3CTRL in the original code. A quick look at the datasheet shows that, as expected, this is setting a pull-up on Port C pin 3. Fancy changing that?

… Or maybe change the SBRS to SBRC ?

Decoding microKorg Patch Files (.prg) to PlainText

MicroKorg “prg” files files are downloaded from the microKorg by the Korg Sound Editor software, and are often posted online (e.g. the microKorg sound bank). But sometimes it is nice to be able to see what the patch is, or post it online in a plain text form. Plain text patches are also a handy way of documenting your own patches in a nice durable format: on paper. Also, if you want to share a patch, posting a readable version of the patch is a nice thing to do, and ideally without having to work your way through the whole matrix, transcribing the settings. Transcribing settings is boring, error-prone…

I have written a small program to convert “.prg” files for the microKorg to a nice readable format. So, if you have Sound Editor working, you can just download your custom patches, locate the place where the .prg files are stored, and away you go. Similarly, it is really quick to see what the Korg sound bank patches (or whatever) are doing at a glance, which I find is a good way of working out the tricks…

e.g. If you drop the “atmos” patch from the microKorg sound bank, you get:

 [Voice]: Synth , Single , Poly , -- , --
 [Pitch]: 0 , 0 , 0 , 2 , 0
 [Osc 1]: DWGS , 0 , 48 , -- , --
 [Osc 2]: Saw , Sync , -12 , 0 , --
 [Mix Levels]: 127 , 91 , 0 , -- , --
 [Filter]: -12dB LP , 101 , 50 , 0 , 0
 [Filter EG]: 0 , 64 , 127 , 0 , yes
 [Amp]: 127 , cnt , on , 0 , --
 [Amp EG]: 0 , 79 , 0 , 53 , yes
 [LFO 1]: Triangle , Off , off , 59 , --
 [LFO 2]: Sine , Off , off , 70 , --
 [Patch 1]: LFO1 , Pitch , 10 , -- , --
 [Patch 2]: Mod Wheel , Cutoff , -63 , -- , --
 [Patch 3]: LFO1 , Cutoff , 0 , -- , --
 [Patch 4]: LFO2 , Cutoff , 0 , -- , --
 [Mod FX]: Ensemble , 20 , 56 , -- , --
 [Delay]: Stero , off , 80 , 74 , --
 [EQ]: 320Hz , 0 , 6kHz , 0 , --
 [Areggio A]: 120 , 1/16 , 100% , Up , 1
 [Arpeggio B]: off , 0 , off , 8 , Both
 [Arp. Pattern]: yes,yes,yes,yes,yes,yes,yes,yes
 [Arp. State]: off

It only works for single-patch files right now, but is can be used for single and layered patches and vocoder patches. On most web browsers (recent versions of Firefox, Chrome, Internet Explorer), you should be able to drag-and-drop a .prg file. Otherwise you have to use the old-school “Browse” button. There is more technical information on the decoder page, and a link to report bugs or make suggestions (although you can do that as comments to this post if you do not wish to create a GitHub account).

Orchard Common and Drystone Edge Geological Field Trip Notes

The following are field notes from a visit to the valley just to the W of Drystone Edge to inspect the Upper Namurian, especially the Ringinglow coal outcrop and associated seatearth and marine shales (contorted beds). The locations were logged using a Garmin GPS60, and may be downloaded in GPX format. The points are named in the format “ORC %N”, and referred to below.

ORC 001 -  SK 02262 68251 – Roadside parking.

Proceed N up the road to Readyleech Green. Just past the house, the road swings NW, following a fault with downthrow on the SW side. To the right is the Upper Namurian Chatsworth Grit (CG), while the higher ground to the W of the road (Knotbury Common) is Westphalian (Coal Measures) Woodhead Hill Rock (WH). The right of way track around the S side of Knotbury Common approximately follows the lower boundary of the WH.

ORC 002 – SK 02198 69014 –  Shaft Hummock. This is in the shales between the Chatsworth Grit (CG) and Rough Rock (RR). The coal sits just above the CG.

Section through Drystone Edge and Orchard Common

Section through Drystone Edge and Orchard Common looking North

At this point you are on Open Access Land. Descend to the stream, which is easy enough if you follow the fence approx Southwards on its stream-side.

ORC 003 – SK 02170 68842 – Good clean exposure just above the stream bed of  CG followed by seatearth then coal. There may be a detectable marine band here but I didn’t look. The seatearth shows interesting patterning. There is also some evidence of fossilised vegetation.

ORC 004 – SK 02330 69112 – Contorted Bed.

ORC 005 – SK 02319 69450 – Quarry in Rough Rock. Look at the texture, grain size, bedding etc to compare with CG on Drystone Edge (ORC 009). The top of the RR is the top of the Namurian; a band of marine shale with distinctive fossils marks the bottom of the Westphalian (Coal Measures).

ORC 006 – SK 02598 69608 – Contorted Beds.

ORC 007 – SK 02680 69725 – Some nice pieces of loose coal (apparently not in situ, but 5-10cm longest dimension).

ORC 008 - SK 02781 69373 – CG boulders showing Karstic features.

ORC 009 – SK 02698 69152 – Scarp exposure of CG on Drystone Edge. Look NW towards the RR quarry visited earlier and consider the section (above), which follows the same line.

A 5km x 5km square of the solid geology with a lower left corner at SK 000 650 may be obtained using the British Geological Survey map server using the link,365000,405000,370000&WIDTH=500&HEIGHT=500

These are personal notes, shared for whoever may find them useful. I am not a qualified geologist; more details may be found in the Geologist Association Guide No. 26, by F. Wolverson Cope. I used this book to visit the site, although the account above contains additional sites, and more precise location for some of Cope’s sites.

Look up: upper carboniferous cyclothems.

Route Between Crowden Clough and Kinder Downfall

The lay of the land and the nature of the water channels probably makes this route over Kinder Scout easier to find when taken from Crowden Clough to Kinder Downfall. The path is generally visible but a compass is necessary equipment to avoid being misled in poor visibility. HOWEVER, the right of way marked on the OS map appears not to be the way people go, and an attempt to follow this route with a GPS is likely to be an unhappy experience (Google/Bing will reveal stories).

In case anyone should wish to follow a GPS track, or to compare an on-the-ground route with the OS map, here is my track log.

Crowden Clough to Kinder Downfall GPS track log (GPX format). This was (for me) a fairly obvious and reasonable route.

Panelising PCBs for Seeed – Eagle and Gerbmerge

The problem of panelising PCBs created using the free version of Eagle and gerbmerge is described in an instructible but I found a couple of issues when creating gerbers for Seeed Studio. This outlines the issues and my approach in brief; it is mostly a public note to myself to remember what  to do next time. The account that follows assumes the guidance in the instructible is followed by default.

The issues stem from use of the “.BOR” and “.GML” gerber layers. Seeed’s instructions do not mention BOR files and they do say that the board outline should be in a GML file, which is supposed to be the milling control. My guess is that if you do not send a GML file, Seeed will use whatever is in the silk layer to guess the board outline. My board had some milled slots for a power connector.

Step 1 – make sure the CAM file emits the right Eagle layers to the right Gerbers

Start the CAM processor and open the CAM file provided by Seeed. It would be silly not to!

Click the “Add” button to create a new job section. Change Job|Section to (e.g.) Board Outline and change the output device to GERBER_RS274X. Style should have only “pos.coord” and “Optimize” ticked. Change the file name to %N.BOR

Select layer Nr 20 (Dimension).

That defines the .BOR file that gerbmerge needs to lay out the panel.

Next, select the “Slot drills/holes” tab. Note the file is %N.GML. Layers 20 and 46 should be selected. De-select layer 20.

Save the file (with a new name) and execute the CAM processor. Here is my variant CAM file: Seeed_Gerber_Generater_v0r95_DrillAlign + BOR and GML separated for gerbmerge ONLY.

Note that this should probably not be used for creating gerbers for a board that will not be panelised because the GML file does not contain the board outline as Seeed request.

Step 2 – edit the panel.cfg file for Gerbmerge

Note the existing lines “BoardOutline=%(prefix)s.bor”, one for the merged output and one for each sub-board. These stay as they are.

If there is any milling (check by looking at the GML in a gerber viewer, if you don’t already know), add “*Milling=%(prefix)s.GML” on a separate line in each of the sections where “BoardOutline=%(prefix)s.bor” appears.

Make sure the line “OutlineLayerFile = %(mergeout)s.OLN” does not begin with a “#” character.

Step 3 – panelise and hack

Run gerbmerge as normal.

Note that if there is no milling, is should work fine to rename the merged output OLN file as GML.

Otherwise… a bit of cut and paste hackery is needed to get the final merged board outline and the in-board milling into the GML file. Copy the section from just below the line with only a % character to the end of the OLN file and paste this into the merged GML file just below the same point, making sure that the last line from the OLN does not get merged with an existing line in the GML.

Now check all the panelised gerber files in a viewer!

This information is provided without warranty; if your boards come back wrong its your fault, not mine.

Using Mapyx Quo to Create Virtual Field-trips with Google Earth

This post describes an approach I have adopted to create virtual field trips using Mapyx Quo as a starting point to produce interactive annotated virtual field-trips. The initial impetus was to look at the geology around Millers Dale, specifically at the outcrops of the Millers Dale Lava Beds. Details of this trip will follow in the next post.

Quo is reasonably good but the KML exports it produces loose some of the folder-like structure that can be used inside Quo. It alsi has the very annoying feature of inserting timings into all “tracks”, no matter whether theses are logged from a GPS or inserted using a mouse or tablet inside Quo. Tracks are the best way to define areas and linear features for visualisation in Google Earth but timings and associated waypoints just make for clutter. Furthermore, the colours set for tracks and waypoints in Quo is lost on export.

My solution was to write some software (for MS Windows) to:

  1. tidy up the KML export, removing unwanted aspects and putting back some folder structure
  2. generate a javascript configuration file to drive a web page that uses the Google Earth Plugin (API)

The resulting KML may be used with the desktop Google Earth or from a web page (with #2 as the intended case).

The source code is available on GitHub, with an MIT licence. At some point I will produce an installer (sooner if someone asks). The source code should be consulted for specifics that are omitted from this post; there are sufficient comments for non-readers of C#.Net.

There are a number of assumptions about how Quo will be used, and how the software (Quo2GE) will be used, and this post is really an aide memoir for myself.

Organising Waypoints and Tracks in Quo

In Quo, create three groups (or two groups and make the first two be layers within the same group), and as content as follows:

  1. A group for points of interest.
    • Within this, create waypoint sets. For each set, specify a different “Point Name Pattern” consisting of a number of alpha-numeric characters followed by “-%N”. The characters comprise a prefix that will be used in Quo2GE to group the waypoints (Quo destroys its own group/layer/waypoint-set structure on export to KML). Note that the “-” sign MUST be present.
    • Any routes will be ignored by Quo2GE.
    • Quo2GE assumes three types of waypoint sets, which can be assigned ad hoc: sites to visit, landmarks, and places that make good viewpoints. These are treated slightly differently by Quo2GE, see below, with implications: for landmarks, add the name of the landmark to the “Note” field for each waypoint; for viewpoints, a place to look at from the viewpoint may be specified by adding to the “Note” field a “@” character followed by the name of any other point of interest, followed by a space character if it is not at the end of the “Note”.
  2. A group containing the walking/driving routes and maybe waypoints at key turns.
    • The waypoints will be ignored by Quo2GE but may be useful if a GPS is used in the field.
    • Several routes may be added, for example to break an over-long route into more walkable units or to separate walking and driving routes. Distinguish the routes by prefix, changing the default “Track 1″ etc to something more meaningful. Note: for routes, use a space character (rather than “-” as before) to separate the prefix from the index number. Use different prefixes to allow different groups of 1 or more tracks to be separated in Google Earth. Otherwise use the same prefix.
  3. A group containing geological/geographical features designated using the Quo “track” tool.
    • Use layers to organise the features by type, e.g. a layer for geological faults.
    • Within each layer name the tracks with a prefix followed by a space and then an index number. e.g. “Fault 1″, “Fault 2″ etc. The prefix is used by Quo2GE to group the features and to allow different colours to be used for each group.
    • Waypoints will be ignored by Quo2GE.
Example of Quo structure.

Example of Quo structure.

Export each of these as a separate KML file (right-click on the group or layer and “Export to…” (file), selecting Google Earth (kml) as the file type).

Quo2GE should work if any of the above groups/layers are omitted.

Using Quo2GE


Use “Set Output Folder” to locate the KML files exported from Quo. The same folder will be used for the output of Quo2GE.

Load each of the exported KML files using the appropriate tab. The list on the left (with check-boxes) should enumerate all of the prefixes used for waypoint or track names in Quo. Use the checkboxes to de-select any that you do not wish to see in Google Earth.

For each prefix, the colour to be used in Google Earth may be changed, as may the title (which is initially set to the prefix). The title will be shown in the web page to allow groups of waypoints or tracks to be shown or hidden. They also appear as folder names in Google Earth Desktop.

For points of interest, there are three types that can be assigned to each prefix-set. The points are handled differently in Quo2GE and in the web page:

  1. Points of type “Site” are intended for places a person would visit. In the virtual tour, users can jump to have an aerial view of any of these. The points are shown in Google Earth with the waypoint name, e.g. WPT-002.
  2. Points of type “Landmark” are intended as key landmarks (!). They are shown in Google Earth with the waypoint Note (e.g. “Hammerton Hill”).
  3. Points of type “Viewpoint” are intended as places a person would view their surrounding from (in real life and in the virtual tour). In the virtual tour, users can choose to go to these places; the Google Earth view changes to a near-ground-level view looking north, or towards any point specified in the Quo waypoint Note using “@”.

Set the Main Title and click “Export”.

Using the Output

Several files will be created in the chosen output folder. Those starting “clean” are tidied-up versions of the KML files exported from Quo but without any organisation into folders, application of styles according to Quo2GE. The file allSets.kml has been produced from the cleaned KML and does contain the folders and styling. Use this with  Google Earth desktop.

Use on the web requires use of allSets.kml, gm.html and config.js. hg.html reads config.js to locate the kml file to be used and to set the controls that appear in the web page to allow the view to be manipulated.


  • edit config.js so that the kmlHref variable contains the full URL to the ultimate location of the allSets.kml file.NOTE: the kml must be on a web server for the Google Earth plugin to be able to use it, although you can run gm.html from your local machine.
  • add text, change styling etc for gm.html according to your taste.
  • copy all three files to the web space.
  • enter the URL for the gm.html file in your web browser…. it should all appear!

As an alternative, which may be useful if you have several virtual field trips is to place the gm.html file in one folder and to create sub-folders for each trip, which contain the kml and js files. In this case, tell gm.html the name of the sub-folder (e.g. “trip1″) by adding it to the end of the URL, after a “?” (e.g.

Change Wheel Calculator for Warco 918 Lathe

Here is a spreadsheet to calculate all the thread pitches possible on a Warco 918 lathe using the change wheel set provided with the machine :  XLSX (newer versions of Excel) and XLS (Excel 97 and 2003, also works in LibreOffice/OpenOffice).

The cells are all locked except D4, which should be set to “y” or “n” depending on whether the 120/127 tooth gearing will be in use (see the plate attached to the lathe). Note that there are three worksheets for mm/rev, inch/rev and tpi.

Use should be self-evident, but in case not, here is an example.

Looking at the “mm per rev” sheet:

  • Put “y” in cell D4 because that gives results in nice round numbers
  • Assume you want 1.5 mm/rev
  • See this appears in four cells: I13, I14, F19 and C24
  • Choose F16 (on a whim, or maybe you already had a 36 tooth wheel in position b)
  • Change-wheels (where a and b are as on the plate attached to the lathe) to use are: a=45 tooth and b=36 tooth
  • The gearbox should be set to no. 4
  • Note that the Warco lathe-plate gives the C24 configuration.

If unsure, check you understand it by choosing a few of the pitches given on the lathe-plate and confirming that the change-wheels and gearbox settings you determine from the spreadsheet match the “right answer”.

Warning: I might have made a mistake so always try out on a piece of scrap and measure the result.


Making a Trepanning Tool – Notes and Plans

I’m planning on cutting some gear wheels and, having struggled with using a hole-saw to cut blanks, decided a trepanning tool was probably the answer.

The tool is only meant for cutting 1/8″ thick stock. Tested on brass and aluminium (may not be up to the job with steel). Use low speeds and if you don’t know what you are doing, don’t do it!

The Finished Trepanning Tool

The dark colour of the main body is due to a (failed) attempt to case harden the pilot; it is just uncleaned scale from from heating. I actually found the setup to be sufficiently rigid that the pilot didn’t take any load with 1/8″ brass and the narrow cutting tool shown below in the bottom right of the picture.


Trepanning Tool (click for larger size)

Trepanning Tool (click for larger size)

The Plans

These are not proper dimensioned drawings in an engineering sense, and were produced as part of the design process, but they should be sufficient. Stock used was steel 1″ dia bar and 3/8″ square.

Trepanning Tool Assembly (click to open full-size image)

Trepanning Tool Assembly (click to open full-size image)

Also available as a DXF File.

Brief Construction Notes


Cut 1″ dia stock to slightly over length

3 jaw chuck :-

  • face off (light cuts), centre drill and support with tailstock centre
  • turn down 1/2″ shank
  • brighten up about 1/4″ of 1″ dia body (used later for concentricity setting with DTI)
  • cross-drill, widening progressively to 7/16″ (ideally finish to size with reamer)
  • drill and tap M5 (and shorten M5 cap screw to match)

4-jaw chuck :-

  • hold using 1/2″ shank, adjust to near zero runout with DTI
  • turn pilot (should be concentric with shank)

Cutter Arm

3/8″ square stock

4-jaw chuck :-

  • face off both ends (low overhang from chuck)
  • centre-drill second end, loosen 2 adjacent jaws, withdraw from chuck and support on centre, retightening the jaws to same setting
  • turn to 7/16″ dia to fit arbor

Pillar drill :-

  • drill and ream 3/16″ for cutting tool
  • drill 1/8″ for end of slot
  • drill for clamp bolt (M4 tapping drill size)
  • cut 1/32″ slot
  • drill clear for clamp bolt (up to slot)
  • thread M4 for clamp bolt

The Cutting Tool

Grind a 3/32″ or 1/16″ wide cutting point. Give it plenty of side clearance because the tool will be making an arc. Tighter arcs => more side clearance will be needed at the expense of a weaker tool.

Since round tool steel is used, the cutter can be rotated to adjust the in-use clearance a little to compensate for slightly uneven grinding, and changes in cutting radius, but I suppose the cutting face should be fairly close to lying on a radial line.

AVR Dragon Problem: stopped working, not recognised by USB

OK… so my Dragon just stopped working. Plug it in, the status LED just flashes amber and Windows (XP) does not detect it. Re-install the drivers – no, that isn’t it. (BTW, the instructions in the helpfile that comes with Atmel Studio 6 are wrong). Try another PC or using a motherboard USB socket rather than the hub – no, wrong again. Try a different USB cable – nope.

The answer, it seems is to use a USB hub but to do so with the hub’s separate power adapter. After that, I was able to dispense with the power adapter and the Dragon kept working, even after unplugging/re-connecting.

Wierd! There are a number of suggestions on the web that the Dragon draws a heavy current on startup,  so I guess it got into “a bit of a state.”



Debugging Arduino using debugWire (+ Atmel Studio and an AVR Dragon)

This post is motivated by the lack of information about using debugWire with an Arduino (or similar) on the web. There are quite a few brief comments on the forums and people asking how to do it but nothing really good, with the possible exception of a post by Steve Cogswell which refers to an old version of Arduino and an old version of Atmel Studio.

This really notes for myself for next time, when I’m bound to have forgotten the recipe, but I hope someone else will find it useful. The previous post describes how to get started with using the Atmel Studio simulator, which is a good introduction to the activities required during on-chip debugging (OCD) without needing to fiddle quite so much and without wondering whether the hardware is playing nicely.

What Can You Do with debugWire?

Inspect memory, single-step through code, set break-points (at which execution will stop), inspect registers and input/output port values etc. i.e. as for the simulator, but for the real hardware.


This assumes you have:

  • an Arduino Uno
  • Atmel Studio 6 (Windows only but you could try using it from inside VirtualBox if you are a linux or Mac user – I’ve had a good experience of VirtualBox on Ubuntu, although I’ve not tried Atmel Studio )
  • an AVR Dragon (a fairly cheap USB programmer/on-chip-debugger) and a 6-way cable to connect it.

I also recommend you get the ATMega328 data sheet.

Preparing the Hardware

The ATMega328 data sheet says:

• Capacitors connected to the RESET pin must be disconnected when using debugWire.
• All external reset sources must be disconnected.

If you check the Arduino Schematic, you will see that there IS a 100nF capacitor connected to RESET. This is used to cause a reset to be triggered when communication is initiated via the USB. This is normally useful since a reset is needed to prompt the bootloader on the Arduino to receive compiled code in the upload process.

In the older Arduinos you had to remove the capacitor (as per Steve Cogswell’s post) but on the Uno there is a bit of circuit board track specially prepared for cutting and re-soldering later if need be. If you leave it cut then it will be necessary to manually press the reset button just as the Arduino IDE (or avrdude) tries to start an upload.

RESET EN marks the place you need to cut (between the two solder pads)

RESET EN marks the place you need to cut (between the two solder pads)

Preparing the Software

This is basically just a case of compiling the code for the Arduino in Atmel Studio as I’ve previously described. It is NOT necessary to upload the compiled code using avrdude because Atmel Studio will do this for us via debugWire.

Preparing the Hardware

Connect the Dragon ISP header to the Arduino ISP header. Note that pin1 connects to pin1 on the other device, i.e. MISO connects to MISO. Both Dragon and Ardiuno are separately powered through their USB connectors and the Dragon senses the Arduino’s power supply voltage through the 6-way connector.

Select the Dragon as the tool to use

Select the Dragon as the tool to use

Open the device programmer using Tools|Device Programming menu or: program button.

Make sure Tool, Device and Interface are correct then click "Apply" to connect.

Make sure Tool, Device and Interface are correct then click “Apply”.

You can also “Read” the device signature to confirm that the physical device matches the one chosen in Atmel Studio. This will happen automatically later on anyway and Atmel Studio will block you if it isn’t right.

Warning… and Being Prepared

As described in Steve Cogswell’s post, it is possible to make a non-permanent mess of the ATMega328. It may be necessary to use the “HV” programming on the AVR Dragon if the ATMega gets stuck in debugWire mode and it may be necessary to re-install the boot-loader. These are not difficult if you have an AVR Dragon (or presumably other programmers too).

It can be useful if you need to recover from mishap, and is generally a good plan, I think, to get the fuse settings BEFORE messing about with debugWire and before fiddling with them. All you need to convert a factory fresh ATMega328 into something usable on an Arduino board is to set the fuses correctly and to program the boot loader.

Use "Copy to clipboard" and save the fuse settings somewhere save. Do the same for the Lock bits.

Use “Copy to clipboard” and save the fuse settings somewhere save. Do the same for the Lock bits.

The debugWire Cycle

This is the sequence of operations I have found works reliably. Try this with “Blink” (if you’ve carried on from the simulation example, remember to replace the delay() lines). NB: step 7 is important to get your chip back into its normal state.

  1. Program the DWEN fuse: make sure the box is ticked then click “Program”.
  2. Cycle the power on the Arduino by temporarily disconnecting the USB connector. At this point, you can probably no longer use the ISP interface.
  3. Set debugWire as the interface (see screenshot below)
  4. Click “Start Debugging and Break” or hit Alt+F5 or set a break-point then “Start Debugging” (F5). Note: this uploads the program too.
  5. Set break-points, single-step etc. Use the “IO View” to manually change the value of output pins on the Arduino, yes, the real ones!
  6. Stop debugging (Ctrl+Shift+F5), change the code and return to step 4.
  7. Menu “Debug|Disable debugWIRE and close”. This menu item is only accessible when debugging so you may need to use F5 again. The DWEN flag will now be reset and you will be able to use the ISP interface again.
Set the interface to debugWIRE

Set the interface to debugWIRE (step 3)

Now compare the fuses and lock-bits to the previously saved settings. They should be identical. debugWIRE should also have preserved the bootloader so it should be possible to go back to the Arduino IDE; you only need to remember to press the Arduino reset button just as the IDE announces it is uploading in order that the bootloader executes.