An input/output controller for virtual pinball machines, with plunger position tracking, accelerometer-based nudge sensing, button input encoding, and feedback device control.

Dependencies:   USBDevice mbed FastAnalogIn FastIO FastPWM SimpleDMA

/media/uploads/mjr/pinscape_no_background_small_L7Miwr6.jpg

The Pinscape Controller is a special-purpose software project that I wrote for my virtual pinball machine.

New version: V2 is now available! The information below is for version 1, which will continue to be available for people who prefer the original setup.

What exactly is a virtual pinball machine? It's basically a video-game pinball emulator built to look like a real pinball machine. (The picture at right is the one I built.) You start with a standard pinball cabinet, either built from scratch or salvaged from a real machine. Inside, you install a PC motherboard to run the software, and install TVs in place of the playfield and backglass. Several Windows pinball programs can take advantage of this setup, including the open-source project Visual Pinball, which has hundreds of tables available. Building one of these makes a great DIY project, and it's a good way to add to your skills at woodworking, computers, and electronics. Check out the Cabinet Builders' Forum on vpforums.org for lots of examples and advice.

This controller project is a key piece in my setup that helps integrate the video game into the pinball cabinet. It handles several input/output tasks that are unique to virtual pinball machines. First, it lets you connect a mechanical plunger to the software, so you can launch the ball like on a real machine. Second, it sends "nudge" data to the software, based on readings from an accelerometer. This lets you interact with the game physically, which makes the playing experience more realistic and immersive. Third, the software can handle button input (for wiring flipper buttons and other cabinet buttons), and fourth, it can control output devices (for tactile feedback, button lights, flashers, and other special effects).

Documentation

The Hardware Build Guide (PDF) has detailed instructions on how to set up a Pinscape Controller for your own virtual pinball cabinet.

Update notes

December 2015 version: This version fully supports the new Expansion Board project, but it'll also run without it. The default configuration settings haven't changed, so existing setups should continue to work as before.

August 2015 version: Be sure to get the latest version of the Config Tool for windows if you're upgrading from an older version of the firmware. This update adds support for TSL1412R sensors (a version of the 1410 sensor with a slightly larger pixel array), and a config option to set the mounting orientation of the board in the firmware rather than in VP (for better support for FP and other pinball programs that don't have VP's flexibility for setting the rotation).

Feb/March 2015 software versions: If you have a CCD plunger that you've been using with the older versions, and the plunger stops working (or doesn't work as well) after you update to the latest version, you might need to increase the brightness of your light source slightly. Check the CCD exposure with the Windows config tool to see if it looks too dark. The new software reads the CCD much more quickly than the old versions did. This makes the "shutter speed" faster, which might require a little more light to get the same readings. The CCD is actually really tolerant of varying light levels, so you probably won't have to change anything for the update - I didn't. But if you do have any trouble, have a look at the exposure meter and try a slightly brighter light source if the exposure looks too dark.

Downloads

  • Config tool for Windows (.exe and C# source): this is a Windows program that lets you view the raw pixel data from the CCD sensor, trigger plunger calibration mode, and configure some of the software options on the controller.
  • Custom VP builds: I created modified versions of Visual Pinball 9.9 and Physmod5 that you might want to use in combination with this controller. The modified versions have special handling for plunger calibration specific to the Pinscape Controller, as well as some enhancements to the nudge physics. If you're not using the plunger, you might still want it for the nudge improvements. The modified version also works with any other input controller, so you can get the enhanced nudging effects even if you're using a different plunger/nudge kit. The big change in the modified versions is a "filter" for accelerometer input that's designed to make the response to cabinet nudges more realistic. It also makes the response more subdued than in the standard VP, so it's not to everyone's taste. The downloads include both the updated executables and the source code changes, in case you want to merge the changes into your own custom version(s).

    Note! These features are now standard in the official VP 9.9.1 and VP 10 releases, so you don't need my custom builds if you're using 9.9.1 or 10 or later. I don't think there's any reason to use my 9.9 instead of the official 9.9.1, but I'm leaving it here just in case. In the official VP releases, look for the checkbox "Enable Nudge Filter" in the Keys preferences dialog. (There's no checkbox in my custom builds, though; the filter is simply always on in those.)
  • Output circuit shopping list: This is a saved shopping cart at mouser.com with the parts needed for each output driver, if you want to use the LedWiz emulator feature. Note that quantities in the cart are for one output channel, so multiply everything by the number of channels you plan to use, except that you only need one of the ULN2803 transistor array chips for each eight output circuits.
  • Lemming77's potentiometer mounting bracket and shooter rod connecter: Sketchup designs for 3D-printable parts for mounting a slide potentiometer as the plunger sensor. These were designed for a particular slide potentiometer that used to be available from an Aliexpress.com seller but is no longer listed. You can probably use this design as a starting point for other similar devices; just check the dimensions before committing the design to plastic.

Features

  • Plunger position sensing, using a TAOS TSL 1410R CCD linear array sensor. This sensor is a 1280 x 1 pixel array at 400 dpi, which makes it about 3" long - almost exactly the travel distance of a standard pinball plunger. The idea is that you install the sensor just above (within a few mm of) the shooter rod on the inside of the cabinet, with the CCD window facing down, aligned with and centered on the long axis of the shooter rod, and positioned so that the rest position of the tip is about 1/2" from one end of the window. As you pull back the plunger, the tip will travel down the length of the window, and the maximum retraction point will put the tip just about at the far end of the window. Put a light source below, facing the sensor - I'm using two typical 20 mA blue LEDs about 8" away (near the floor of the cabinet) with good results. The principle of operation is that the shooter rod casts a shadow on the CCD, so pixels behind the rod will register lower brightness than pixels that aren't in the shadow. We scan down the length of the sensor for the edge between darker and brighter, and this tells us how far back the rod has been pulled. We can read the CCD at about 25-30 ms intervals, so we can get rapid updates. We pass the readings reports to VP via our USB joystick reports.

    The hardware build guide includes schematics showing how to wire the CCD to the KL25Z. It's pretty straightforward - five wires between the two devices, no external components needed. Two GPIO ports are used as outputs to send signals to the device and one is used as an ADC in to read the pixel brightness inputs. The config tool has a feature that lets you display the raw pixel readings across the array, so you can test that the CCD is working and adjust the light source to get the right exposure level.

    Alternatively, you can use a slide potentiometer as the plunger sensor. This is a cheaper and somewhat simpler option that seems to work quite nicely, as you can see in Lemming77's video of this setup in action. This option is also explained more fully in the build guide.
  • Nudge sensing via the KL25Z's on-board accelerometer. Mounting the board in your cabinet makes it feel the same accelerations the cabinet experiences when you nudge it. Visual Pinball already knows how to interpret accelerometer input as nudging, so we simply feed the acceleration readings to VP via the joystick interface.
  • Cabinet button wiring. Up to 24 pushbuttons and switches can be wired to the controller for input controls (for example, flipper buttons, the Start button, the tilt bob, coin slot switches, and service door buttons). These appear to Windows as joystick buttons. VP can map joystick buttons to pinball inputs via its keyboard preferences dialog. (You can raise the 24-button limit by editing the source code, but since all of the GPIO pins are allocated, you'll have to reassign pins currently used for other functions.)
  • LedWiz emulation (limited). In addition to emulating a joystick, the device emulates the LedWiz USB interface, so controllers on the PC side such as DirectOutput Framework can recognize it and send it commands to control lights, solenoids, and other feedback devices. 22 GPIO ports are assigned by default as feedback device outputs. This feature has some limitations. The big one is that the KL25Z hardware only has 10 PWM channels, which isn't enough for a fully decked-out cabinet. You also need to build some external power driver circuitry to use this feature, because of the paltry 4mA output capacity of the KL25Z GPIO ports. The build guide includes instructions for a simple and robust output circuit, including part numbers for the exact components you need. It's not hard if you know your way around a soldering iron, but just be aware that it'll take a little work.

Warning: This is not replacement software for the VirtuaPin plunger kit. If you bought the VirtuaPin kit, please don't try to install this software. The VP kit happens to use the same microcontroller board, but the rest of its hardware is incompatible. The VP kit uses a different type of sensor for its plunger and has completely different button wiring, so the Pinscape software won't work properly with it.

Files at this revision

API Documentation at this revision

Comitter:
mjr
Date:
Wed Feb 03 22:57:25 2016 +0000
Parent:
39:b3815a1c3802
Child:
43:7a6364d82a41
Commit message:
Gamma correction option for outputs; work in progress on new config program

Changed in this revision

74HC595/74HC595.h Show annotated file Show diff for this revision Revisions of this file
TLC5940/TLC5940.h Show annotated file Show diff for this revision Revisions of this file
TSL1410R/tsl1410r.h Show annotated file Show diff for this revision Revisions of this file
USBDevice.lib Show annotated file Show diff for this revision Revisions of this file
USBJoystick/USBJoystick.cpp Show annotated file Show diff for this revision Revisions of this file
USBJoystick/USBJoystick.h Show annotated file Show diff for this revision Revisions of this file
USBProtocol.h Show annotated file Show diff for this revision Revisions of this file
Updates.h Show annotated file Show diff for this revision Revisions of this file
ccdSensor.h Show annotated file Show diff for this revision Revisions of this file
cfgVarMsgMap.h Show annotated file Show diff for this revision Revisions of this file
config.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
nvm.h Show annotated file Show diff for this revision Revisions of this file
--- a/74HC595/74HC595.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/74HC595/74HC595.h	Wed Feb 03 22:57:25 2016 +0000
@@ -70,9 +70,10 @@
     }
     
     // Initialize.  This must be called once at startup to clear the chips' 
-    // shift registers and enable the physical outputs.  We clock a 0 bit (OFF
-    // state) to each shift register position, latch the OFF states on the
-    // outputs, and enable the chips.
+    // shift registers.  We clock a 0 bit (OFF state) to each shift register 
+    // position and latch the OFF states on the outputs.  Note that this
+    // doesn't enable the chips - that must be done with a separate call
+    // to enable(true).
     void init()
     {
         // set the internal state of all inputs
@@ -91,9 +92,6 @@
         // bit for each pin to the actual output pin)
         latch = 1;
         latch = 0;
-        
-        // enable the outputs
-        ena = 1;
     }
     
     // Set an output state.  This only sets the state internally; call
@@ -107,12 +105,32 @@
         }
     }
     
+    // Global enable/disable the outputs.  We use this for cleaner startup,
+    // by disabling all outputs after power-on and when coming out of sleep
+    // mode until we've had a chance to initialize the chip registers.  The
+    // chips have random values in their shift registers when first powered
+    // on, so we have to send an initial update after power-on.  The snag
+    // is that the chips might have a separate power supply from the KL25Z,
+    // so we can't assume that the chips are powered just because the program
+    // is running.  Instead, we can use the USB connection status as a proxy
+    // for chip power, on the assumption that (a) the chips are running off
+    // of the PC power supply, and (b) the USB connection can only be running
+    // when the PC is running (hence the PC power supply is on).  
+    void enable(bool f)
+    {
+        // set the new enable state
+        ena = (f ? 1 : 0);
+    }
+    
     // Apply updates.  This sends the current state of each pin to the
