An I/O controller for virtual pinball machines: accelerometer nudge sensing, analog plunger input, button input encoding, LedWiz compatible output controls, and more.

Dependencies:   mbed FastIO FastPWM USBDevice

Fork of Pinscape_Controller by Mike R

/media/uploads/mjr/pinscape_no_background_small_L7Miwr6.jpg

This is Version 2 of the Pinscape Controller, an I/O controller for virtual pinball machines. (You can find the old version 1 software here.) Pinscape is software for the KL25Z that turns the board into a full-featured I/O controller for virtual pinball, with support for accelerometer-based nudging, a mechanical plunger, button inputs, and feedback device control.

In case you haven't heard of the idea before, a "virtual pinball machine" is basically a video pinball simulator that's built into a real pinball machine body. A TV monitor goes in place of the pinball playfield, and a second TV goes in the backbox to show the backglass artwork. Some cabs also include a third monitor to simulate the DMD (Dot Matrix Display) used for scoring on 1990s machines, or even an original plasma DMD. A computer (usually a Windows PC) is hidden inside the cabinet, running pinball emulation software that displays a life-sized playfield on the main TV. The cabinet has all of the usual buttons, too, so it not only looks like the real thing, but plays like it too. That's a picture of my own machine to the right. On the outside, it's built exactly like a real arcade pinball machine, with the same overall dimensions and all of the standard pinball cabinet trim hardware.

It's possible to buy a pre-built virtual pinball machine, but it also makes a great DIY project. If you have some basic wood-working skills and know your way around PCs, you can build one from scratch. The computer part is just an ordinary Windows PC, and all of the pinball emulation can be built out of free, open-source software. In that spirit, the Pinscape Controller is an open-source software/hardware project that offers a no-compromises, all-in-one control center for all of the unique input/output needs of a virtual pinball cabinet. If you've been thinking about building one of these, but you're not sure how to connect a plunger, flipper buttons, lights, nudge sensor, and whatever else you can think of, this project might be just what you're looking for.

You can find much more information about DIY Pin Cab building in general in the Virtual Cabinet Forum on vpforums.org. Also visit my Pinscape Resources page for more about this project and other virtual pinball projects I'm working on.

Downloads

  • Pinscape Release Builds: This page has download links for all of the Pinscape software. To get started, install and run the Pinscape Config Tool on your Windows computer. It will lead you through the steps for installing the Pinscape firmware on the KL25Z.
  • Config Tool Source Code. The complete C# source code for the config tool. You don't need this to run the tool, but it's available if you want to customize anything or see how it works inside.

Documentation

The new Version 2 Build Guide is now complete! This new version aims to be a complete guide to building a virtual pinball machine, including not only the Pinscape elements but all of the basics, from sourcing parts to building all of the hardware.

You can also refer to the original Hardware Build Guide (PDF), but that's out of date now, since it refers to the old version 1 software, which was rather different (especially when it comes to configuration).

System Requirements

The new Config Tool requires a fairly up-to-date Microsoft .NET installation. If you use Windows Update to keep your system current, you should be fine. A modern version of Internet Explorer (IE) is required, even if you don't use it as your main browser, because the Config Tool uses some system components that Microsoft packages into the IE install set. I test with IE11, so that's known to work. IE8 doesn't work. IE9 and 10 are unknown at this point.

The Windows requirements are only for the config tool. The firmware doesn't care about anything on the Windows side, so if you can make do without the config tool, you can use almost any Windows setup.

Main Features

Plunger: The Pinscape Controller started out as a "mechanical plunger" controller: a device for attaching a real pinball plunger to the video game software so that you could launch the ball the natural way. This is still, of course, a central feature of the project. The software supports several types of sensors: a high-resolution optical sensor (which works by essentially taking pictures of the plunger as it moves); a slide potentiometer (which determines the position via the changing electrical resistance in the pot); a quadrature sensor (which counts bars printed on a special guide rail that it moves along); and an IR distance sensor (which determines the position by sending pulses of light at the plunger and measuring the round-trip travel time). The Build Guide explains how to set up each type of sensor.

