Skip to content

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:

atmos
 [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 https://map.bgs.ac.uk/arcgis/services/BGS_Detailed_Geology/MapServer/WMSServer?REQUEST=GetMap&VERSION=1.3.0&LAYERS=BGS.50k.Bedrock&STYLES=default&FORMAT=image/gif&CRS=EPSG:27700&BBOX=400000,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

CaptureQuo2GE

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.

Steps:

  • 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. http://www.test.net/trips/gm.html?trip1).

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

Arbor

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.

Pre-requisites

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.

Simulating Arduino Code using Atmel Studio 6

The next post will look at on-chip-debugging (OCD) but it is worth using the Atmel Studio Simulator first. Using the simulator isn’t practical unless the input-output is pretty simple because it doesn’t simulate attached devices or real-time events. But even so, you can fiddle with input/output at the bit level and follow the way variables in the code change as it executes. This is MUCH smarter than using Serial.println() because once you’ve mastered Atmel Studio, you can save plenty of time. And poking about with the simulator helps to make sense of what is going on inside code such as “int led=13″ or “digitalWrite(12, HIGH)”. All clean fun, and you don’t need any hardware other than a PC.

This starts off as just a case of compiling the code in Atmel Studio so you can set break-points or step line-by-line through the code to see what happens. See an earlier post of mine for how to get an Arduno sketch to become an Atmel Studio 6 project or just download the Atmel Studio project to match the following.

device

First make sure you have selected the right target device

choose_simulator

Then choose the simulator as the device

I have the “device and debugger toolbar” permanently enabled: device and debugger toolbar.

Tracing Input/Output

I’m going to use “blink” with delay() commented out because I have also found that use of delay() causes problems. Real time stuff doesn’t make sense in a step-through simulator anyway.

Set a breakpoint by clicking in the margin

Set a break-point by clicking in the margin

Now just hit F5 (or the green “play” icon) , watch the compile and wait for the break-point line to become highlighted in yellow. Now make sure the “IO View” is open. Use F10 to step through lines or the “Step Over” icon. If you F11/”Step Into”, you will end up inside the code that implements digitalWrite().

IO View showing PORTB inputs/outputs, which includes Arduino pin 13 as "bit 5"

IO View showing PORTB inputs/outputs, which includes Arduino pin 13 as “bit 5″. DDRB is set because pin13 is defined as an output. The bottom row is the output. PINB is the input value, which just follows the output.

Step through and watch bit 5 change, with nice highlighting in red. You can also click on it to change the value manually. I tend to use keyboard shortcuts but you might prefer the toolbar: step toolbar (watch, step-into, step-over and step-out). Step-Out is handy if you accidentally Step-Into the code for digitalWrite(), for example.

It should be an easy step to modify blink to read pin11 and write the value to pin12. Which bits of PORTB are these? Click on the appropriate bit in the PINB row to set the input value as high or low and step through to see it propagate to the output. Does it work if pin11 is set as an output (DDRB is set for that bit)?

Watching CPU Clock Cycles

Open the Processor view and watch the “Cycle Counter” as you step through. Changes in this indicate how many CPU clock cycles were needed to execute the line(s) of code. You can over-type the value to zero. At 16MHz clock, each cycle is 1/16,000,000s long so it how long does it take for the two digitalWrite()s in blink to execute?

Processor View is a little cryptic except for Cycle Counter

Processor View is a little cryptic except for Cycle Counter

 Watching Variables

Declare a boolean called “in” and read pin 11 into “in” before doing a digitalWrite(12, in). Now select the text “in” and add a “QuickWatch” (Shift F9 or click the glasses icon). Step through as before, manually changing bit 3 (pin 11) in “IO View”. NB: you can manually change values in the “Watch 1″ tab too.

The result of a QuickWatch of both "led" and "in", which has just changed to 1

The result of a QuickWatch of both “led” and “in”, which has just changed to 1

OK… that was too simple but… Now find the “Memory 1″ view (try Debug|Windows menu) and select “Memory: data IRAM”. Step through again and see if you can see which memory byte stores the value of “in”. Hint: in my case it was address 0x01df. Now add a QuickWatch for “led”, find the memory location and check its value is 0x0d (i.e. hexadecimal for 13 in decimal). See what happens in the Memory view if you change the value of “led” in Watch 1 to be -1 or 512. It should be clear that “led” uses two bytes of storage (check the Arduino reference and it says “Integers …  store a 2 byte value. This yields a range of -32,768 to 32,767″).