-    // chips and latches the new settings.
-    void update()
+    // chips and latches the new settings.  If 'force' is true, we flush
+    // our internal state to the chips even if we haven't made any changes
+    // since the last update.
+    void update(bool force = false)
     {
-        // if we have changes to apply, send the changes
-        if (dirty)
+        // if we have changes to apply, or the caller wants the update to
+        // happen regardless of pending changes, refresh the chips
+        if (dirty || force)
         {
             // Clock out the new states.  Since the outputs are arranged
             // as shift registers, we have to clock out the bits in reverse
--- a/TLC5940/TLC5940.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/TLC5940/TLC5940.h	Wed Feb 03 22:57:25 2016 +0000
@@ -24,35 +24,37 @@
 //
 // NOTE!  This section contains a possible workaround to try if you're 
 // having data signal stability problems with your TLC5940 chips.  If
-// your chips are working properly, you can ignore this part!
+// things are working properly, you can ignore this part.
 //
 // The software has two options for sending data updates to the chips:
 //
-// Mode 0:  Send data *during* the grayscale cycle.  This is the way the
-// chips are designed to be used.  While the grayscale clock is running,
-// we send data for the *next* cycle, then latch the updated data to the
-// output registers during the blanking interval at the end of the cycle.
-//
+// Mode 0:  Send data *during* the grayscale cycle.  This is the default,
+// and it's the standard method the chips are designed for.  In this mode, 
+// we start sending an update just after then blanking interval that starts 
+// a new grayscale cycle.  The timing is arranged so that the update is 
+// completed well before the end of the grayscale cycle.  At the next 
+// blanking interval, we latch the new data, so the new brightness levels 
+// will be shown starting on the next cycle.
+
 // Mode 1:  Send data *between* grayscale cycles.  In this mode, we send
 // each complete update during a blanking period, then latch the update
 // and start the next grayscale cycle.  This isn't the way the chips were
 // intended to be used, but it works.  The disadvantage is that it requires
-// the blanking interval to be extended to be long enough for the full
-// data update (192 bits * the number of chips in the chain).  Since the
-// outputs are turned off for the entire blanking period, this reduces
+// the blanking interval to be extended long enough for the full data 
+// update (192 bits * the number of chips in the chain).  Since the
+// outputs are turned off throughout the blanking period, this reduces
 // the overall brightness/intensity of the outputs by reducing the duty
 // cycle.  The TLC5940 chips can't achieve 100% duty cycle to begin with,
-// since they require a certain minimum time in the blanking interval
+// since they require a brief minimum time in the blanking interval
 // between grayscale cycles; however, the minimum is so short that the
 // duty cycle is close to 100%.  With the full data transmission stuffed
 // into the blanking interval, we reduce the duty cycle further below
 // 100%.  With four chips in the chain, a 28 MHz data clock, and a
 // 500 kHz grayscale clock, the reduction is about 0.3%.
 //
-// By default, we use Mode 0, because that's the timing model specified
-// by the manufacturer, and empirically it works well with the Pinscape 
-// Expansion boards.  
-// 
+// Mode 0 is the method documented in the manufacturer's data sheet.
+// It works well empirically with the Pinscape expansion boards.
+//
 // So what's the point of Mode 1?  In early testing, with a breadboard 
 // setup, I saw some problems with data signal stability, which manifested 
 // as sporadic flickering in the outputs.  Switching to Mode 1 improved
@@ -105,22 +107,17 @@
   * interval is (1/GSCLK_SPEED) * 4096.  The maximum reliable rate is
   * around 32Mhz.  It's best to keep this rate as low as possible:
   * the higher the rate, the higher the refresh() call frequency,
-  * so the higher the CPU load.
+  * so the higher the CPU load.  Higher frequencies also make it more
+  * challenging to wire the chips for clean signal transmission, so
+  * minimizing the clock speed will help with signal stability.
   *
-  * The lower bound depends on the application.  For driving LEDs, 
-  * the limiting factor is that lower rates will increase visible flicker.
-  * A GSCLK speed of 200 kHz is about as low as you can go with LEDs 
-  * without excessive flicker.  That equals about 48 full grayscale
-  * cycles per second.  That might seem perfectly good in that it's 
-  * about the same as the standard 50Hz A/C cycle rate in many countries, 
-  * but the 50Hz rate was chosen to minimize visible flicker in 
-  * incandescent lamps, not LEDs.  LEDs need a higher rate because they 
-  * don't have thermal inertia as incandescents do.  The default we use 
-  * here is 500 kHz = 122 full grayscale cycles per second.  That seems
-  * to produce excellent visual results.  Higher rates would probably
-  * produce diminishing returns given that they also increase CPU load.
+  * The lower bound depends on the application.  For driving lights,
+  * the limiting factor is flicker: the lower the rate, the more
+  * noticeable the flicker.  Incandescents tend to look flicker-free
+  * at about 50 Hz (205 kHz grayscale clock).  LEDs need slightly 
+  * faster rates.
   */
-#define GSCLK_SPEED    500000
+#define GSCLK_SPEED    350000
 
 /**
   *  This class controls a TLC5940 PWM driver IC.
@@ -163,6 +160,9 @@
           xlat(XLAT),
           nchips(nchips)
     {
+        // start up initially disabled
+        enabled = false;
+        
         // set XLAT to initially off
         xlat = 0;
         
@@ -199,17 +199,28 @@
         xlat = 0;
 
         // Allocate our DMA buffers.  The transfer on each cycle is 192 bits per
-        // chip = 24 bytes per chip. 
-        dmabuf = new char[nchips*24];
-        memset(dmabuf, 0, nchips*24);
+        // chip = 24 bytes per chip.  Allocate two buffers, so that we have a
+        // stable buffer that we can send to the chips, and a separate working
+        // copy that we can asynchronously update.
+        dmalen = nchips*24;
+        dmabuf = new uint8_t[dmalen*2];
+        memset(dmabuf, 0, dmalen*2);
         
+        zerobuf = new uint8_t[dmalen];//$$$
+        memset(zerobuf, 0xff, dmalen);//$$$
+        
+        // start with buffer 0 live, with no new data pending
+        livebuf = dmabuf;
+        workbuf = dmabuf + dmalen;
+        dirty = false;
+
         // Set up the Simple DMA interface object.  We use the DMA controller to
         // send grayscale data updates to the TLC5940 chips.  This lets the CPU
         // keep running other tasks while we send gs updates, and importantly
         // allows our blanking interrupt handler return almost immediately.
         // The DMA transfer is from our internal DMA buffer to SPI0, which is
         // the SPI controller physically connected to the TLC5940s.
-        sdma.source(dmabuf, true, 8);
+        sdma.source(livebuf, true, 8);
         sdma.destination(&(SPI0->D), false, 8);
         sdma.trigger(Trigger_SPI0_TX);
         sdma.attach(this, &TLC5940::dmaDone);
@@ -223,9 +234,36 @@
         gsclk.period(1.0/GSCLK_SPEED);
         
         // mark that we need an initial update
-        newGSData = true;
+        dirty = true;
         needXlat = false;
-     }
+    }
+     
+    // Global enable/disble.  When disabled, we assert the blanking signal
+    // continuously to keep all outputs turned off.  This can be used during
+    // startup and sleep mode to prevent spurious output signals from
+    // uninitialized grayscale registers.  The chips have random values in
+    // their internal registers when power is first applied, so we have to 
+    // explicitly send the initial zero levels after power cycling the chips.
+    // The chips might not have power even when the KL25Z is running, because
+    // they might be powered from a separate power supply from the KL25Z
+    // (the Pinscape Expansion Boards work this way).  Global blanking helps
+    // us start up more cleanly by suppressing all outputs until we can be
+    // reasonably sure that the various chip registers are initialized.
+    void enable(bool f)
+    {
+        // note the new setting
+        enabled = f;
+        
+        // if disabled, apply blanking immediately
+        if (!f)
+        {
+            gsclk.write(0);
+            blank = 1;
+        }
+        
+        // do a full update with the new setting
+        dirty = true;
+    }
     
     // Start the clock running
     void start()
@@ -264,6 +302,20 @@
         // validate the index
         if (idx >= 0 && idx < nchips*16)
         {
+            // this is a critical section, since we're updating a static buffer and
+            // can call this routine from application context or interrupt context
+            __disable_irq();
+            
+            // If the buffer isn't dirty, it means that the previous working buffer
+            // was swapped into the live buffer on the last blanking interval.  This
+            // means that the working buffer hasn't been updated to the live data yet,
+            // so we need to copy it now.
+            if (!dirty) 
+            {
+                memcpy(workbuf, livebuf, dmalen);
+                dirty = true;
+            }
+
             // Figure the DMA buffer location of the data.  The DMA buffer has the
             // packed bit format that we send across the wire, with 12 bits per output,
             // arranged from last output to first output (N = number of outputs = nchips*16):
@@ -284,25 +336,33 @@
             int di = nchips*24 - 3 - (3*(idx/2));
             if (idx & 1)
             {
-                //printf("out %d = %d -> updating dma[%d] odd (xx x. ..)\r\n", idx, data, di);
                 // ODD = high 8 | low 4
-                dmabuf[di]    = uint8_t((data >> 4) & 0xff);
-                dmabuf[di+1] &= 0x0F;
-                dmabuf[di+1] |= uint8_t((data << 4) & 0xf0);
+                workbuf[di]    = uint8_t((data >> 4) & 0xff);
+                workbuf[di+1] &= 0x0F;
+                workbuf[di+1] |= uint8_t((data << 4) & 0xf0);
             }
             else
             {
                 // EVEN = high 4 | low 8
-                //printf("out %d = %d -> updating dma[%d] even (.. .x xx)\r\n", idx, data, di);
-                dmabuf[di+1] &= 0xF0;
-                dmabuf[di+1] |= uint8_t((data >> 8) & 0x0f);
-                dmabuf[di+2]  = uint8_t(data & 0xff);
+                workbuf[di+1] &= 0xF0;
+                workbuf[di+1] |= uint8_t((data >> 8) & 0x0f);
+                workbuf[di+2]  = uint8_t(data & 0xff);
             }
             
-            // note the update
-            newGSData = true;
+            // end the critical section
+            __enable_irq();
         }
     }
+    
+    // Update the outputs.  We automatically update the outputs on the grayscale timer
+    // when we have pending changes, so it's not necessary to call this explicitly after 
+    // making a change via set().  This can be called to force an update when the chips
+    // might be out of sync with our internal state, such as after power-on.
+    void update(bool force = false)
+    {
+        if (force)
+            dirty = true;
+    }
 
 private:
     // current level for each output
@@ -311,10 +371,36 @@
     // Simple DMA interface object
     SimpleDMA sdma;
 
-    // DMA transfer buffer.  Each time we have data to transmit to the TLC5940 chips,
-    // we format the data into this buffer exactly as it will go across the wire, then
-    // hand the buffer to the DMA controller to move through the SPI port.
-    char *dmabuf;
+    // DMA transfer buffers - double buffer.  Each time we have data to transmit to the 
+    // TLC5940 chips, we format the data into the working half of this buffer exactly as 
+    // it will go across the wire, then hand the buffer to the DMA controller to move 
+    // through the SPI port.  This memory block is actually two buffers, one live and 
+    // one pending.  When we're ready to send updates to the chips, we swap the working
+    // buffer into the live buffer so that we can send the latest updates.  We keep a
+    // separate working copy so that our live copy is stable, so that we don't alter
+    // any data in the midst of an asynchronous DMA transmission to the chips.
+    uint8_t *dmabuf;
+    
+    uint8_t *zerobuf; // $$$ buffer for all zeroes to flush chip registers when no updates are needed
+    
+    // The working and live buffer pointers.  At any give time, one buffer is live and
+    // the other is active.
+    // dmabuf1 is live and the other is the working buffer.  When there's pending work,
+    // we swap them to make the pending data live.
+    uint8_t *livebuf;
+    uint8_t *workbuf;
+    
+    // length of each DMA buffer, in bytes - 12 bits = 1.5 bytes per output, 16 outputs
+    // per chip -> 24 bytes per chip
+    uint16_t dmalen;
+    
+    // Dirty: true means that the non-live buffer has new pending data.  False means
+    // that the non-live buffer is empty.
+    bool dirty;
+    
+    // Enabled: this enables or disables all outputs.  When this is true, we assert the
+    // BLANK signal continuously.
+    bool enabled;
     
     // SPI port - only MOSI and SCK are used
     SPI spi;
@@ -334,18 +420,36 @@
     // on each cycle.
     Timeout resetTimer;
     
-    // Has new GS/DC data been loaded?
-    volatile bool newGSData;
-    
     // Do we need an XLAT signal on the next blanking interval?
     volatile bool needXlat;
+    volatile bool newGSData;//$$$
 
-    // Function to reset the display and send the next chunks of data
+    // Reset the grayscale cycle and send the next data update
     void reset()
     {
         // start the blanking cycle
         startBlank();
         
+        // if we have pending grayscale data, update the DMA data
+        /*$$$bool*/ newGSData = false;
+        if (dirty) 
+        {
+            // swap live and working buffers
+            uint8_t *tmp = livebuf;
+            livebuf = workbuf;
+            workbuf = tmp;
+            
+            // set the new DMA source
+            sdma.source(livebuf, true, 8);            
+            
+            // no longer dirty
+            dirty = false;
+            
+            // note the new data
+            newGSData = true;
+        }
+        else { sdma.source(zerobuf, true, 8); }//$$$
+        
 #if DATA_UPDATE_INSIDE_BLANKING
         // We're configured to send the new GS data entirely within
         // the blanking interval.  Start the DMA transfer now, and
@@ -361,22 +465,16 @@
         // did updates on some cycles and not others.  By doing an
         // update on every cycle, we make the brightness reduction
         // uniform across time, which makes it less perceptible.
-        sdma.start(nchips*24);
+        sdma.start(dmalen);
         
 #else // DATA_UPDATE_INSIDE_BLANKING
         
         // end the blanking interval
         endBlank();
         
-        // if we have pending grayscale data, update the DMA data
-        // if (newGSData) 
-        {
-            // send out the DMA contents
-            sdma.start(nchips*24);
-            
-            // we don't have to send again until the next gs data cahnge
-            newGSData = false;
-        }
+        // send out the DMA contents if we have new data
+       //$$$ if (newGSData)
+            sdma.start(dmalen);
 
 #endif // DATA_UPDATE_INSIDE_BLANKING
     }
@@ -385,6 +483,7 @@
     {
         // turn off the grayscale clock, and assert BLANK to end the grayscale cycle
         gsclk.write(0);
+        blank = 0;  // for a slight delay - chip requires 20ns GSCLK up to BLANK up
         blank = 1;        
     }
             
@@ -400,8 +499,9 @@
             needXlat = false;
         }
 
-        // end the blanking interval and restart the grayscale clock
-        blank = 0;
+        // End the blanking interval and restart the grayscale clock.  Note
+        // that we keep the blanking on if the chips are globally disabled.
+        blank = enabled ? 0 : 1;
         gsclk.write(.5);
         
         // set up the next blanking interrupt