Nudging: The KL25Z (the little microcontroller that the software runs on) has a built-in accelerometer. The Pinscape software uses it to sense when you nudge the cabinet, and feeds the acceleration data to the pinball software on the PC. This turns physical nudges into virtual English on the ball. The accelerometer is quite sensitive and accurate, so we can measure the difference between little bumps and hard shoves, and everything in between. The result is natural and immersive.

Buttons: You can wire real pinball buttons to the KL25Z, and the software will translate the buttons into PC input. You have the option to map each button to a keyboard key or joystick button. You can wire up your flipper buttons, Magna Save buttons, Start button, coin slots, operator buttons, and whatever else you need.

Feedback devices: You can also attach "feedback devices" to the KL25Z. Feedback devices are things that create tactile, sound, and lighting effects in sync with the game action. The most popular PC pinball emulators know how to address a wide variety of these devices, and know how to match them to on-screen action in each virtual table. You just need an I/O controller that translates commands from the PC into electrical signals that turn the devices on and off. The Pinscape Controller can do that for you.

Expansion Boards

There are two main ways to run the Pinscape Controller: standalone, or using the "expansion boards".

In the basic standalone setup, you just need the KL25Z, plus whatever buttons, sensors, and feedback devices you want to attach to it. This mode lets you take advantage of everything the software can do, but for some features, you'll have to build some ad hoc external circuitry to interface external devices with the KL25Z. The Build Guide has detailed plans for exactly what you need to build.

The other option is the Pinscape Expansion Boards. The expansion boards are a companion project, which is also totally free and open-source, that provides Printed Circuit Board (PCB) layouts that are designed specifically to work with the Pinscape software. The PCB designs are in the widely used EAGLE format, which many PCB manufacturers can turn directly into physical boards for you. The expansion boards organize all of the external connections more neatly than on the standalone KL25Z, and they add all of the interface circuitry needed for all of the advanced software functions. The big thing they bring to the table is lots of high-power outputs. The boards provide a modular system that lets you add boards to add more outputs. If you opt for the basic core setup, you'll have enough outputs for all of the toys in a really well-equipped cabinet. If your ambitions go beyond merely well-equipped and run to the ridiculously extravagant, just add an extra board or two. The modular design also means that you can add to the system over time.

Expansion Board project page

Update notes

If you have a Pinscape V1 setup already installed, you should be able to switch to the new version pretty seamlessly. There are just a couple of things to be aware of.

First, the "configuration" procedure is completely different in the new version. Way better and way easier, but it's not what you're used to from V1. In V1, you had to edit the project source code and compile your own custom version of the program. No more! With V2, you simply install the standard, pre-compiled .bin file, and select options using the Pinscape Config Tool on Windows.

Second, if you're using the TSL1410R optical sensor for your plunger, there's a chance you'll need to boost your light source's brightness a little bit. The "shutter speed" is faster in this version, which means that it doesn't spend as much time collecting light per frame as before. The software actually does "auto exposure" adaptation on every frame, so the increased shutter speed really shouldn't bother it, but it does require a certain minimum level of contrast, which requires a certain minimal level of lighting. Check the plunger viewer in the setup tool if you have any problems; if the image looks totally dark, try increasing the light level to see if that helps.

New Features

V2 has numerous new features. Here are some of the highlights...

Dynamic configuration: as explained above, configuration is now handled through the Config Tool on Windows. It's no longer necessary to edit the source code or compile your own modified binary.

Improved plunger sensing: the software now reads the TSL1410R optical sensor about 15x faster than it did before. This allows reading the sensor at full resolution (400dpi), about 400 times per second. The faster frame rate makes a big difference in how accurately we can read the plunger position during the fast motion of a release, which allows for more precise position sensing and faster response. The differences aren't dramatic, since the sensing was already pretty good even with the slower V1 scan rate, but you might notice a little better precision in tricky skill shots.

Keyboard keys: button inputs can now be mapped to keyboard keys. The joystick button option is still available as well, of course. Keyboard keys have the advantage of being closer to universal for PC pinball software: some pinball software can be set up to take joystick input, but nearly all PC pinball emulators can take keyboard input, and nearly all of them use the same key mappings.

Local shift button: one physical button can be designed as the local shift button. This works like a Shift button on a keyboard, but with cabinet buttons. It allows each physical button on the cabinet to have two PC keys assigned, one normal and one shifted. Hold down the local shift button, then press another key, and the other key's shifted key mapping is sent to the PC. The shift button can have a regular key mapping of its own as well, so it can do double duty. The shift feature lets you access more functions without cluttering your cabinet with extra buttons. It's especially nice for less frequently used functions like adjusting the volume or activating night mode.

Night mode: the output controller has a new "night mode" option, which lets you turn off all of your noisy devices with a single button, switch, or PC command. You can designate individual ports as noisy or not. Night mode only disables the noisemakers, so you still get the benefit of your flashers, button lights, and other quiet devices. This lets you play late into the night without disturbing your housemates or neighbors.

Gamma correction: you can designate individual output ports for gamma correction. This adjusts the intensity level of an output to make it match the way the human eye perceives brightness, so that fades and color mixes look more natural in lighting devices. You can apply this to individual ports, so that it only affects ports that actually have lights of some kind attached.

IR Remote Control: the controller software can transmit and/or receive IR remote control commands if you attach appropriate parts (an IR LED to send, an IR sensor chip to receive). This can be used to turn on your TV(s) when the system powers on, if they don't turn on automatically, and for any other functions you can think of requiring IR send/receive capabilities. You can assign IR commands to cabinet buttons, so that pressing a button on your cabinet sends a remote control command from the attached IR LED, and you can have the controller generate virtual key presses on your PC in response to received IR commands. If you have the IR sensor attached, the system can use it to learn commands from your existing remotes.

Yet more USB fixes: I've been gradually finding and fixing USB bugs in the mbed library for months now. This version has all of the fixes of the last couple of releases, of course, plus some new ones. It also has a new "last resort" feature, since there always seems to be "just one more" USB bug. The last resort is that you can tell the device to automatically reboot itself if it loses the USB connection and can't restore it within a given time limit.

More Downloads

  • 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 releases, so you don't need my custom builds if you're using 9.9.1 or later and/or VP 10. I don't think there's any reason to use my versions instead of the latest official ones, and in fact I'd encourage you to use the official releases since they're more up to date, but I'm leaving my builds available just in case. In the official versions, look for the checkbox "Enable Nudge Filter" in the Keys preferences dialog. My custom versions don't include that checkbox; they just enable the filter unconditionally.
  • Output circuit shopping list: This is a saved shopping cart at mouser.com with the parts needed to build one copy of the high-power output circuit for the LedWiz emulator feature, for use with the standalone KL25Z (that is, without the expansion boards). The quantities in the cart are for one output channel, so if you want N outputs, simply multiply the quantities by the N, with one exception: you only need one ULN2803 transistor array chip for each eight output circuits. If you're using the expansion boards, you won't need any of this, since the boards provide their own high-power outputs.
  • Cary Owens' optical sensor housing: A 3D-printable design for a housing/mounting bracket for the optical plunger sensor, designed by Cary Owens. This makes it easy to mount the sensor.
  • 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.

Copyright and License

The Pinscape firmware is copyright 2014, 2021 by Michael J Roberts. It's released under an MIT open-source license. See License.

Warning to VirtuaPin Kit Owners