@@ -416,7 +516,7 @@
     {
         // mark that we need to assert XLAT to latch the new
         // grayscale data during the next blanking interval
-        needXlat = true;
+        needXlat = newGSData;//$$$ true;
         
 #if DATA_UPDATE_INSIDE_BLANKING
         // we're doing the gs update within the blanking cycle, so end
--- a/TSL1410R/tsl1410r.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/TSL1410R/tsl1410r.h	Wed Feb 03 22:57:25 2016 +0000
@@ -126,7 +126,7 @@
                 pix[dst] = ao1.read_u16();
                 pix[dst+n/2] = ao2.read_u16();
                 
-                // turn off the ADC until the next pixel is ready
+                // turn off the ADC until the next pixel is clocked out
                 ao1.disable();
                 ao2.disable();
                 
@@ -188,8 +188,12 @@
         si = 0;
         clockPort->PCOR |= clockMask;
         
+        // if in serial mode, clock all pixels across both sensor halves;
+        // in parallel mode, the pixels are clocked together
+        int n = parallel ? nPix/2 : nPix;
+        
         // clock out all pixels
-        for (int i = 0 ; i < nPix + 1 ; ++i) {
+        for (int i = 0 ; i < n + 1 ; ++i) {
             clockPort->PSOR |= clockMask;
             clockPort->PCOR |= clockMask;
         }
@@ -197,13 +201,13 @@
 
 private:
     int nPix;                 // number of pixels in physical sensor array
-    DigitalOut si;
-    DigitalOut clock;
-    FGPIO_Type *clockPort;    // IOPORT base address for clock pin, for fast writes
+    DigitalOut si;            // GPIO pin for sensor SI (serial data) 
+    DigitalOut clock;         // GPIO pin for sensor SCLK (serial clock)
+    FGPIO_Type *clockPort;    // IOPORT base address for clock pin - cached for fast writes
     uint32_t clockMask;       // IOPORT register bit mask for clock pin
-    FastAnalogIn ao1; 
-    FastAnalogIn ao2;         // valid iff running in parallel mode
-    bool parallel;            // true -> running in parallel mode
+    FastAnalogIn ao1;         // GPIO pin for sensor AO1 (analog output 1) - we read sensor data from this pin
+    FastAnalogIn ao2;         // GPIO pin for sensor AO2 (analog output 2) - 2nd sensor data pin, when in parallel mode
+    bool parallel;            // true -> running in parallel mode (we read AO1 and AO2 separately on each clock)
 };
  
 #endif /* TSL1410R_H */
--- a/USBDevice.lib	Mon Jan 11 21:08:36 2016 +0000
+++ b/USBDevice.lib	Wed Feb 03 22:57:25 2016 +0000
@@ -1,1 +1,1 @@
-http://mbed.org/users/mjr/code/USBDevice/#c5ac4ccf6597
+http://mbed.org/users/mjr/code/USBDevice/#cd877d5c09ea
--- a/USBJoystick/USBJoystick.cpp	Mon Jan 11 21:08:36 2016 +0000
+++ b/USBJoystick/USBJoystick.cpp	Wed Feb 03 22:57:25 2016 +0000
@@ -47,8 +47,9 @@
 
    // Fill the report according to the Joystick Descriptor
 #define put(idx, val) (report.data[idx] = (val) & 0xff, report.data[(idx)+1] = ((val) >> 8) & 0xff)
+#define putl(idx, val) (put(idx, val), put((idx)+2, (val) >> 16))
    put(0, _status);
-   put(2, 0);  // second byte of status isn't used in normal reports
+   put(2, 0);  // second word of status - zero in high bit identifies as normal joystick report
    put(4, _buttonsLo);
    put(6, _buttonsHi);
    put(8, _x);
@@ -119,7 +120,28 @@
     return sendTO(&report, 100);
 }
 