This software isn't designed as a replacement for the VirtuaPin plunger kit's firmware. If you bought the VirtuaPin kit, I recommend that you don't install this software. The KL25Z can only run one firmware program at a time, so if you install the Pinscape firmware on your KL25Z, it will replace and erase your existing VirtuaPin proprietary firmware. If you do this, the only way to restore your VirtuaPin firmware is to physically ship the KL25Z back to VirtuaPin and ask them to re-flash it. They don't allow you to do this at home, and they don't even allow you to back up your firmware, since they want to protect their proprietary software from copying. For all of these reasons, if you want to run the Pinscape software, I strongly recommend that you buy a "blank" retail KL25Z to use with Pinscape. They only cost about $15 and are available at several online retailers, including Amazon, Mouser, and eBay. The blank retail boards don't come with any proprietary firmware pre-installed, so installing Pinscape won't delete anything that you paid extra for.

With those warnings in mind, if you're absolutely sure that you don't mind permanently erasing your VirtuaPin firmware, it is at least possible to use Pinscape as a replacement for the VirtuaPin firmware. Pinscape uses the same button wiring conventions as the VirtuaPin setup, so you can keep your buttons (although you'll have to update the GPIO pin mappings in the Config Tool to match your physical wiring). As of the June, 2021 firmware, the Vishay VCNL4010 plunger sensor that comes with the VirtuaPin v3 plunger kit is supported, so you can also keep your plunger, if you have that chip. (You should check to be sure that's the sensor chip you have before committing to this route, if keeping the plunger sensor is important to you. The older VirtuaPin plunger kits came with different IR sensors that the Pinscape software doesn't handle.)

Revision:
101:755f44622abc
Parent:
100:1ff35c07217c
Child:
104:6e06e0f4b476
--- a/TSL14xx/TSL14xx.h	Thu Nov 28 23:18:23 2019 +0000
+++ b/TSL14xx/TSL14xx.h	Fri Nov 29 05:38:07 2019 +0000
@@ -28,6 +28,8 @@
  *  which add the image processing that analyzes the image data to 
  *  determine the plunger position.)
  *
+ *  *** Double buffering ***
+ *
  *  Our API is based on a double-buffered asynchronous read.  The caller
  *  can access a completed buffer, containing the pixels from the last image 
  *  frame, while the sensor is transferring data asynchronously (using the 
@@ -35,56 +37,46 @@
  *  new read is started, we swap buffers, making the last completed buffer 
  *  available to the client and handing the other buffer to the DMA
  *  controller to fill asynchronously.
- *  
- *  The photodiodes in these sensors gather light very rapidly, allowing
- *  for extremely short exposure times.  The "shutter" is electronic;
- *  a signal on the pulse input resets the pixels and begins an integration
- *  period, and a subsequent signal ends the integration and transfers the
- *  pixel voltages to the hold capacitors.  Minimum exposure times are less
- *  than a millisecond.  The actual timing is under software control, since
- *  we determine the start and end of the integration period via the pulse
- *  input.  Longer integration periods gather more light, like a longer
- *  exposure on a conventional camera.  For our purposes in the Pinscape
- *  Controller, we want the highest possible frame rate, as we're trying to 
- *  capture the motion of a fast-moving object (the plunger).  The KL25Z 
- *  can't actually keep up with shortest integration time the sensor can 
- *  achieve - the limiting factor is the KL25Z ADC, which needs at least
- *  2.5us to collect each sample.  The sensor transfers pixels to the MCU 
- *  serially, and each pixel is transferred as an analog voltage level, so 
- *  we have to collect one ADC sample per pixel.  Our maximum frame rate 
- *  is therefore determined by the product of the minimum ADC sample time 
- *  and the number of pixels.  
+ *
+ *  In a way, there are actually THREE frames in our pipeline at any given
+ *  time:
+ *
+ *   - a live image integrating light on the photo receptors on the sensor
+ *   - the prior image, held in the sensor's shift register and being 
+ *     transferred via DMA into one of our buffers (the "DMA" buffer)
+ *   - the second prior image, in our other buffer (the "stable" buffer),
+ *     available for the client to process
+ *
+ *  The integration process on the sensor starts when we begin the transfer
+ *  of an image via DMA.  That frame's integration period ends when the next 
+ *  transfer starts.  So the minimum integration time is also the DMA pixel
+ *  transfer time.  Longer integration times can be achieved by waiting
+ *  for an additional interval after a DMA transfer finishes, before starting
+ *  the next transfer.  We make provision for this added time to allow for
+ *  longer exposure times to optimize image quality.
+ *
  *
- *  The fastest operating mode for the KL25Z ADC is its "continuous"
- *  mode, where it automatically starts taking a new sample every time
- *  it completes the previous one.  The fastest way to transfer the
- *  samples to memory in this mode is via the hardware DMA controller.
- *  
- *  It takes a pretty tricky setup to make this work.  I don't like tricky 
- *  setups - I prefer something easy to understand - but in this case it's
- *  justified because of the importance in this application of maximizing 
- *  the frame rate.  I'm pretty sure there's no other way to even get close 
- *  to the rate we can achieve with the continuous ADC/DMA combination.
- *  The ADC/DMA mode gives us pixel read times of about 2us, vs a minimum 
- *  of about 14us for the next best method I've found.  Using this mode, we 
- *  can read the TSL1410R's 1280 pixels at full resolution in about 2.5ms.  
- *  That's a frame rate of 400 frames per second, which is fast enough to 
- *  capture a fast-moving plunger with minimal motion blur.
+ *  *** Optimizing pixel transfer speed ***
  *
- *  Note that some of the sensors in this series (TSL1410R, TSL1412S) have
- *  a "parallel" readout mode that lets them physically deliver two pixels
- *  at once the MCU, via separate physical connections.  This could provide 
- *  a 2X speedup on an MCU equipped with two independent ADC samplers.  
- *  Unfortunately, the KL25Z is not so equipped; even though it might appear
- *  at first glance to support multiple ADC "channels", all of the channels
- *  internally connect to a single ADC sampler, so the hardware can ultimately
- *  perform only one conversion at a time.  Paradoxically, using the sensor's
- *  parallel mode is actually *slower* with a KL25Z than using its serial
- *  mode, because we can only maintain the higher throughput of the KL25Z
- *  ADC's "continuous sampling mode" by reading all samples thorugh a single
- *  channel.
+ *  For Pinscape purposes, we want the fastest possible frame rate, as we're
+ *  trying to accurately capture the motion of a fast-moving object (the 
+ *  plunger).  The TSL14xx sensors can achieve a frame rate up to about
+ *  1000 frames per second, if everything is clocked at the limits in the
+ *  data sheet.  The KL25Z, however, can't achieve that fast a rate.  The
+ *  limiting factor is the KL25Z's ADC.  We have to take an ADC sample for
+ *  every pixel, and the minimum sampling time for the ADC on the KL25Z is
+ *  about 2us.  With the 1280-pixel TSL1410R, that gives us a minimum
+ *  pixel transfer time of about 2.6ms.  And it's actually very difficult
+ *  to achieve that speed - my original, naive implementation took more
+ *  like 30ms (!!!) to transfer each frame.
  *
- *  Here's the tricky approach we use:
+ *  As a rule, I don't like tricky code, because it's hard to understand
+ *  and hard to debug.  But in this case it's justified.  For good plunger
+ *  tracking, it's critical to achieve a minimum frame rate of around 200 
+ *  fps (5ms per frame).  I'm pretty sure there's no way to even get close 
+ *  to this rate without the complex setup described below.
+ *
+ *  Here's our approach for fast data transfer:
  * 
  *  First, we put the analog input port (the ADC == Analog-to-Digital 
  *  Converter) in "continuous" mode, at the highest clock speed we can 
@@ -211,6 +203,22 @@
  *  (the TLC5940 PWM controller interface), and it only needs one
  *  channel.  So the KL25Z's complement of four DMA channels is just
  *  enough for all of our needs for the moment.)