-bool USBJoystick::reportConfig(int numOutputs, int unitNo, int plungerZero, int plungerMax)
+bool USBJoystick::reportID()
+{
+    HID_REPORT report;
+
+    // initially fill the report with zeros
+    memset(report.data, 0, sizeof(report.data));
+    
+    // Set the special status bits to indicate that it's an ID report
+    uint16_t s = 0x9000;
+    put(0, s);
+    
+    // write the 80-bit ID
+    put(2, SIM->UIDMH);
+    putl(4, SIM->UIDML);
+    putl(8, SIM->UIDL);
+    
+    // send the report
+    report.length = reportLen;
+    return sendTO(&report, 100);
+}
+
+bool USBJoystick::reportConfig(int numOutputs, int unitNo, int plungerZero, int plungerMax, bool configured)
 {
     HID_REPORT report;
 
@@ -140,6 +162,10 @@
     put(6, plungerZero);
     put(8, plungerMax);
     
+    // write the status bits: 
+    //  0x01  -> configuration loaded
+    report.data[10] = (configured ? 0x01 : 0x00);
+    
     // send the report
     report.length = reportLen;
     return sendTO(&report, 100);
--- a/USBJoystick/USBJoystick.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/USBJoystick/USBJoystick.h	Wed Feb 03 22:57:25 2016 +0000
@@ -229,8 +229,16 @@
          *
          * @param numOutputs the number of configured output channels
          * @param unitNo the device unit number
+         * @param plungerZero plunger zero calibration point
+         * @param plungerMax plunger max calibration point
+         * @param configured true if a configuration has been saved to flash from the host
          */
-         bool reportConfig(int numOutputs, int unitNo, int plungerZero, int plungerMax);
+         bool reportConfig(int numOutputs, int unitNo, int plungerZero, int plungerMax, bool configured);
+         
+         /**
+         * Write a device ID report.
+         */
+         bool reportID();
  
          /**
          * Send a joystick report to the host
--- a/USBProtocol.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/USBProtocol.h	Wed Feb 03 22:57:25 2016 +0000
@@ -16,9 +16,13 @@
 // looks like this (see USBJoystick.cpp for the formal HID report descriptor):
 //
 //    ss     status bits:  0x01 -> plunger enabled
+//    00     2nd byte of status (reserved)
+//    00     3rd byte of status (reserved)
 //    00     always zero for joystick reports
-//    bb     joystick buttons, low byte (buttons 1-16, 1 bit per button)
-//    bb     joystick buttons, high byte (buttons 17-32)
+//    bb     joystick buttons, low byte (buttons 1-8, 1 bit per button)
+//    bb     joystick buttons, 2nd byte (buttons 9-16)
+//    bb     joystick buttons, 3rd byte (buttons 17-24)
+//    bb     joystick buttons, high byte (buttons 25-32)
 //    xx     low byte of X position = nudge/accelerometer X axis
 //    xx     high byte of X position
 //    yy     low byte of Y position = nudge/accelerometer Y axis
@@ -75,12 +79,27 @@
 //
 //    bytes 0:1 = 0x8800.  This has the bit pattern 10001 in the high
 //                5 bits, which distinguishes it from regular joystick
-//                reports and from exposure status reports.
+//                reports and from other special report types.
 //    bytes 2:3 = total number of outputs, little endian
-//    bytes 4:5 = plunger calibration zero point, little endian
-//    bytes 6:7 = plunger calibration maximum point, little endian
-//    remaining bytes = reserved for future use; set to 0 in current version
+//    bytes 6:7 = plunger calibration zero point, little endian
+//    bytes 8:9 = plunger calibration maximum point, little endian
+//    byte  10   = bit flags: 
+//                 0x01 -> configuration loaded; 0 in this bit means that
+//                         the firmware has been loaded but no configuration
+//                         has been sent from the host
+//    The remaining bytes are reserved for future use.
 //
+// 2C. Device ID query.
+// This is requested by sending custom protocol message 65 7 (see below).
+// In response, the device sends one report to the host using this format:
+//
+//    bytes 0:1 = 0x9000.  This has bit pattern 10010 in the high 5
+//                bits, which distinguishes this special report from other 
+//                report types.
+//    bytes 2-11 = Unique CPU ID.  This is the ID stored in the CPU at the
+//                factory, guaranteed to be unique across Kinetis devices.
+//                This can be used by the host to distinguish devices when
+//                two or more controllers are attached.
 //
 // WHY WE USE THIS HACKY APPROACH TO DIFFERENT REPORT TYPES
 //
@@ -211,7 +230,8 @@
 //             plunger sensor isn't an image sensor type, no pixel messages are sent.
 //
 //        4 -> Query configuration.  The device sends a special configuration report,
-//             defined in USBJoystick.cpp, then resumes sending normal joystick reports.
+//             (see above; see also USBJoystick.cpp), then resumes sending normal 
+//             joystick reports.
 //
 //        5 -> Turn all outputs off and restore LedWiz defaults.  Sets output ports
 //             1-32 to OFF and LedWiz brightness/mode setting 48, sets outputs 33 and
@@ -221,6 +241,14 @@
 //             type 66 messages since the last reboot, then automatically reboots the
 //             device to put the changes into effect.
 //
+//        7 -> Query device ID.  The device replies with a special device ID report
+//             (see above; see also USBJoystick.cpp), then resumes sending normal
+//             joystick reports.
+//
+//        8 -> Engage/disengage night mode.  The third byte of the message is 1 to
+//             engage night mode, 0 to disengage night mode.  (This mode isn't stored
+//             persistently; night mode is disengaged after a reset or power cycle.)
+//
 // 66  -> Set configuration variable.  The second byte of the message is the config
 //        variable number, and the remaining bytes give the new value for the variable.
 //        The value format is specific to each variable; see the list below for details.
@@ -327,8 +355,8 @@
 //       in DOF.  Set the port to 0 to disable the feature.  Byte 4 is the button
 //       number (1-32) that we'll "press" when the feature is activated.  Bytes 5-6
 //       give the "push distance" for activating the button by pushing forward on
-//       the plunger knob, in .001 inch increments (e.g., 80 represents 0.08", which
-//       is the recommended setting).
+//       the plunger knob, in 1/1000 inch increments (e.g., 80 represents 0.08", 
+//       which is the recommended setting).
 //
 // 9  -> TV ON relay setup.  This requires external circuitry implemented on the
 //       Expansion Board (or an equivalent circuit as described in the Build Guide).
@@ -422,6 +450,7 @@
 //         byte 6 = flags: a combination of these bit values:
 //                   0x01 = active-high output (0V on output turns attached device ON)
 //                   0x02 = noisemaker device: disable this output when "night mode" is engaged
+//                   0x04 = apply gamma correction to this output
 //
 //       Note that the on-board LED segments can be used as LedWiz output ports.  This
 //       is useful for testing a new installation with DOF or other PC software without
@@ -440,12 +469,6 @@
 //               momentary pushbutton switch used to activate night mode.  The light 
 //               provides visual feedback that the mode is turned on.
 //
-//
-// 14 -> Engage/disengage Night Mode.  When night mode is engaged, LedWiz outputs marked
-//       as "noisemaker" devices are disabled.  Byte 3 is 1 to engage night mode, 0 to
-//       cancel night mode.  Note that sending this command will override the current
-//       switch setting, if a toggle switch is configured to control Night Mode.  Toggling
-//       the switch will take control via the switch again.
 
 
 
--- a/Updates.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/Updates.h	Wed Feb 03 22:57:25 2016 +0000
@@ -69,6 +69,16 @@
 // noisy, so you can still enjoy the rest of your feedback features during
 // night play (e.g., flashers and other lighting effects).
 //
+// Gamma correction: each output can now optionally have gamma correction 
+// applied.  This can be set in the configuration individually for each 
+// output attached to an LED or lamp.  Gamma correction translates the
+// computer's idea of linear brightness to the human eye's logarithmic
+// brightness curve, which makes make the perceived brightness level of a 
+// lamp more linear.  This can greatly improve the appearance of fading 
+// effects and the fidelity of color mixing in RGB devices.  Without gamma
+// correction, fades tend to saturate on the bright end of the scale, and
+// mixed colors tend to look washed out.
+//
 // USB fixes: the low-level USB device code had some serious bugs that only
 // very occasionally manifested in past versions, but became much more
 // frequently triggered due to other changes in this release (particularly
--- a/ccdSensor.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/ccdSensor.h	Wed Feb 03 22:57:25 2016 +0000
@@ -52,9 +52,9 @@
         // determine which end is brighter
         uint16_t p1 = pix[0];
         uint16_t p2 = pix[nlpix-1];
-        int si = 1, di = 1;
+        int si = 0, di = 1;
         if (p1 < p2)
-            si = nlpix, di = -1;
+            si = nlpix - 1, di = -1;
         
         // figure the shadow edge threshold - just use the midpoint 
         // of the levels at the bright and dark ends
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cfgVarMsgMap.h	Wed Feb 03 22:57:25 2016 +0000
@@ -0,0 +1,156 @@
+// Define the configuration variable USB get/set mapper.  We use
+// macros for the get/set operations to allow for common source
+// code for the two operations.  main.cpp #includes this file twice:
+// once for the SET function and once for the GET function.  main.cpp
+// redefines the v_xxx macros according to the current inclusion mode.
+//
+// This is a little tricky to follow because of the macros, but the
+// benefit is that the get and set functions automatically stay in
+// sync in terms of the variable types and byte mappings in the USB
+// messages, since they're both generated automatically from the
+// same code.
+//
+// The SET function is called directly from the corresponding USB
+// protocol message to set one variable.  The data buffer is simply
+// the data passed in from the USB message.
+//
+// The GET function is called in a loop from our configuration
+// variable reporting function.  The report function loops through
+// each variable in turn to generate a series of reports.  The
+// caller in this case fills in data[1] with the variable ID, and
+// it also fills in data[2] with the current index being queried
+// for the array variables (buttons, outputs).  We fill in the
+// rest of the data[] bytes with the current variable value(s),
+// encoded for the USB protocol message.
+
+
+void v_func(uint8_t *data)
+{
+    switch (data[1])
+    {
+    case 1:
+        // USB identification (Vendor ID, Product ID)
+        v_ui16(usbVendorID, 2);
+        v_ui16(usbProductID, 4);
+        break;
+        
+    case 2:
+        // Pinscape Controller unit number (nominal unit number, 1-16)
+        if_msg_valid(data[2] >= 1 && data[2] <= 16)
+            v_byte(psUnitNo, 2);
+        break;
+        
+    case 3:
+        // Enable/disable joystick
+        v_byte(joystickEnabled, 2);
+        break;
+        
+    case 4:
+        // Accelerometer orientation
+        v_byte(orientation, 2);
+        break;
+
+    case 5:
+        // Plunger sensor type
+        v_byte(plunger.sensorType, 2);
+        break;
+        
+    case 6:
+        // Plunger sensor pin assignments
+        v_pin(plunger.sensorPin[0], 2);
+        v_pin(plunger.sensorPin[1], 3);
+        v_pin(plunger.sensorPin[2], 4);
+        v_pin(plunger.sensorPin[3], 5);
+        break;
+        
+    case 7:
+        // Plunger calibration button and indicator light pin assignments
+        v_pin(plunger.cal.btn, 2);
+        v_pin(plunger.cal.led, 3);
+        break;
+        
+    case 8:
+        // ZB Launch Ball setup
+        v_byte(plunger.zbLaunchBall.port, 2);
+        v_byte(plunger.zbLaunchBall.btn, 3);
+        v_ui16(plunger.zbLaunchBall.pushDistance, 4);
+        break;
+        
+    case 9:
+        // TV ON setup
+        v_pin(TVON.statusPin, 2);
+        v_pin(TVON.latchPin, 3);
+        v_pin(TVON.relayPin, 4);
+        v_ui16(TVON.delayTime, 5);
+        break;
+        
+    case 10:
+        // TLC5940NT PWM controller chip setup
+        v_byte(tlc5940.nchips, 2);
+        v_pin(tlc5940.sin, 3);
+        v_pin(tlc5940.sclk, 4);
+        v_pin(tlc5940.xlat, 5);
+        v_pin(tlc5940.blank, 6);
+        v_pin(tlc5940.gsclk, 7);
+        break;
+        
+    case 11:
+        // 74HC595 shift register chip setup
+        v_byte(hc595.nchips, 2);
+        v_pin(hc595.sin, 3);
+        v_pin(hc595.sclk, 4);
+        v_pin(hc595.latch, 5);
+        v_pin(hc595.ena, 6);
+        break;
+        
+    case 12:
+        // button setup
+        {
+            // get the button number
+            int idx = data[2];
+            
+            // if it's in range, set the button data
+            if (idx > 0 && idx <= MAX_BUTTONS)
+            {
+                // adjust to an array index
+                --idx;
+                
+                // set the values
+                v_byte(button[idx].pin, 3);
+                v_byte(button[idx].typ, 4);
+                v_byte(button[idx].val, 5);
+                v_byte(button[idx].flags, 6);
+            }
+        }
+        break;
+        
+    case 13:
+        // LedWiz output port setup
+        {
+            // get the port number
+            int idx = data[2];
+            
+            // if it's in range, set the port data
+            if (idx > 0 && idx <= MAX_OUT_PORTS)
+            {
+                // adjust to an array index
+                --idx;
+                
+                // set the values
+                v_byte(outPort[idx].typ, 3);
+                v_byte(outPort[idx].pin, 4);
+                v_byte(outPort[idx].flags, 5);
+            }
+            else if (idx == 254)
+            {
+                // special ports
+                idx -= 254;
+                v_byte(specialPort[idx].typ, 3);
+                v_byte(specialPort[idx].pin, 4);
+                v_byte(specialPort[idx].flags, 5);
+            }
+        }
+        break;
+    }
+}
+
--- a/config.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/config.h	Wed Feb 03 22:57:25 2016 +0000
@@ -53,6 +53,25 @@
 // input button flags
 const uint8_t BtnFlagPulse     = 0x01;   // pulse mode - reports each change in the physical switch state
                                          // as a brief press of the logical button/keyboard key
+                                         
+// button setup structure
+struct ButtonCfg
+{
+    uint8_t pin;        // physical input GPIO pin - a USB-to-PinName mapping index
+    uint8_t typ;        // key type reported to PC - a BtnTypeXxx value
+    uint8_t val;        // key value reported - meaning depends on 'typ' value
+    uint8_t flags;      // key flags - a bitwise combination of BtnFlagXxx values
+
+    void set(uint8_t pin, uint8_t typ, uint8_t val, uint8_t flags = 0)
+    {
+        this->pin = pin;
+        this->typ = typ;
+        this->val = val;
+        this->flags = flags;
+    }
+        
+} __attribute__((packed));
+    
 
 // maximum number of input button mappings
 const int MAX_BUTTONS = 32;
@@ -69,6 +88,7 @@
 // LedWiz output port flag bits
 const uint8_t PortFlagActiveLow  = 0x01; // physical output is active-low
 const uint8_t PortFlagNoisemaker = 0x02; // noisemaker device - disable when night mode is engaged
+const uint8_t PortFlagGamma      = 0x04; // apply gamma correction to this output
 
 // maximum number of output ports
 const int MAX_OUT_PORTS = 203;
@@ -82,6 +102,14 @@
                         // the output number, starting from 0 for OUT0 on the first chip in 
                         // the daisy chain.  For inactive and virtual ports, it's unused.
     uint8_t flags;      // flags:  a combination of PortFlagXxx values
+    
+    void set(uint8_t typ, uint8_t pin, uint8_t flags = 0)
+    {
+        this->typ = typ;
+        this->pin = pin;
+        this->flags = flags;
+    }
+        
 } __attribute__((packed));
 
 
@@ -139,7 +167,7 @@
         
         // assume no TLC5940 chips
 #if 1 // $$$
-        tlc5940.nchips = 2;
+        tlc5940.nchips = 4;
 #else
         tlc5940.nchips = 0;
 #endif
@@ -152,8 +180,12 @@
         tlc5940.gsclk = PTA1;
         
         // assume no 74HC595 chips
+#if 1 // $$$
+        hc595.nchips = 1;
+#else
         hc595.nchips = 0;
-        
+#endif
+    
         // default 74HC595 pin assignments
         hc595.sin = PTA5;
         hc595.sclk = PTA4;
@@ -196,10 +228,8 @@
                 41, // 22 = PTD6
                 42, // 23 = PTD7
                 44  // 24 = PTE1
-            };                
-            button[i].pin = bp[i];
-            button[i].typ = BtnTypeKey;
-            button[i].val = i+4;  // A, B, C...
+            };               
+            button[i].set(bp[i], BtnTypeKey, i+4); // A, B, C... 
         }
 #endif
         
@@ -220,31 +250,54 @@
 #endif
         
 #if 1 // $$$
+        // CONFIGURE EXPANSION BOARD PORTS
+        //
+        // We have the following hardware attached:
+        //
+        //   Main board
+        //     TLC ports 0-15  -> flashers
+        //     TLC ports 16    -> strobe
+        //     TLC ports 17-31 -> flippers
+        //     Dig GPIO PTC8   -> knocker (timer-protected outputs)
+        //
+        //   Power board:
+        //     TLC ports 32-63 -> general purpose outputs
+        //
+        //   Chime board:
+        //     HC595 ports 0-7 -> timer-protected outputs
+        //
         {
             int n = 0;
-            for (int i = 0 ; i < 32 ; ++i, ++n) {
-                outPort[n].typ = PortTypeTLC5940;
-                outPort[n].pin = i;
-                outPort[n].flags = 0;
-            }
-            outPort[n].typ = PortTypeGPIODig;
-            outPort[n].pin = 27; // PTC8
-            outPort[n++].flags = 0;
+            
+            // 1-15 = flashers (TLC ports 0-15)
+            // 16   = strobe   (TLC port 15)
+            for (int i = 0 ; i < 16 ; ++i)
+                outPort[n++].set(PortTypeTLC5940, i, PortFlagGamma);
+            
+            // 17 = knocker
+            outPort[n++].set(PortTypeGPIODig, 27);
             
+            // 18-49 = power board outputs 1-32 (TLC ports 32-63)
+            for (int i = 0 ; i < 32 ; ++i)
+                outPort[n++].set(PortTypeTLC5940, i+32);
+            
+            // 50-65 = flipper RGB (TLC ports 16-31)
+            for (int i = 0 ; i < 16 ; ++i)
+                outPort[n++].set(PortTypeTLC5940, i+16, PortFlagGamma);
+            
+            // 66-73 = chime board ports 1-8 (74HC595 ports 0-7)
+            for (int i = 0 ; i < 8 ; ++i)
+                outPort[n++].set(PortType74HC595, i);
+            
+            // set Disabled to signify end of configured outputs
             outPort[n].typ = PortTypeDisabled;
         }
 #endif
 #if 0
-        outPort[0].typ = PortTypeGPIOPWM;
-        outPort[0].pin = 17;  // PTB18 = LED1 = Red LED
-        outPort[0].flags = PortFlagActiveLow;
-        outPort[1].typ = PortTypeGPIOPWM;
-        outPort[1].pin = 18;  // PTB19 = LED2 = Green LED
-        outPort[1].flags = PortFlagActiveLow;
-        outPort[2].typ = PortTypeGPIOPWM;
-        outPort[2].pin = 36;  // PTD1 = LED3 = Blue LED
-        outPort[2].flags = PortFlagActiveLow;
-
+        // configure the on-board RGB LED as outputs 1,2,3
+        outPort[0].set(PortTypeGPIOPWM, 17, PortFlagActiveLow);     // PTB18 = LED1 = Red LED
+        outPort[1].set(PortTypeGPIOPWM, 18, PortFlagActiveLow);     // PTB19 = LED2 = Green LED
+        outPort[2].set(PortTypeGPIOPWM, 36, PortFlagActiveLow);     // PTD1  = LED3 = Blue LED
         outPort[3].typ = PortTypeDisabled;
 #endif
     }        
@@ -315,18 +368,18 @@
         // This can be connected to the physical Launch button, or can simply be
         // an otherwise unused button.
         //
-        // The "push distance" is the distance, in inches, for registering a push
-        // on the plunger as a button push.  If the player pushes the plunger forward
-        // of the rest position by this amount, we'll treat it as pushing the button,
-        // even if the player didn't pull back the plunger first.  This lets the
-        // player treat the plunger knob as a button for games where it's meaningful
+        // The "push distance" is the distance, in 1/1000 inch units, for registering a 
+        // push on the plunger as a button push.  If the player pushes the plunger 
+        // forward of the rest position by this amount, we'll treat it as pushing the 
+        // button, even if the player didn't pull back the plunger first.  This lets 
+        // the player treat the plunger knob as a button for games where it's meaningful
         // to hold down the Launch button for specific intervals (e.g., "Championship 
         // Pub").
         struct
         {
             int port;
             int btn;
-            float pushDistance;
+            int pushDistance;
         
         } zbLaunchBall;
            
@@ -388,10 +441,10 @@
         // relay.  Raising the pin HIGH turns the relay ON (energizes the coil).
         PinName relayPin;
         
-        // TV ON delay time, in seconds.  This is the interval between sensing
-        // that the secondary power supply has turned on and pulsing the TV ON
-        // switch relay.  
-        float delayTime;
+        // TV ON delay time, in 1/100 second units.  This is the interval between 
+        // sensing that the secondary power supply has turned on and pulsing the 
+        // TV ON switch relay.  
+        int delayTime;
     
     } TVON;
     
@@ -429,15 +482,7 @@
 
 
     // --- Button Input Setup ---
-    struct
-    {
-        uint8_t pin;        // physical input GPIO pin - a USB-to-PinName mapping index
-        uint8_t typ;        // key type reported to PC - a BtnTypeXxx value
-        uint8_t val;        // key value reported - meaning depends on 'typ' value
-        uint8_t flags;      // key flags - a bitwise combination of BtnFlagXxx values
-        
-    } __attribute__((packed))  button[MAX_BUTTONS] __attribute((packed));
-    
+    ButtonCfg button[MAX_BUTTONS] __attribute__((packed));
 
     // --- LedWiz Output Port Setup ---
     LedWizPortCfg outPort[MAX_OUT_PORTS] __attribute__((packed));  // LedWiz & extended output ports 
--- a/main.cpp	Mon Jan 11 21:08:36 2016 +0000
+++ b/main.cpp	Wed Feb 03 22:57:25 2016 +0000
@@ -85,30 +85,32 @@
 //  - LedWiz emulation.  The KL25Z can appear to the PC as an LedWiz device, and will
 //    accept and process LedWiz commands from the host.  The software can turn digital
 //    output ports on and off, and can set varying PWM intensitiy levels on a subset
-//    of ports.  (The KL25Z can only provide 6 PWM ports.  Intensity level settings on
-//    other ports is ignored, so non-PWM ports can only be used for simple on/off
-//    devices such as contactors and solenoids.)  The KL25Z can only supply 4mA on its
-//    output ports, so external hardware is required to take advantage of the LedWiz
-//    emulation.  Many different hardware designs are possible, but there's a simple
-//    reference design in the documentation that uses a Darlington array IC to
-//    increase the output from each port to 500mA (the same level as the LedWiz),
-//    plus an extended design that adds an optocoupler and MOSFET to provide very
-//    high power handling, up to about 45A or 150W, with voltages up to 100V.
-//    That will handle just about any DC device directly (wtihout relays or other
-//    amplifiers), and switches fast enough to support PWM devices.
+//    of ports.  The KL25Z hardware is limited to 10 PWM ports.  Ports beyond the
+//    10 PWM ports are simple digital on/off ports.  Intensity level settings on 
+//    digital ports is ignored, so such ports can only be used for devices such as 
+//    contactors and solenoids that don't need differeing intensities.
 //
-//    The device can report any desired LedWiz unit number to the host, which makes
-//    it possible to use the LedWiz emulation on a machine that also has one or more
-//    actual LedWiz devices intalled.  The LedWiz design allows for up to 16 units
-//    to be installed in one machine - each one is invidually addressable by its
-//    distinct unit number.
+//    Note that the KL25Z can only supply or sink 4mA on its output ports, so external 
+//    amplifier hardware is required to use the LedWiz emulation.  Many different 
+//    hardware designs are possible, but there's a simple reference design in the 
+//    documentation that uses a Darlington array IC to increase the output from 
+//    each port to 500mA (the same level as the LedWiz), plus an extended design 
+//    that adds an optocoupler and MOSFET to provide very high power handling, up 
+//    to about 45A or 150W, with voltages up to 100V.  That will handle just about 
+//    any DC device directly (wtihout relays or other amplifiers), and switches fast 
+//    enough to support PWM devices.  For example, you can use it to drive a motor at
+//    different speeds via the PWM intensity.
+//
+//    The Controller device can report any desired LedWiz unit number to the host, 
+//    which makes it possible for one or more Pinscape Controller units to coexist
+//    with one more more real LedWiz units in the same machine.  The LedWiz design 
+//    allows for up to 16 units to be installed in one machine.  Each device needs
+//    to have a distinct LedWiz Unit Number, which allows software on the PC to
+//    address each device independently.
 //
 //    The LedWiz emulation features are of course optional.  There's no need to 
 //    build any of the external port hardware (or attach anything to the output 
-//    ports at all) if the LedWiz features aren't needed.  Most people won't have
-//    any use for the LedWiz features.  I built them mostly as a learning exercise,
-//    but with a slight practical need for a handful of extra ports (I'm using the
-//    cutting-edge 10-contactor setup, so my real LedWiz is full!).
+//    ports at all) if the LedWiz features aren't needed.
 //
 //  - Enhanced LedWiz emulation with TLC5940 PWM controller chips.  You can attach
 //    external PWM controller chips for controlling device outputs, instead of using
@@ -219,9 +221,28 @@
 
 // --------------------------------------------------------------------------
 // 
+// Extended verison of Timer class.  This adds the ability to interrogate
+// the running state.
+//
+class Timer2: public Timer
+{
+public:
+    Timer2() : running(false) { }
+
+    void start() { running = true; Timer::start(); }
+    void stop()  { running = false; Timer::stop(); }
+    
+    bool isRunning() const { return running; }
+    
+private:
+    bool running;
+};
+
+// --------------------------------------------------------------------------
+// 
 // USB product version number
 //
-const uint16_t USB_VERSION_NO = 0x0008;
+const uint16_t USB_VERSION_NO = 0x0009;
 
 // --------------------------------------------------------------------------
 //
@@ -232,8 +253,8 @@
 
 // ---------------------------------------------------------------------------
 //
-// Wire protocol value translations.  These translate byte values from
-// the USB protocol to local native format.
+// Wire protocol value translations.  These translate byte values to and
+// from the USB protocol to local native format.
 //
 
 // unsigned 16-bit integer 
@@ -241,33 +262,61 @@
 {
     return b[0] | ((uint16_t)b[1] << 8);
 }
+inline void ui16Wire(uint8_t *b, uint16_t val)
+{
+    b[0] = (uint8_t)(val & 0xff);
+    b[1] = (uint8_t)((val >> 8) & 0xff);
+}
 
 inline int16_t wireI16(const uint8_t *b)
 {
     return (int16_t)wireUI16(b);
 }
+inline void i16Wire(uint8_t *b, int16_t val)
+{
+    ui16Wire(b, (uint16_t)val);
+}
 
 inline uint32_t wireUI32(const uint8_t *b)
 {
     return b[0] | ((uint32_t)b[1] << 8) | ((uint32_t)b[2] << 16) | ((uint32_t)b[3] << 24);
 }
+inline void ui32Wire(uint8_t *b, uint32_t val)
+{
+    b[0] = (uint8_t)(val & 0xff);
+    b[1] = (uint8_t)((val >> 8) & 0xff);    
+    b[2] = (uint8_t)((val >> 16) & 0xff);    
+    b[3] = (uint8_t)((val >> 24) & 0xff);    
+}
 
 inline int32_t wireI32(const uint8_t *b)
 {
     return (int32_t)wireUI32(b);
 }
 
+static const PinName pinNameMap[] =  {
+    NC,    PTA1,  PTA2,  PTA4,  PTA5,  PTA12, PTA13, PTA16, PTA17, PTB0,    // 0-9
+    PTB1,  PTB2,  PTB3,  PTB8,  PTB9,  PTB10, PTB11, PTB18, PTB19, PTC0,    // 10-19
+    PTC1,  PTC2,  PTC3,  PTC4,  PTC5,  PTC6,  PTC7,  PTC8,  PTC9,  PTC10,   // 20-29
+    PTC11, PTC12, PTC13, PTC16, PTC17, PTD0,  PTD1,  PTD2,  PTD3,  PTD4,    // 30-39
+    PTD5,  PTD6,  PTD7,  PTE0,  PTE1,  PTE2,  PTE3,  PTE4,  PTE5,  PTE20,   // 40-49
+    PTE21, PTE22, PTE23, PTE29, PTE30, PTE31                                // 50-55
+};
 inline PinName wirePinName(int c)
 {
-    static const PinName p[] =  {
-        NC,    PTA1,  PTA2,  PTA4,  PTA5,  PTA12, PTA13, PTA16, PTA17, PTB0,    // 0-9
-        PTB1,  PTB2,  PTB3,  PTB8,  PTB9,  PTB10, PTB11, PTB18, PTB19, PTC0,    // 10-19
-        PTC1,  PTC2,  PTC3,  PTC4,  PTC5,  PTC6,  PTC7,  PTC8,  PTC9,  PTC10,   // 20-29
-        PTC11, PTC12, PTC13, PTC16, PTC17, PTD0,  PTD1,  PTD2,  PTD3,  PTD4,    // 30-39
-        PTD5,  PTD6,  PTD7,  PTE0,  PTE1,  PTE2,  PTE3,  PTE4,  PTE5,  PTE20,   // 40-49
-        PTE21, PTE22, PTE23, PTE29, PTE30, PTE31                                // 50-55
-    };
-    return (c < countof(p) ? p[c] : NC);
+    return (c < countof(pinNameMap) ? pinNameMap[c] : NC);
+}
+inline void pinNameWire(uint8_t *b, PinName n)
+{
+    b[0] = 0; // presume invalid -> NC
+    for (int i = 0 ; i < countof(pinNameMap) ; ++i)
+    {
+        if (pinNameMap[i] == n)
+        {
+            b[0] = i;
+            return;
+        }
+    }
 }
 
 
@@ -381,9 +430,9 @@
 class LwOut
 {
 public:
-    // Set the output intensity.  'val' is 0.0 for fully off, 1.0 for
-    // fully on, and fractional values for intermediate intensities.
-    virtual void set(float val) = 0;
+    // Set the output intensity.  'val' is 0 for fully off, 255 for
+    // fully on, with values in between signifying lower intensity.
+    virtual void set(uint8_t val) = 0;
 };
 
 // LwOut class for virtual ports.  This type of port is visible to
@@ -395,22 +444,73 @@
 {
 public:
     LwVirtualOut() { }
-    virtual void set(float val) { }
+    virtual void set(uint8_t ) { }
 };
 
 // Active Low out.  For any output marked as active low, we layer this
 // on top of the physical pin interface.  This simply inverts the value of
-// the output value, so that 1.0 means fully off and 0.0 means fully on.
+// the output value, so that 255 means fully off and 0 means fully on.
 class LwInvertedOut: public LwOut
 {
 public:
     LwInvertedOut(LwOut *o) : out(o) { }
-    virtual void set(float val) { out->set(1.0 - val); }
+    virtual void set(uint8_t val) { out->set(255 - val); }
     
 private:
     LwOut *out;
 };
 
+// Gamma correction table for 8-bit input values
+static const uint8_t gamma[] = {
+      0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   1, 
+      1,   1,   1,   1,   1,   1,   1,   1,   1,   2,   2,   2,   2,   2,   2,   2, 
+      2,   3,   3,   3,   3,   3,   3,   3,   4,   4,   4,   4,   4,   5,   5,   5, 
+      5,   6,   6,   6,   6,   7,   7,   7,   7,   8,   8,   8,   9,   9,   9,  10, 
+     10,  10,  11,  11,  11,  12,  12,  13,  13,  13,  14,  14,  15,  15,  16,  16, 
+     17,  17,  18,  18,  19,  19,  20,  20,  21,  21,  22,  22,  23,  24,  24,  25, 
+     25,  26,  27,  27,  28,  29,  29,  30,  31,  32,  32,  33,  34,  35,  35,  36, 
+     37,  38,  39,  39,  40,  41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  50, 
+     51,  52,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,  64,  66,  67,  68, 
+     69,  70,  72,  73,  74,  75,  77,  78,  79,  81,  82,  83,  85,  86,  87,  89, 
+     90,  92,  93,  95,  96,  98,  99, 101, 102, 104, 105, 107, 109, 110, 112, 114, 
+    115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, 135, 137, 138, 140, 142, 
+    144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 167, 169, 171, 173, 175, 
+    177, 180, 182, 184, 186, 189, 191, 193, 196, 198, 200, 203, 205, 208, 210, 213, 
+    215, 218, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, 255
+};
+
+// Gamma-corrected out.  This is a filter object that we layer on top
+// of a physical pin interface.  This applies gamma correction to the
+// input value and then passes it along to the underlying pin object.
+class LwGammaOut: public LwOut
+{
+public:
+    LwGammaOut(LwOut *o) : out(o) { }
+    virtual void set(uint8_t val) { out->set(gamma[val]); }
+    
+private:
+    LwOut *out;
+};
+
+// Noisy output.  This is a filter object that we layer on top of
+// a physical pin output.  This filter disables the port when night
+// mode is engaged.
+class LwNoisyOut: public LwOut
+{
+public:
+    LwNoisyOut(LwOut *o) : out(o) { }
+    virtual void set(uint8_t val) { out->set(nightMode ? 0 : val); }
+    
+    static bool nightMode;
+
+private:
+    LwOut *out;
+};
+
+// global night mode flag
+bool LwNoisyOut::nightMode = false;
+
 
 //
 // The TLC5940 interface object.  We'll set this up with the port 
@@ -426,6 +526,55 @@
     }
 }
 
+// Conversion table for 8-bit DOF level to 12-bit TLC5940 level
+static const uint16_t dof_to_tlc[] = {
+       0,   16,   32,   48,   64,   80,   96,  112,  128,  145,  161,  177,  193,  209,  225,  241, 
+     257,  273,  289,  305,  321,  337,  353,  369,  385,  401,  418,  434,  450,  466,  482,  498, 
+     514,  530,  546,  562,  578,  594,  610,  626,  642,  658,  674,  691,  707,  723,  739,  755, 
+     771,  787,  803,  819,  835,  851,  867,  883,  899,  915,  931,  947,  964,  980,  996, 1012, 
+    1028, 1044, 1060, 1076, 1092, 1108, 1124, 1140, 1156, 1172, 1188, 1204, 1220, 1237, 1253, 1269, 
+    1285, 1301, 1317, 1333, 1349, 1365, 1381, 1397, 1413, 1429, 1445, 1461, 1477, 1493, 1510, 1526, 
+    1542, 1558, 1574, 1590, 1606, 1622, 1638, 1654, 1670, 1686, 1702, 1718, 1734, 1750, 1766, 1783, 
+    1799, 1815, 1831, 1847, 1863, 1879, 1895, 1911, 1927, 1943, 1959, 1975, 1991, 2007, 2023, 2039, 
+    2056, 2072, 2088, 2104, 2120, 2136, 2152, 2168, 2184, 2200, 2216, 2232, 2248, 2264, 2280, 2296, 
+    2312, 2329, 2345, 2361, 2377, 2393, 2409, 2425, 2441, 2457, 2473, 2489, 2505, 2521, 2537, 2553, 
+    2569, 2585, 2602, 2618, 2634, 2650, 2666, 2682, 2698, 2714, 2730, 2746, 2762, 2778, 2794, 2810, 
+    2826, 2842, 2858, 2875, 2891, 2907, 2923, 2939, 2955, 2971, 2987, 3003, 3019, 3035, 3051, 3067, 
+    3083, 3099, 3115, 3131, 3148, 3164, 3180, 3196, 3212, 3228, 3244, 3260, 3276, 3292, 3308, 3324, 
+    3340, 3356, 3372, 3388, 3404, 3421, 3437, 3453, 3469, 3485, 3501, 3517, 3533, 3549, 3565, 3581, 
+    3597, 3613, 3629, 3645, 3661, 3677, 3694, 3710, 3726, 3742, 3758, 3774, 3790, 3806, 3822, 3838, 
+    3854, 3870, 3886, 3902, 3918, 3934, 3950, 3967, 3983, 3999, 4015, 4031, 4047, 4063, 4079, 4095
+};
+
+// Conversion table for 8-bit DOF level to 12-bit TLC5940 level, with 
+// gamma correction.  Note that the output layering scheme can handle
+// this without a separate table, by first applying gamma to the DOF
+// level to produce an 8-bit gamma-corrected value, then convert that
+// to the 12-bit TLC5940 value.  But we get better precision by doing
+// the gamma correction in the 12-bit TLC5940 domain.  We can only
+// get the 12-bit domain by combining both steps into one layering
+// object, though, since the intermediate values in the layering system
+// are always 8 bits.
+static const uint16_t dof_to_gamma_tlc[] = {
+      0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1,   1,   1,   1, 
+      2,   2,   2,   3,   3,   4,   4,   5,   5,   6,   7,   8,   8,   9,  10,  11, 
+     12,  13,  15,  16,  17,  18,  20,  21,  23,  25,  26,  28,  30,  32,  34,  36, 
+     38,  40,  43,  45,  48,  50,  53,  56,  59,  62,  65,  68,  71,  75,  78,  82, 
+     85,  89,  93,  97, 101, 105, 110, 114, 119, 123, 128, 133, 138, 143, 149, 154, 
+    159, 165, 171, 177, 183, 189, 195, 202, 208, 215, 222, 229, 236, 243, 250, 258, 
+    266, 273, 281, 290, 298, 306, 315, 324, 332, 341, 351, 360, 369, 379, 389, 399, 
+    409, 419, 430, 440, 451, 462, 473, 485, 496, 508, 520, 532, 544, 556, 569, 582, 
+    594, 608, 621, 634, 648, 662, 676, 690, 704, 719, 734, 749, 764, 779, 795, 811, 
+    827, 843, 859, 876, 893, 910, 927, 944, 962, 980, 998, 1016, 1034, 1053, 1072, 1091, 
+    1110, 1130, 1150, 1170, 1190, 1210, 1231, 1252, 1273, 1294, 1316, 1338, 1360, 1382, 1404, 1427, 
+    1450, 1473, 1497, 1520, 1544, 1568, 1593, 1617, 1642, 1667, 1693, 1718, 1744, 1770, 1797, 1823, 
+    1850, 1877, 1905, 1932, 1960, 1988, 2017, 2045, 2074, 2103, 2133, 2162, 2192, 2223, 2253, 2284, 
+    2315, 2346, 2378, 2410, 2442, 2474, 2507, 2540, 2573, 2606, 2640, 2674, 2708, 2743, 2778, 2813, 
+    2849, 2884, 2920, 2957, 2993, 3030, 3067, 3105, 3143, 3181, 3219, 3258, 3297, 3336, 3376, 3416, 
+    3456, 3496, 3537, 3578, 3619, 3661, 3703, 3745, 3788, 3831, 3874, 3918, 3962, 4006, 4050, 4095
+};
+
+
 // LwOut class for TLC5940 outputs.  These are fully PWM capable.
 // The 'idx' value in the constructor is the output index in the
 // daisy-chained TLC5940 array.  0 is output #0 on the first chip,
@@ -434,16 +583,31 @@
 class Lw5940Out: public LwOut
 {
 public:
-    Lw5940Out(int idx) : idx(idx) { prv = -1; }
-    virtual void set(float val)
+    Lw5940Out(int idx) : idx(idx) { prv = 0; }
+    virtual void set(uint8_t val)
     {
         if (val != prv)
-           tlc5940->set(idx, (int)((prv = val) * 4095.0f));
+           tlc5940->set(idx, dof_to_tlc[prv = val]);
     }
     int idx;
-    float prv;
+    uint8_t prv;
 };
 
+// LwOut class for TLC5940 gamma-corrected outputs.
+class Lw5940GammaOut: public LwOut
+{
+public:
+    Lw5940GammaOut(int idx) : idx(idx) { prv = 0; }
+    virtual void set(uint8_t val)
+    {
+        if (val != prv)
+           tlc5940->set(idx, dof_to_gamma_tlc[prv = val]);
+    }
+    int idx;
+    uint8_t prv;
+};
+
+
 
 // 74HC595 interface object.  Set this up with the port assignments in
 // config.h.
@@ -468,51 +632,81 @@
 class Lw595Out: public LwOut
 {
 public:
-    Lw595Out(int idx) : idx(idx) { prv = -1; }
-    virtual void set(float val)
+    Lw595Out(int idx) : idx(idx) { prv = 0; }
+    virtual void set(uint8_t val)
     {
         if (val != prv)
-           hc595->set(idx, (prv = val) == 0.0 ? 0 : 1);
+           hc595->set(idx, (prv = val) == 0 ? 0 : 1);
     }
     int idx;
-    float prv;
+    uint8_t prv;
 };
 
 
-// 
-// Default LedWiz mode - using on-board GPIO ports.  In this mode, we
-// assign a KL25Z GPIO port to each LedWiz output.  We have to use a
-// mix of PWM-capable and Digital-Only ports in this configuration, 
-// since the KL25Z hardware only has 10 PWM channels, which isn't
-// enough to fill out the full complement of 32 LedWiz outputs.
-//
+
+// Conversion table - 8-bit DOF output level to PWM float level
+// (normalized to 0.0..1.0 scale)
+static const float pwm_level[] = {
+    0.000000, 0.003922, 0.007843, 0.011765, 0.015686, 0.019608, 0.023529, 0.027451, 
+    0.031373, 0.035294, 0.039216, 0.043137, 0.047059, 0.050980, 0.054902, 0.058824, 
+    0.062745, 0.066667, 0.070588, 0.074510, 0.078431, 0.082353, 0.086275, 0.090196, 
+    0.094118, 0.098039, 0.101961, 0.105882, 0.109804, 0.113725, 0.117647, 0.121569, 
+    0.125490, 0.129412, 0.133333, 0.137255, 0.141176, 0.145098, 0.149020, 0.152941, 
+    0.156863, 0.160784, 0.164706, 0.168627, 0.172549, 0.176471, 0.180392, 0.184314, 
+    0.188235, 0.192157, 0.196078, 0.200000, 0.203922, 0.207843, 0.211765, 0.215686, 
+    0.219608, 0.223529, 0.227451, 0.231373, 0.235294, 0.239216, 0.243137, 0.247059, 
+    0.250980, 0.254902, 0.258824, 0.262745, 0.266667, 0.270588, 0.274510, 0.278431, 
+    0.282353, 0.286275, 0.290196, 0.294118, 0.298039, 0.301961, 0.305882, 0.309804, 
+    0.313725, 0.317647, 0.321569, 0.325490, 0.329412, 0.333333, 0.337255, 0.341176, 
+    0.345098, 0.349020, 0.352941, 0.356863, 0.360784, 0.364706, 0.368627, 0.372549, 
+    0.376471, 0.380392, 0.384314, 0.388235, 0.392157, 0.396078, 0.400000, 0.403922, 
+    0.407843, 0.411765, 0.415686, 0.419608, 0.423529, 0.427451, 0.431373, 0.435294, 
+    0.439216, 0.443137, 0.447059, 0.450980, 0.454902, 0.458824, 0.462745, 0.466667, 
+    0.470588, 0.474510, 0.478431, 0.482353, 0.486275, 0.490196, 0.494118, 0.498039, 
+    0.501961, 0.505882, 0.509804, 0.513725, 0.517647, 0.521569, 0.525490, 0.529412, 
+    0.533333, 0.537255, 0.541176, 0.545098, 0.549020, 0.552941, 0.556863, 0.560784, 
+    0.564706, 0.568627, 0.572549, 0.576471, 0.580392, 0.584314, 0.588235, 0.592157, 
+    0.596078, 0.600000, 0.603922, 0.607843, 0.611765, 0.615686, 0.619608, 0.623529, 
+    0.627451, 0.631373, 0.635294, 0.639216, 0.643137, 0.647059, 0.650980, 0.654902, 
+    0.658824, 0.662745, 0.666667, 0.670588, 0.674510, 0.678431, 0.682353, 0.686275, 
+    0.690196, 0.694118, 0.698039, 0.701961, 0.705882, 0.709804, 0.713725, 0.717647, 
+    0.721569, 0.725490, 0.729412, 0.733333, 0.737255, 0.741176, 0.745098, 0.749020, 
+    0.752941, 0.756863, 0.760784, 0.764706, 0.768627, 0.772549, 0.776471, 0.780392, 
+    0.784314, 0.788235, 0.792157, 0.796078, 0.800000, 0.803922, 0.807843, 0.811765, 
+    0.815686, 0.819608, 0.823529, 0.827451, 0.831373, 0.835294, 0.839216, 0.843137, 
+    0.847059, 0.850980, 0.854902, 0.858824, 0.862745, 0.866667, 0.870588, 0.874510, 
+    0.878431, 0.882353, 0.886275, 0.890196, 0.894118, 0.898039, 0.901961, 0.905882, 
+    0.909804, 0.913725, 0.917647, 0.921569, 0.925490, 0.929412, 0.933333, 0.937255, 
+    0.941176, 0.945098, 0.949020, 0.952941, 0.956863, 0.960784, 0.964706, 0.968627, 
+    0.972549, 0.976471, 0.980392, 0.984314, 0.988235, 0.992157, 0.996078, 1.000000
+};
 
 // LwOut class for a PWM-capable GPIO port
 class LwPwmOut: public LwOut
 {
 public:
-    LwPwmOut(PinName pin) : p(pin) { prv = -1; }
-    virtual void set(float val) 
+    LwPwmOut(PinName pin) : p(pin) { prv = 0; }
+    virtual void set(uint8_t val) 
     { 
         if (val != prv)
-            p.write(prv = val); 
+            p.write(pwm_level[prv = val]); 
     }
     PwmOut p;
-    float prv;
+    uint8_t prv;
 };
 
 // LwOut class for a Digital-Only (Non-PWM) GPIO port
 class LwDigOut: public LwOut
 {
 public:
-    LwDigOut(PinName pin) : p(pin) { prv = -1; }
-    virtual void set(float val) 
+    LwDigOut(PinName pin) : p(pin) { prv = 0; }
+    virtual void set(uint8_t val) 
     {
          if (val != prv)
-            p.write((prv = val) == 0.0 ? 0 : 1); 
+            p.write((prv = val) == 0 ? 0 : 1); 
     }
     DigitalOut p;
-    float prv;
+    uint8_t prv;
 };
 
 // Array of output physical pin assignments.  This array is indexed
@@ -532,6 +726,7 @@
 //    [0] = Night Mode indicator light
 //
 static LwOut *specialPin[1];
+const int SPECIAL_PIN_NIGHTMODE = 0;
 
 
 // Number of LedWiz emulation outputs.  This is the number of ports
@@ -541,20 +736,11 @@
 // lower of 32 or the actual number of outputs.
 static int numLwOutputs;
 
-// Current absolute brightness level for an output.  This is a float
-// value from 0.0 for fully off to 1.0 for fully on.  This is used
-// for all extended ports (33 and above), and for any LedWiz port
-// with wizVal == 255.
-static float *outLevel;
-
-// Day/night mode override for an output.  For each output, this is
-// set to 1 if the output is enabled and 0 if the output is disabled
-// by a global mode control, such as Night Mode (currently Night Mode
-// is the only such global mode, but the idea could be extended to
-// other similar controls if other needs emerge).  To get the final
-// output level for each output, we simply multiply the outLevel value
-// for the port by this override vlaue.
-static uint8_t *modeLevel;
+// Current absolute brightness level for an output.  This is a DOF
+// brightness level value, from 0 for fully off to 255 for fully on.  
+// This is used for all extended ports (33 and above), and for any 
+// LedWiz port with wizVal == 255.
+static uint8_t *outLevel;
 
 // create a single output pin
 LwOut *createLwPin(LedWizPortCfg &pc, Config &cfg)
@@ -563,7 +749,9 @@
     int typ = pc.typ;
     int pin = pc.pin;
     int flags = pc.flags;
+    int noisy = flags & PortFlagNoisemaker;
     int activeLow = flags & PortFlagActiveLow;
+    int gamma = flags & PortFlagGamma;
 
     // create the pin interface object according to the port type        
     LwOut *lwp;
@@ -583,9 +771,37 @@
         // TLC5940 port (if we don't have a TLC controller object, or it's not a valid
         // output port number on the chips we have, create a virtual port)
         if (tlc5940 != 0 && pin < cfg.tlc5940.nchips*16)
-            lwp = new Lw5940Out(pin);
+        {
+            // If gamma correction is to be used, and we're not inverting the output,
+            // use the combined TLC4950 + Gamma output class.  Otherwise use the plain 
+            // TLC5940 output.  We skip the combined class if the output is inverted
+            // because we need to apply gamma BEFORE the inversion to get the right
+            // results, but the combined class would apply it after because of the
+            // layering scheme - the combined class is a physical device output class,
+            // and a physical device output class is necessarily at the bottom of 
+            // the stack.  We don't have a combined inverted+gamma+TLC class, because
+            // inversion isn't recommended for TLC5940 chips in the first place, so
+            // it's not worth the extra memory footprint to have a dedicated table
+            // for this unlikely case.
+            if (gamma && !activeLow)
+            {
+                // use the gamma-corrected 5940 output mapper
+                lwp = new Lw5940GammaOut(pin);
+                
+                // DON'T apply further gamma correction to this output
+                gamma = false;
+            }
+            else
+            {
+                // no gamma - use the plain (linear) 5940 output class
+                lwp = new Lw5940Out(pin);
+            }
+        }
         else
+        {
+            // no TLC5940 chips, or invalid port number - use a virtual out
             lwp = new LwVirtualOut();
+        }
         break;
     
     case PortType74HC595:
@@ -604,9 +820,20 @@
         break;
     }
     
-    // if it's Active Low, layer on an inverter
+    // If it's Active Low, layer on an inverter.  Note that an inverter
+    // needs to be the bottom-most layer, since all of the other filters
+    // assume that they're working with normal (non-inverted) values.
     if (activeLow)
         lwp = new LwInvertedOut(lwp);
+        
+    // If it's a noisemaker, layer on a night mode switch.  Note that this
+    // needs to be 
+    if (noisy)
+        lwp = new LwNoisyOut(lwp);
+        
+    // If it's gamma-corrected, layer on a gamma corrector
+    if (gamma)
+        lwp = new LwGammaOut(lwp);
 
     // turn it off initially      
     lwp->set(0);
@@ -643,13 +870,7 @@
     // allocate the full set of actual ports if we have more than the
     // LedWiz complement.
     int minOuts = numOutputs < 32 ? 32 : numOutputs;
-    outLevel = new float[minOuts];
-    
-    // Allocate the mode override array
-    modeLevel = new uint8_t[minOuts];
-    
-    // start with all modeLevel values set to ON
-    memset(modeLevel, 1, minOuts);
+    outLevel = new uint8_t[minOuts];
     
     // create the pin interface object for each port
     for (i = 0 ; i < numOutputs ; ++i)
@@ -674,22 +895,24 @@
 // on/off state for each LedWiz output
 static uint8_t wizOn[32];
 
-// Profile (brightness/blink) state for each LedWiz output.  If the
-// output was last updated through an LedWiz protocol message, it
-// will have one of these values:
+// LedWiz "Profile State" (the LedWiz brightness level or blink mode)
+// for each LedWiz output.  If the output was last updated through an 
+// LedWiz protocol message, it will have one of these values:
 //
 //   0-48 = fixed brightness 0% to 100%
+//   49  = fixed brightness 100% (equivalent to 48)
 //   129 = ramp up / ramp down
 //   130 = flash on / off
 //   131 = on / ramp down
 //   132 = ramp up / on
 //
-// Special value 255:  If the output was updated through the 
-// extended protocol, we'll set the wizVal entry to 255, which has 
-// no meaning in the LedWiz protocol.  This tells us that the value 
-// in outLevel[] was set directly from the extended protocol, so it 
-// shouldn't be derived from wizVal[].
+// If the output was last updated through an extended protocol message,
+// it will have the special value 255.  This means that we use the
+// outLevel[] value for the port instead of an LedWiz setting.
 //
+// (Note that value 49 isn't documented in the LedWiz spec, but real
+// LedWiz units treat it as equivalent to 48, and some PC software uses
+// it, so we need to accept it for compatibility.)
 static uint8_t wizVal[32] = {
     48, 48, 48, 48, 48, 48, 48, 48,
     48, 48, 48, 48, 48, 48, 48, 48,
@@ -701,11 +924,24 @@
 // rate for lights in blinking states.
 static uint8_t wizSpeed = 2;
 
-// Current LedWiz flash cycle counter.
+// Current LedWiz flash cycle counter.  This runs from 0 to 255
+// during each cycle.
 static uint8_t wizFlashCounter = 0;
 
-// Get the current brightness level for an LedWiz output.
-static float wizState(int idx)
+// translate an LedWiz brightness level (0-49) to a DOF brightness
+// level (0-255)
+static const uint8_t lw_to_dof[] = {
+       0,    5,   11,   16,   21,   27,   32,   37, 
+      43,   48,   53,   58,   64,   69,   74,   80, 
+      85,   90,   96,  101,  106,  112,  117,  122, 
+     128,  133,  138,  143,  149,  154,  159,  165, 
+     170,  175,  181,  186,  191,  197,  202,  207, 
+     213,  218,  223,  228,  234,  239,  244,  250, 
+     255,  255
+};
+
+// Translate an LedWiz output (ports 1-32) to a DOF brightness level.
+static uint8_t wizState(int idx)
 {
     // if the output was last set with an extended protocol message,
     // use the value set there, ignoring the output's LedWiz state
@@ -718,7 +954,7 @@
 
     // check the state
     uint8_t val = wizVal[idx];
-    if (val <= 48)
+    if (val <= 49)
     {
         // PWM brightness/intensity level.  Rescale from the LedWiz
         // 0..48 integer range to our internal PwmOut 0..1 float range.
@@ -740,40 +976,34 @@
         // makes us work properly with software that's expecting the
         // documented LedWiz behavior and therefore uses level 48 to
         // turn a contactor or relay fully on.
-        return val/48.0f;
-    }
-    else if (val == 49)
-    {
-        // 49 is undefined in the LedWiz documentation, but actually
-        // means 100% on.  The documentation says that levels 1-48 are
-        // the full PWM range, but empirically it appears that the real
-        // range implemented in the firmware is 1-49.  Some software on
-        // the PC side (notably DOF) is aware of this and uses level 49
-        // to mean "100% on".  To ensure compatibility with existing 
-        // PC-side software, we need to recognize level 49.
-        return 1.0f;
+        //
+        // Note that value 49 is undefined in the LedWiz documentation,
+        // but real LedWiz units treat it as 100%, equivalent to 48.
+        // Some software on the PC side uses this, so we need to treat
+        // it the same way for compatibility.
+        return lw_to_dof[val];
     }
     else if (val == 129)
     {
-        //   129 = ramp up / ramp down
+        // 129 = ramp up / ramp down
         return wizFlashCounter < 128 
-            ? wizFlashCounter/128.0f 
-            : (256 - wizFlashCounter)/128.0f;
+            ? wizFlashCounter*2 + 1
+            : (255 - wizFlashCounter)*2;
     }
     else if (val == 130)
     {
-        //   130 = flash on / off
-        return wizFlashCounter < 128 ? 1.0f : 0.0f;
+        // 130 = flash on / off
+        return wizFlashCounter < 128 ? 255 : 0;
     }
     else if (val == 131)
     {
-        //   131 = on / ramp down
-        return wizFlashCounter < 128 ? 1.0f : (255 - wizFlashCounter)/128.0f;
+        // 131 = on / ramp down
+        return wizFlashCounter < 128 ? 255 : (255 - wizFlashCounter)*2;
     }
     else if (val == 132)
     {
-        //   132 = ramp up / on
-        return wizFlashCounter < 128 ? wizFlashCounter/128.0f : 1.0f;
+        // 132 = ramp up / on
+        return wizFlashCounter < 128 ? wizFlashCounter*2 : 255;
     }
     else
     {
@@ -782,7 +1012,7 @@
         // LedWiz unit exhibits in response is accidental and could change
         // in a future version.  We'll treat all undefined values as equivalent 
         // to 48 (fully on).
-        return 1.0f;
+        return 255;
     }
 }
 
@@ -812,7 +1042,7 @@
             uint8_t s = wizVal[i];
             if (s >= 129 && s <= 132)
             {
-                lwPin[i]->set(wizState(i) * modeLevel[i]);
+                lwPin[i]->set(wizState(i));
                 ena = true;
             }
         }
@@ -837,7 +1067,7 @@
     for (int i = 0 ; i < numLwOutputs ; ++i)
     {
         pulse |= (wizVal[i] >= 129 && wizVal[i] <= 132);
-        lwPin[i]->set(wizState(i) * modeLevel[i]);
+        lwPin[i]->set(wizState(i));
     }
     
     // if any outputs are set to flashing mode, and the pulse timer
@@ -856,11 +1086,11 @@
 {
     // uddate each LedWiz output
     for (int i = 0 ; i < numLwOutputs ; ++i)
-        lwPin[i]->set(wizState(i) * modeLevel[i]);
+        lwPin[i]->set(wizState(i));
         
     // update each extended output
     for (int i = 33 ; i < numOutputs ; ++i)
-        lwPin[i]->set(outLevel[i] * modeLevel[i]);
+        lwPin[i]->set(outLevel[i]);
         
     // flush 74HC595 changes, if necessary
     if (hc595 != 0)
@@ -1677,7 +1907,7 @@
     }
     
     // reset all extended outputs (ports >32) to full off (brightness 0)
-    for (int i = 32 ; i < numOutputs ; ++i)
+    for (int i = numLwOutputs ; i < numOutputs ; ++i)
     {
         outLevel[i] = 0;
         lwPin[i]->set(0);
@@ -1723,16 +1953,20 @@
 // previous check.  When we see this condition, we start a countdown
 // timer, and pulse the TV switch relay when the countdown ends.
 //
-// This scheme might seem a little convoluted, but it neatly handles
-// all of the different cases that can occur:
+// This scheme might seem a little convoluted, but it handles a number
+// of tricky but likely scenarios:
 //
 // - Most cabinets systems are set up with "soft" PC power switches, 
-//   so that the PC goes into "Soft Off" mode (ACPI state S5, in Windows
-//   parlance) when the user turns off the cabinet.  In this state, the
-//   motherboard supplies power to USB devices, so the KL25Z continues
-//   running without interruption.  The latch system lets us monitor
-//   the power state even when we're never rebooted, since the latch
-//   will turn off when PSU2 is off regardless of what the KL25Z is doing.
+//   so that the PC goes into "Soft Off" mode when the user turns off
+//   the cabinet by pushing the power button or using the Shut Down
+//   command from within Windows.  In Windows parlance, this "soft off"
+//   condition is called ACPI State S5.  In this state, the main CPU
+//   power is turned off, but the motherboard still provides power to
+//   USB devices.  This means that the KL25Z keeps running.  Without
+//   the external power sensing circuit, the only hint that we're in 
+//   this state is that the USB connection to the host goes into Suspend
+//   mode, but that could mean other things as well.  The latch circuit
+//   lets us tell for sure that we're in this state.
 //
 // - Some cabinet builders might prefer to use "hard" power switches,
 //   cutting all power to the cabinet, including the PC motherboard (and
@@ -1741,14 +1975,15 @@
 //   a power outage occurs, etc.  In these cases, the KL25Z will do a cold
 //   boot when the PC is turned on.  We don't know whether the KL25Z
 //   will power up before or after PSU2, so it's not good enough to 
-//   observe the *current* state of PSU2 when we first check - if PSU2
-//   were to come on first, checking the current state alone would fool
-//   us into thinking that no action is required, because we would never
-//   have known that PSU2 was ever off.  The latch handles this case by
-//   letting us see that PSU2 *was* off before we checked.
+//   observe the current state of PSU2 when we first check.  If PSU2
+//   were to come on first, checking only the current state would fool
+//   us into thinking that no action is required, because we'd only see
+//   that PSU2 is turned on any time we check.  The latch handles this 
+//   case by letting us see that PSU2 was indeed off some time before our
+//   first check.
 //
 // - If the KL25Z is rebooted while the main system is running, or the 
-//   KL25Z is unplugged and plugged back in, we will correctly leave the 
+//   KL25Z is unplugged and plugged back in, we'll correctly leave the 
 //   TVs as they are.  The latch state is independent of the KL25Z's 
 //   power or software state, so it's won't affect the latch state when
 //   the KL25Z is unplugged or rebooted; when we boot, we'll see that 
@@ -1756,7 +1991,6 @@
 //   This is important because TV ON buttons are usually on/off toggles,
 //   so we don't want to push the button on a TV that's already on.
 //   
-//
 
 // Current PSU2 state:
 //   1 -> default: latch was on at last check, or we haven't checked yet
@@ -1764,7 +1998,6 @@
 //   3 -> SET pulsed low, ready to check status
 //   4 -> TV timer countdown in progress
 //   5 -> TV relay on
-//   
 int psu2_state = 1;
 
 // PSU2 power sensing circuit connections
@@ -1810,7 +2043,7 @@
         
     case 3:
         // CHECK state: we pulsed SET, and we're now ready to see
-        // if that stuck.  If the latch is now on, PSU2 has transitioned
+        // if it stuck.  If the latch is now on, PSU2 has transitioned
         // from OFF to ON, so start the TV countdown.  If the latch is
         // off, our SET command didn't stick, so PSU2 is still off.
         if (psu2_status_sense->read())
@@ -1863,7 +2096,7 @@
         psu2_status_sense = new DigitalIn(cfg.TVON.statusPin);
         psu2_status_set = new DigitalOut(cfg.TVON.latchPin);
         tv_relay = new DigitalOut(cfg.TVON.relayPin);
-        tv_delay_time = cfg.TVON.delayTime;
+        tv_delay_time = cfg.TVON.delayTime/100.0;
     
         // Set up our time routine to run every 1/4 second.  
         tv_ticker.attach(&TVTimerInt, 0.25);
@@ -1957,43 +2190,26 @@
 
 // ---------------------------------------------------------------------------
 //
-// NIGHT MODE flag.  When night mode is on, we disable all outputs
-// marked as "noisemakers" in the output configuration flags.
-int nightMode;
-
-// Update the global output mode settings
-static void globalOutputModeChange()
-{
-    // set the global modeLevel[] 
-    for (int i = 0 ; i < numOutputs ; ++i)
-    {
-        // assume the port will be on
-        uint8_t f = 1;
-        
-        // if night mode is in effect, and this is a noisemaker, disable it
-        if (nightMode && (cfg.outPort[i].flags & PortFlagNoisemaker) != 0)
-            f = 0;
-            
-        // set the final output port override value
-        modeLevel[i] = f;
-    }
-    
-    // update all outputs for the mode change
-    updateAllOuts();
-}
+// Night mode setting updates
+//
 
 // Turn night mode on or off
 static void setNightMode(bool on)
 {
-    nightMode = on;
-    globalOutputModeChange();
-    specialPin[0]->set(on ? 255.0 : 0.0);
+    // set the new night mode flag in the noisy output class
+    LwNoisyOut::nightMode = on;
+
+    // update the special output pin that shows the night mode state
+    specialPin[SPECIAL_PIN_NIGHTMODE]->set(on ? 255 : 0);
+
+    // update all outputs for the mode change
+    updateAllOuts();
 }
 
 // Toggle night mode
 static void toggleNightMode()
 {
-    setNightMode(!nightMode);
+    setNightMode(!LwNoisyOut::nightMode);
 }
 
 
@@ -2131,144 +2347,32 @@
 
 // ---------------------------------------------------------------------------
 //
-// Handle a configuration variable update.  'data' is the USB message we
-// received from the host.
+// Configuration variable get/set message handling
 //
-void configVarMsg(uint8_t *data)
-{
-    switch (data[1])
-    {
-    case 1:
-        // USB identification (Vendor ID, Product ID)
-        cfg.usbVendorID = wireUI16(data+2);
-        cfg.usbProductID = wireUI16(data+4);
-        break;
-        
-    case 2:
-        // Pinscape Controller unit number - note that data[2] contains
-        // the nominal unit number, 1-16
-        if (data[2] >= 1 && data[2] <= 16)
-            cfg.psUnitNo = data[2];
-        break;
-        
-    case 3:
-        // Enable/disable joystick
-        cfg.joystickEnabled = data[2];
-        break;
-        
-    case 4:
-        // Accelerometer orientation
-        cfg.orientation = data[2];
-        break;
+
+// Handle SET messages - write configuration variables from USB message data
+#define if_msg_valid(test)  if (test)
+#define v_byte(var, ofs)   cfg.var = data[ofs]
+#define v_ui16(var, ofs)   cfg.var = wireUI16(data+ofs)
+#define v_pin(var, ofs)    cfg.var = wirePinName(data[ofs])
+#define v_func configVarSet
+#include "cfgVarMsgMap.h"
 
-    case 5:
-        // Plunger sensor type
-        cfg.plunger.sensorType = data[2];
-        break;
-        
-    case 6:
-        // Set plunger pin assignments
-        cfg.plunger.sensorPin[0] = wirePinName(data[2]);
-        cfg.plunger.sensorPin[1] = wirePinName(data[3]);
-        cfg.plunger.sensorPin[2] = wirePinName(data[4]);
-        cfg.plunger.sensorPin[3] = wirePinName(data[5]);
-        break;
-        
-    case 7:
-        // Plunger calibration button and indicator light pin assignments
-        cfg.plunger.cal.btn = wirePinName(data[2]);
-        cfg.plunger.cal.led = wirePinName(data[3]);
-        break;
-        
-    case 8:
-        // ZB Launch Ball setup
-        cfg.plunger.zbLaunchBall.port = (int)(unsigned char)data[2];
-        cfg.plunger.zbLaunchBall.btn = (int)(unsigned char)data[3];
-        cfg.plunger.zbLaunchBall.pushDistance = (float)wireUI16(data+4) / 1000.0;
-        break;
-        
-    case 9:
-        // TV ON setup
-        cfg.TVON.statusPin = wirePinName(data[2]);
-        cfg.TVON.latchPin = wirePinName(data[3]);
-        cfg.TVON.relayPin = wirePinName(data[4]);
-        cfg.TVON.delayTime = (float)wireUI16(data+5) / 100.0;
-        break;
-        
-    case 10:
-        // TLC5940NT PWM controller chip setup
-        cfg.tlc5940.nchips = (int)(unsigned char)data[2];
-        cfg.tlc5940.sin = wirePinName(data[3]);
-        cfg.tlc5940.sclk = wirePinName(data[4]);
-        cfg.tlc5940.xlat = wirePinName(data[5]);
-        cfg.tlc5940.blank = wirePinName(data[6]);
-        cfg.tlc5940.gsclk = wirePinName(data[7]);
-        break;
-        
-    case 11:
-        // 74HC595 shift register chip setup
-        cfg.hc595.nchips = (int)(unsigned char)data[2];
-        cfg.hc595.sin = wirePinName(data[3]);
-        cfg.hc595.sclk = wirePinName(data[4]);
-        cfg.hc595.latch = wirePinName(data[5]);
-        cfg.hc595.ena = wirePinName(data[6]);
-        break;
-        
-    case 12:
-        // button setup
-        {
-            // get the button number
-            int idx = data[2];
-            
-            // if it's in range, set the button data
-            if (idx > 0 && idx <= MAX_BUTTONS)
-            {
-                // adjust to an array index
-                --idx;
-                
-                // set the values
-                cfg.button[idx].pin = data[3];
-                cfg.button[idx].typ = data[4];
-                cfg.button[idx].val = data[5];
-                cfg.button[idx].flags = data[6];
-            }
-        }
-        break;
-        
-    case 13:
-        // LedWiz output port setup
-        {
-            // get the port number
-            int idx = data[2];
-            
-            // if it's in range, set the port data
-            if (idx > 0 && idx <= MAX_OUT_PORTS)
-            {
-                // adjust to an array index
-                --idx;
-                
-                // set the values
-                cfg.outPort[idx].typ = data[3];
-                cfg.outPort[idx].pin = data[4];
-                cfg.outPort[idx].flags = data[5];
-            }
-            else if (idx == 254)
-            {
-                // special ports
-                idx -= 254;
-                cfg.specialPort[idx].typ = data[3];
-                cfg.specialPort[idx].pin = data[4];
-                cfg.specialPort[idx].flags = data[5];
-            }
-        }
-        break;
+// redefine everything for the SET messages
+#undef if_msg_valid
+#undef v_byte
+#undef v_ui16
+#undef v_pin
+#undef v_func
 
-    case 14:
-        // engage/cancel Night Mode
-        setNightMode(data[2]);
-        break;
-    }
-}
+// Handle GET messages - read variable values and return in USB message daa
+#define if_msg_valid(test)
+#define v_byte(var, ofs)   data[ofs] = cfg.var
+#define v_ui16(var, ofs)   ui16Wire(data+ofs, cfg.var)
+#define v_pin(var, ofs)    pinNameWire(data+ofs, cfg.var)
+#define v_func  configVarGet
+#include "cfgVarMsgMap.h"
+
 
 // ---------------------------------------------------------------------------
 //
@@ -2326,7 +2430,7 @@
             // states are independent, so an SBA just turns an output
             // on or off but retains its last brightness level.
             if (wizVal[i] == 255)
-                wizVal[i] = (uint8_t)round(outLevel[i]*48);
+                wizVal[i] = (uint8_t)round(outLevel[i]/255.0 * 48.0);
         }
         
         // set the flash speed - enforce the value range 1-7
@@ -2416,7 +2520,8 @@
             js.reportConfig(
                 numOutputs, 
                 cfg.psUnitNo - 1,   // report 0-15 range for unit number (we store 1-16 internally)
-                cfg.plunger.cal.zero, cfg.plunger.cal.max);
+                cfg.plunger.cal.zero, cfg.plunger.cal.max,
+                nvm.valid());
             break;
             
         case 5:
@@ -2434,6 +2539,18 @@
             // really needed.
             reboot(js);
             break;
+            
+        case 7:
+            // 7 = Device ID report
+            // (No parameters)
+            js.reportID();
+            break;
+            
+        case 8:
+            // 8 = Engage/disengage night mode.
+            //     data[2] = 1 to engage, 0 to disengage
+            setNightMode(data[2]);
+            break;
         }
     }
     else if (data[0] == 66)
@@ -2442,7 +2559,7 @@
         // The second byte of the message is the ID of the variable
         // to update, and the remaining bytes give the new value,
         // in a variable-dependent format.
-        configVarMsg(data);
+        configVarSet(data);
     }
     else if (data[0] >= 200 && data[0] <= 228)
     {
@@ -2470,7 +2587,7 @@
         for (int i = i0 ; i < i1 ; ++i)
         {
             // set the brightness level for the output
-            float b = data[i-i0+1]/255.0;
+            uint8_t b = data[i-i0+1];
             outLevel[i] = b;
             
             // if it's in the basic LedWiz output set, set the LedWiz
@@ -2479,7 +2596,7 @@
                 wizVal[i] = 255;
                 
             // set the output
-            lwPin[i]->set(b * modeLevel[i]);
+            lwPin[i]->set(b);
         }
         
         // update 74HC595 outputs, if attached
@@ -2567,12 +2684,9 @@
     Ticker preConnectTicker;
     preConnectTicker.attach(preConnectFlasher, 3);
 
-    // start the TV timer, if applicable
-    startTVTimer(cfg);
-    
     // we're not connected/awake yet
     bool connected = false;
-    time_t connectChangeTime = time(0);
+    Timer connectChangeTimer;
 
     // create the plunger sensor interface
     createPlunger();
@@ -2594,6 +2708,9 @@
     if (tlc5940 != 0)
         tlc5940->start();
         
+    // start the TV timer, if applicable
+    startTVTimer(cfg);
+    
     // initialize the button input ports
     bool kbKeys = false;
     initButtons(cfg, kbKeys);
@@ -2604,7 +2721,7 @@
     
     // we're now connected - kill the pre-connect ticker
     preConnectTicker.detach();
-        
+    
     // Last report timer for the joytick interface.  We use the joystick timer 
     // to throttle the report rate, because VP doesn't benefit from reports any 
     // faster than about every 10ms.
@@ -2980,7 +3097,7 @@
             if (cfg.plunger.zbLaunchBall.port != 0)
             {
                 const int cockThreshold = JOYMAX/3;
-                const int pushThreshold = int(-JOYMAX/3 * cfg.plunger.zbLaunchBall.pushDistance);
+                const int pushThreshold = int(-JOYMAX/3.0 * cfg.plunger.zbLaunchBall.pushDistance/1000.0);
                 int newState = lbState;
                 switch (lbState)
                 {
@@ -3293,20 +3410,70 @@
 #endif
 
         // check for connection status changes
-        int newConnected = js.isConnected() && !js.isSuspended();
+        bool newConnected = js.isConnected() && !js.isSuspended();
         if (newConnected != connected)
         {
             // give it a few seconds to stabilize
-            time_t tc = time(0);
-            if (tc - connectChangeTime > 3)
+            connectChangeTimer.start();
+            if (connectChangeTimer.read() > 3)
             {
                 // note the new status
                 connected = newConnected;
-                connectChangeTime = tc;
+                
+                // done with the change timer for this round - reset it for next time
+                connectChangeTimer.stop();
+                connectChangeTimer.reset();
                 
-                // if we're no longer connected, turn off all outputs
-                if (!connected)
+                // adjust to the new status
+                if (connected)
+                {
+                    // We're newly connected.  This means we just powered on, we were
+                    // just plugged in to the PC USB port after being unplugged, or the
+                    // PC just came out of sleep/suspend mode and resumed the connection.
+                    // In any of these cases, we can now assume that the PC power supply
+                    // is on (the PC must be on for the USB connection to be running, and
+                    // if the PC is on, its power supply is on).  This also means that 
+                    // power to any external output controller chips (TLC5940, 74HC595)
+                    // is now on, because those have to be powered from the PC power
+                    // supply to allow for a reliable data connection to the KL25Z.
+                    // We can thus now set clear initial output state in those chips and
+                    // enable their outputs.
+                    if (tlc5940 != 0)
+                    {
+                        tlc5940->update(true);
+                        tlc5940->enable(true);
+                    }
+                    if (hc595 != 0)
+                    {
+                        hc595->update(true);
+                        hc595->enable(true);
+                    }
+                }
+                else
+                {
+                    // We're no longer connected.  Turn off all outputs.
                     allOutputsOff();
+                    
+                    // The KL25Z runs off of USB power, so we might (depending on the PC
+                    // and OS configuration) continue to receive power even when the main
+                    // PC power supply is turned off, such as in soft-off or suspend/sleep
+                    // mode.  Any external output controller chips (TLC5940, 74HC595) might
+                    // be powered from the PC power supply directly rather than from our
+                    // USB power, so they might be powered off even when we're still running.
+                    // To ensure cleaner startup when the power comes back on, globally
+                    // disable the outputs.  The global disable signals come from GPIO lines
+                    // that remain powered as long as the KL25Z is powered, so these modes
+                    // will apply smoothly across power state transitions in the external
+                    // hardware.  That is, when the external chips are powered up, they'll
+                    // see the global disable signals as stable voltage inputs immediately,
+                    // which will cause them to suppress any output triggering.  This ensures
+                    // that we don't fire any solenoids or flash any lights spuriously when
+                    // the power first comes on.
+                    if (tlc5940 != 0)
+                        tlc5940->enable(false);
+                    if (hc595 != 0)
+                        hc595->enable(false);
+                }
             }
         }
         
@@ -3335,23 +3502,19 @@
             else if (jsOKTimer.read() > 5)
             {
                 // USB freeze - show red/yellow.
-                //  Our outgoing joystick messages aren't going through, even though we
+                // Our outgoing joystick messages aren't going through, even though we
                 // think we're still connected.  This indicates that one or more of our
                 // USB endpoints have stopped working, which can happen as a result of
                 // bugs in the USB HAL or latency responding to a USB IRQ.  Show a
                 // distinctive diagnostic flash to signal the error.  I haven't found a 
                 // way to recover from this class of error other than rebooting the MCU, 
-                // so the goal is to fix the HAL so that this error never happens.  This
-                // flash pattern is thus for debugging purposes only; hopefully it won't
-                // ever occur in a real installation.
-                static bool dumped;
-                if (!dumped) {
-                    // If we haven't already, dump the USB HAL status to the debug console,
-                    // in case it helps identify the reason for the endpoint failure.
-                    extern void USBDeviceStatusDump(void);
-                    USBDeviceStatusDump();
-                    dumped = true;
-                }
+                // so the goal is to fix the HAL so that this error never happens.  
+                //
+                // NOTE!  This diagnostic code *hopefully* shouldn't occur.  It happened
+                // in the past due to a number of bugs in the mbed KL25Z USB HAL that
+                // I've since fixed.  I think I found all of the cases that caused it,
+                // but I'm leaving the diagnostics here in case there are other bugs
+                // still lurking that can trigger the same symptoms.
                 jsOKTimer.stop();
                 hb = !hb;
                 diagLED(1, hb, 0);
--- a/nvm.h	Mon Jan 11 21:08:36 2016 +0000
+++ b/nvm.h	Wed Feb 03 22:57:25 2016 +0000
@@ -18,15 +18,18 @@
 // and calibration data in flash memory.
 //
 // Hack alert!
+//
 // Our use of flash for this purpose is ad hoc and not supported
-// by the mbed platform.  mbed doesn't impose a file system on the
-// KL25Z flash; it simply treats the flash as a raw storage space
-// and assumes that the linker output is the only thing using it.
-// So if we want to use the flash, we basically have to do it on 
-// the sly, by using space that the linker happens to leave unused.
-// Fortunately, it's fairly easy to do this, because the flash
-// is mapped in the obvious way, as a single contiguous block in 
-// the CPU memory space, and the linker does the obvious thing, 
+// by the mbed platform.  mbed doesn't impose a file system (or any
+// other kind of formal structure) on the KL25Z flash; it simply 
+// treats the flash as a raw storage space for linker output and 
+// assumes that the linker is the only thing using it.  So ito use 
+// the flash, we basically have to do it on the sly, by using space 
+// that the linker happens to leave unused.
+// 
+// Fortunately, it's fairly easy to do this, because the flash is
+// mapped in the obvious way, as a single contiguous block in the
+// CPU memory space, and because the linker does the obvious thing, 
 // storing its entire output in a single contiguous block starting
 // at the lowest flash address.  This means that all flash memory
 // from (lowest flash address + length of linker output) to
@@ -44,6 +47,11 @@
 // configuration structure is much much smaller than the available 
 // leftover flash space, so we should be safe indefinitely, barring 
 // a major expansion of the configuration structure or code size.
+// (And if we get to the point where we actually don't have space
+// for our ~1K structure, we'll be up against the limits of the
+// device anyway, so we'd have to rein in our ambitions or write
+// more efficient code for deeper reasons than sharing this tiny
+// sliver of memory.)
 //
 // The boot loader seems to erase the entire flash space every time
 // we load new firmware, so our configuration structure is lost