+ *
+ *  Note that some of the sensors in this series (TSL1410R, TSL1412S)
+ *  have a "parallel" readout mode that lets them physically deliver 
+ *  two pixels at once the MCU, via separate physical connections.  This 
+ *  could provide a 2X speedup on an MCU equipped with two independent 
+ *  ADC samplers.  Unfortunately, the KL25Z is not so equipped; even 
+ *  though it might appear at first glance to support multiple ADC 
+ *  "channels", all of the channels internally multiplex into a single 
+ *  converter unit, so the hardware can ultimately perform only one 
+ *  conversion at a time.  Paradoxically, using the sensor's parallel 
+ *  mode is actually *slower* with a KL25Z than using its serial mode,
+ *  because we can only maintain the higher throughput of the KL25Z ADC's
+ *  continuous sampling mode by reading all samples thorugh a single
+ *  channel.  Switching channels on alternating samples involves a
+ *  bunch of setup overhead within the ADC hardware that adds lots of
+ *  clocks compared to single-channel continuous mode.
  */
  
 #include "mbed.h"
@@ -277,13 +285,18 @@
         // start the sample timer with an arbitrary zero point of 'now'
         t.start();
         
+        // start with no minimum integration time
+        tIntMin = 0;
+        
         // allocate our double pixel buffers
         pix1 = new uint8_t[nPixSensor*2];
         pix2 = pix1 + nPixSensor;
         
         // put the first DMA transfer into the first buffer (pix1)
         pixDMA = 0;
-        running = false;
+        
+        // DMA owns both buffers until the first transfer completes
+        clientOwnsStablePix = true;
 
         // remember the clock pin port base and pin mask for fast access
         clockPort = GPIO_PORT_BASE(clockPin);
@@ -337,6 +350,9 @@
         // clear the timing statistics        
         totalTime = 0.0; 
         nRuns = 0;
+        
+        // start the first transfer
+        startTransfer();
     }
     
     // Get the stable pixel array.  This is the image array from the
@@ -366,7 +382,7 @@
     // until the next transfer after that.
     void waitPix(uint8_t * &pix, uint32_t &t)
     {
-        // wait for the current transfer to finish
+        // wait for stable buffer ownership to transfer to the client
         wait();
         
         // Return the pixel array that IS assigned to DMA, since this
@@ -388,39 +404,62 @@
         }
     }
     
-    // Start an image capture from the sensor.  Waits the previous
-    // capture to finish if it's still running, then starts a new one
-    // and returns immediately.  The new capture proceeds autonomously 
-    // via the DMA hardware, so the caller can continue with other 
-    // processing during the capture.
-    void startCapture(uint32_t minIntTime_us = 0)
+    // Set the requested minimum integration time.  If this is less than the
+    // sensor's physical minimum time, the physical minimum applies.
+    virtual void setMinIntTime(uint32_t us)
     {
-        IF_DIAG(uint32_t tDiag0 = mainLoopTimer.read_us();)
+        tIntMin = us;
+    }
+    
+    // Wait for the stable buffer ownership to transfer to the client
+    void wait() { while (!clientOwnsStablePix) ; }
+    
+    // Is a buffer available?
+    bool ready() const { return clientOwnsStablePix; }
+    
+    // Release the client DMA buffer.  The client must call this when it's
+    // done with the current image frame to release the frame back to the
+    // DMA subsystem, so that it can hand us the next frame.
+    void releasePix() { clientOwnsStablePix = false; }
         
-        // wait for the last current capture to finish
-        while (running) { }
-
-        // we're starting a new capture immediately        
-        running = true;
-
-        // collect timing diagnostics
-        IF_DIAG(mainLoopIterCheckpt[8] += uint32_t(mainLoopTimer.read_us() - tDiag0);)
-        
-        // If the elapsed time since the start of the last integration
-        // hasn't reached the specified minimum yet, wait.  This allows
-        // the caller to control the integration time to optimize the
-        // exposure level.
-        uint32_t dt = uint32_t(t.read_us() - tInt);
-        if (dt < minIntTime_us)
+    // get the timing statistics - sum of scan time for all scans so far 
+    // in microseconds, and total number of scans so far
+    void getTimingStats(uint64_t &totalTime, uint32_t &nRuns) const
+    {
+        totalTime = this->totalTime;
+        nRuns = this->nRuns;
+    }
+    
+    // get the average scan time in microseconds
+    uint32_t getAvgScanTime() const
+    {
+        return uint32_t(totalTime / nRuns);
+    }
+    
+private:
+    // Start a new transfer.  We call this at the end of each integration
+    // cycle, in interrupt mode.  This can be called directly by the interrupt
+    // handler invoked when the DMA transfer completes, or by a timeout.  In
+    // either case, we're in interrupt mode.
+    void startTransfer()
+    {
+        // If we own the stable buffer, swap buffers: hand ownership of the
+        // old DMA buffer to the client, and take control of the old client
+        // buffer (which the client must be done with if we own it) as our
+        // new DMA buffer.
+        //
+        // If the client owns the stable buffer, we can't swap buffers,
+        // because the client is still working on the stable one.  So we
+        // must start the new transfer using the existing DMA buffer.
+        if (!clientOwnsStablePix)
         {
-            // we haven't reached the required minimum yet - wait for the 
-            // remaining interval
-            wait_us(minIntTime_us - dt);
+            // swap buffers
+            pixDMA ^= 1;
+            
+            // release the prior DMA buffer to the client
+            clientOwnsStablePix = true;
         }
         
-        // swap to the other DMA buffer for reading the new pixel samples
-        pixDMA ^= 1;
-        
         // Set up the active pixel array as the destination buffer for 
         // the ADC DMA channel. 
         adc_dma.destination(pixDMA ? pix2 : pix1, true);
@@ -471,24 +510,53 @@
         // setup takes about 2us, so clocking 19 pixels takes about 38us.
         // In addition, the ADC takes about 4us extra for the first read.
         tInt = t.read_us() + 19*2 + 4;
-        
-        IF_DIAG(mainLoopIterCheckpt[9] += uint32_t(mainLoopTimer.read_us() - tDiag0);)
     }
     
-    // Wait for the current capture to finish
-    void wait()
+    // End of transfer notification.  This is called as an interrupt
+    // handler when the DMA transfer completes.
+    void transferDone()
     {
-        while (running) { }
+        // stop the ADC sampler
+        ao.stop();
+            
+        // clock out one extra pixel to leave the analog out pin on
+        // the sensor in the high-Z state
+        clock = 1;
+        clock = 0;
+        
+        // add this sample to the timing statistics (for diagnostics and
+        // performance measurement)
+        uint32_t now = t.read_us();
+        totalTime += uint32_t(now - t0);
+        nRuns += 1;
+        
+        // note the ending time of the transfer
+        tDone = now;
+        
+        // Figure the time remaining to reach the minimum requested 
+        // integration time for the next cycle.  The sensor is currently
+        // working on an integration cycle that started at tInt, and that
+        // cycle will end when we start the next cycle.  We therefore want
+        // to wait to start the next cycle until we've reached the desired
+        // total integration time.
+        uint32_t dt = now - tInt;
+        if (dt < tIntMin)
+        {
+            // more time is required - set a timeout for the remaining inteval
+            integrationTimeout.attach_us(this, &TSL14xx::startTransfer, tIntMin - dt);
+        }
+        else
+        {
+            // we've already reached the minimum integration time - start
+            // the next transfer immediately
+            startTransfer();
+        }
     }
-    
-    // Is the latest reading ready?
-    bool ready() const { return !running; }
-    
-    // Is a DMA transfer in progress?
-    bool dmaBusy() const { return running; }
-        
-    // Clock through all pixels to clear the array.  Pulses SI at the
-    // beginning of the operation, which starts a new integration cycle.
+
+    // Clear the sensor shift register.  Clocks in all of the pixels from
+    // the sensor without bothering to read them on the ADC.  Pulses SI 
+    // at the beginning of the operation, which starts a new integration 
+    // cycle.
     void clear()
     {
         // get the clock toggle register
@@ -527,45 +595,7 @@
             *ptor = clockMask;
         }
     }
-    
-    // get the timing statistics - sum of scan time for all scans so far 
-    // in microseconds, and total number of scans so far
-    void getTimingStats(uint64_t &totalTime, uint32_t &nRuns) const
-    {
-        totalTime = this->totalTime;
-        nRuns = this->nRuns;
-    }
-    
-    // get the average scan time in microseconds
-    uint32_t getAvgScanTime() const
-    {
-        return uint32_t(totalTime / nRuns);
-    }
-
-private:
-    // end of transfer notification
-    void transferDone()
-    {
-        // stop the ADC sampler
-        ao.stop();
-            
-        // clock out one extra pixel to leave A1 in the high-Z state
-        clock = 1;
-        clock = 0;
         
-        // add this sample to the timing statistics (for diagnostics and
-        // performance measurement)
-        uint32_t now = t.read_us();
-        totalTime += uint32_t(now - t0);
-        nRuns += 1;
-        
-        // the sampler is no long running
-        running = false;
-        
-        // note the ending time of the transfer
-        tDone = now;
-    }
-    
     // DMA controller interfaces
     SimpleDMA adc_dma;        // DMA channel for reading the analog input
     SimpleDMA clkUp_dma;      // "Clock Up" channel
@@ -597,9 +627,53 @@
     // data from the last transfer.
     uint8_t pixDMA;
     
-    // flag: sample is running
-    volatile bool running;
-
+    // Stable buffer ownership.  At any given time, the DMA subsystem owns
+    // the buffer specified by pixDMA.  The other buffer - the "stable" buffer,
+    // which contains the most recent completed frame, can be owned by EITHER
+    // the client or by the DMA subsystem.  Each time a DMA transfer completes,
+    // the DMA subsystem looks at the stable buffer owner flag to determine 
+    // what to do:
+    //
+    // - If the DMA subsystem owns the stable buffer, it swaps buffers.  This
+    //   makes the newly completed DMA buffer the new stable buffer, and makes
+    //   the old stable buffer the new DMA buffer.  At this time, the DMA 
+    //   subsystem also changes the stable buffer ownership to CLIENT.
+    //
+    // - If the CLIENT owns the stable buffer, the DMA subsystem can't swap
+    //   buffers, because the client is still using the stable buffer.  It
+    //   simply leaves things as they are.
+    //
+    // In either case, the DMA system starts a new transfer at this point.
+    //
+    // The client, meanwhile, is free to access the stable buffer when it has
+    // ownership.  If the client *doesn't* have ownership, it must wait for
+    // the ownership to be transferred, which can only be done by the DMA
+    // subsystem on completing a transfer.
+    //
+    // When the client is done with the stable buffer, it transfers ownership
+    // back to the DMA subsystem.
+    //
+    // Transfers of ownership from DMA to CLIENT are done only by DMA.
+    // Transfers from CLIENT to DMA are done only by CLIENT.  So whoever has
+    // ownership now is responsible for transferring ownership.
+    //
+    volatile bool clientOwnsStablePix;
+    
+    // End-of-integration timeout handler.  This lets us fire an interrupt
+    // when the current integration cycle is done, so that we can start the
+    // next cycle.
+    Timeout integrationTimeout;
+    
+    // Requested minimum integration time, in micoseconds.  The client can use 
+    // this to control the exposure level, by increasing it for a longer
+    // exposure and thus more light-gathering in low-light conditions.  Note 
+    // that the physical limit on the minimum integration time is roughly equal 
+    // to the pixel file transfer time, because the integration cycle is
+    // initiated and ended by transfer starts.  It's thus impossible to make
+    // the integration time less than the time for one full pixel file 
+    // transfer.
+    uint32_t tIntMin;
+    
     // timing statistics
     Timer t;                  // sample timer
     uint32_t t0;              // start time (us) of current sample