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.)

Files at this revision

API Documentation at this revision

Comitter:
mjr
Date:
Mon Feb 15 20:30:32 2016 +0000
Parent:
44:b5ac89b9cd5d
Child:
47:df7a88cd249c
Commit message:
More work in progress on CCD speedups;

Changed in this revision

AltAnalogIn/AltAnalogIn.h Show annotated file Show diff for this revision Revisions of this file
AltAnalogIn/AltAnalogIn_KL25Z.cpp Show annotated file Show diff for this revision Revisions of this file
SimpleDMA.lib Show diff for this revision Revisions of this file
SimpleDMA/SimpleDMA.h Show annotated file Show diff for this revision Revisions of this file
SimpleDMA/SimpleDMA_KL25.h Show annotated file Show diff for this revision Revisions of this file
SimpleDMA/SimpleDMA_KL25_46.cpp Show annotated file Show diff for this revision Revisions of this file
SimpleDMA/SimpleDMA_KL46.h Show annotated file Show diff for this revision Revisions of this file
SimpleDMA/SimpleDMA_LPC1768.cpp Show annotated file Show diff for this revision Revisions of this file
SimpleDMA/SimpleDMA_LPC1768.h Show annotated file Show diff for this revision Revisions of this file
SimpleDMA/SimpleDMA_common.cpp 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
TSL1410R/tsl1410r_dma.cpp Show annotated file Show diff for this revision Revisions of this file
TSL1410R/tsl1410r_orig.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
main.cpp Show annotated file Show diff for this revision Revisions of this file
plunger.h Show annotated file Show diff for this revision Revisions of this file
--- a/AltAnalogIn/AltAnalogIn.h	Sun Feb 07 03:07:11 2016 +0000
+++ b/AltAnalogIn/AltAnalogIn.h	Mon Feb 15 20:30:32 2016 +0000
@@ -23,65 +23,64 @@
  */
 #include "mbed.h"
 #include "pinmap.h"
+#include "SimpleDMA.h"
+
+// KL25Z definitions
+#if defined TARGET_KLXX
+
+// Maximum ADC clock for KL25Z in 12-bit mode - 18 MHz per the data sheet
+#define MAX_FADC_12BIT      18000000
+
+#define CHANNELS_A_SHIFT     5          // bit position in ADC channel number of A/B mux
+#define ADC_CFG1_ADLSMP      0x10       // long sample time mode
+#define ADC_SC1_AIEN         0x40       // interrupt enable
+#define ADC_SC2_ADLSTS(mode) (mode)     // long sample time select - bits 1:0 of CFG2
+#define ADC_SC2_DMAEN        0x04       // DMA enable
+#define ADC_SC3_CONTINUOUS   0x08       // continuous conversion mode
+
+#else
+    #error "This target is not currently supported"
+#endif
 
 #if !defined TARGET_LPC1768 && !defined TARGET_KLXX && !defined TARGET_LPC408X && !defined TARGET_LPC11UXX && !defined TARGET_K20D5M
     #error "Target not supported"
 #endif
 
- /** A class similar to AnalogIn, only faster, for LPC1768, LPC408X and KLxx
- *
- * AnalogIn does a single conversion when you read a value (actually several conversions and it takes the median of that).
- * This library runns the ADC conversion automatically in the background.
- * When read is called, it immediatly returns the last sampled value.
- *
- * LPC1768 / LPC4088
- * Using more ADC pins in continuous mode will decrease the conversion rate (LPC1768:200kHz/LPC4088:400kHz).
- * If you need to sample one pin very fast and sometimes also need to do AD conversions on another pin,
- * you can disable the continuous conversion on that ADC channel and still read its value.
+ /** A class similar to AnalogIn, but much faster.  This class is optimized 
+ * for taking a string of readings from a single input.
  *
- * KLXX
- * Multiple Fast instances can be declared of which only ONE can be continuous (all others must be non-continuous).
- *
- * When continuous conversion is disabled, a read will block until the conversion is complete
- * (much like the regular AnalogIn library does).
- * Each ADC channel can be enabled/disabled separately.
- *
- * IMPORTANT : It does not play nicely with regular AnalogIn objects, so either use this library or AnalogIn, not both at the same time!!
- *
- * Example for the KLxx processors:
- * @code
- * // Print messages when the AnalogIn is greater than 50%
- *
- * #include "mbed.h"
+ * This is a heavily modified version of the popular FastAnalogIn class.
+ * Like FastAnalogIn, this class uses the continuous conversion mode to
+ * achieve faster read times.  It adds interrupt callbacks on each
+ * conversion, and DMA transfer of the input data to memory (or to another
+ * peripheral) using the SimpleDMA class.  DMA makes a huge difference -
+ * it speeds up the sampling time by about 3x and gets us fairly close to
+ * the speeds claimed by the manufacturer.  Reading through the MCU code
+ * seems to add at least a few microseconds per sample, which is significant
+ * when trying to get close to the theoretical speed limits for the ADC
+ * hardware, which are around 1.5us.
  *
- * AltAnalogIn temperature(PTC2); //Fast continuous sampling on PTC2
- * AltAnalogIn speed(PTB3, 0);    //Fast non-continuous sampling on PTB3
+ * This class can be used with or without DMA.  By default, you take samples
+ * directly.  Call start() to initiate sampling, and call one of the
+ * read routines (read() or read_u16()) to wait for the sample to complete
+ * and fetch the value.  In this mode, samples are taken individually.
+ * The start() and read routines are separated so that the caller can
+ * perform other work, if desired, while the ADC hardware takes the sample.
  *
- * int main() {
- *     while(1) {
- *         if(temperature > 0.5) {
- *             printf("Too hot! (%f) at speed %f", temperature.read(), speed.read());
- *         }
- *     }
- * }
- * @endcode
- * Example for the LPC1768 processor:
- * @code
- * // Print messages when the AnalogIn is greater than 50%
+ * To use with DMA, set up a SimpleDMA object, and call initDMA() to tie
+ * it to the analog input.  Call startDMA() to initiate a transfer.  We'll
+ * start reading the analog input in continuous mode; each time a sample
+ * completes, it will trigger a DMA transfer to the destination.  startDMA()
+ * returns immediately, so the caller can continue with other tasks while
+ * the samples are taken.
  *
- * #include "mbed.h"
- *
- * AltAnalogIn temperature(p20);
- *
- * int main() {
- *     while(1) {
- *         if(temperature > 0.5) {
- *             printf("Too hot! (%f)", temperature.read());
- *         }
- *     }
- * }
- * @endcode
-*/
+ * IMPORTANT!  This class does not play nicely with regular AnalogIn objects,
+ * nor with the original FastAnalogIn, because all of these classes set global
+ * configuration registers in the ADC hardware at setup time and then will 
+ * assume that no one else is messing with them.  Each library requires
+ * exclusive access to and control over the hardware, so they can't be mixed
+ * in the same program.
+ */
 class AltAnalogIn {
 
 public:
@@ -90,12 +89,70 @@
      * @param pin AnalogIn pin to connect to
      * @param enabled Enable the ADC channel (default = true)
      */
-    AltAnalogIn( PinName pin, bool enabled = true );
+    AltAnalogIn(PinName pin, bool continuous = false);
     
     ~AltAnalogIn( void )
     {
+#if 0//$$$
+        if (intInstance == this)
+            intInstance = 0;
+#endif
     }
     
+    // Initialize DMA.  This connects the analog in port to the
+    // given DMA object.
+    //
+    // DMA transfers from the analog in port often use continuous
+    // conversion mode.  Note, however, that we don't automatically
+    // assume this - single sample mode is the default, which means
+    // that you must manually start each sample.  If you want to use
+    // continuous mode, you need to set that separately (via the 
+    // constructor).
+    void initDMA(SimpleDMA *dma);
+    
+    // Start a DMA transfer.  'nele' is the number of elements (not
+    // bytes) in the buffer.
+    template<typename T> void startDMA(T *buf, int nele, bool autoInc) 
+    {
+        // set the DMA destination buffer
+        dma->destination(buf, autoInc);
+        
+        // start the DMA transfer
+        dma->start(nele * sizeof(T));
+    }
+            
+#if 0 // $$$
+    // set up an interrupt callback and enable interrupt mode
+    template<typename T> void attach(T *object, void (T::*member)(void))
+    {
+        // attach the callback
+        _callback.attach(object, member);
+        
+        // set our internal interrupt handler
+        NVIC_SetVector(ADC0_IRQn, (uint32_t)&_aiIRQ);
+        NVIC_EnableIRQ(ADC0_IRQn);
+        
+        // enable interrupt mode
+        enableInterruptMode();
+    }
+#endif
+
+    // turn on interrupt mode
+    void enableInterruptMode()
+    {
+        // set interrupt mode
+        sc1 |= ADC_SC1_AIEN;        
+    }
+
+#if 0 // $$$    
+    // interrupt handler
+    static void _aiIRQ()
+    {
+        if (intInstance != 0)
+            intInstance->_callback.call();
+    }
+#endif
+    
     /** Start a sample.  This sets the ADC multiplexer to read from
     * this input and activates the sampler.
     */
@@ -115,11 +172,37 @@
                 ADC0->CFG2 &= ~ADC_CFG2_MUXSEL_MASK;
         }
         
-        // select our ADC channel in the control register - this initiates sampling
-        // on the channel
-        ADC0->SC1[0] = startMask;
+        // update the SC2 and SC3 bits only if we're changing inputs
+        static uint32_t lastid = 0;
+        if (id != lastid) 
+        {
+            // set our ADC0 SC2 and SC3 configuration bits
+            ADC0->SC2 = sc2;
+            ADC0->SC3 = sc3;
+        
+            // we're the active one now
+            lastid = id;
+            
+            // handle any interrupts through this object
+//$$$            intInstance = this;
+        }
+        
+        // set our SC1 bits - this initiates the sample
+        ADC0->SC1[0] = sc1;
     }
  
+    // stop sampling
+    void stop()
+    {
+        // set the channel bits to binary 11111 to disable sampling
+        ADC0->SC1[0] = 0x1F;
+    }
+    
+    // wait for the current sample to complete
+    inline void wait()
+    {
+        while ((ADC0->SC1[0] & ADC_SC1_COCO_MASK) == 0);
+    }
 
     
     /** Returns the raw value
@@ -129,7 +212,7 @@
     inline uint16_t read_u16()
     {
         // wait for the hardware to signal that the sample is completed
-        while ((ADC0->SC1[0] & ADC_SC1_COCO_MASK) == 0);
+        wait();
     
         // return the result register value
         return (uint16_t)ADC0->R[0] << 4;  // convert 12-bit to 16-bit, padding with zeroes
@@ -151,9 +234,17 @@
 
     
 private:
-    char ADCnumber;         // ADC number of our input pin
-    char ADCmux;            // multiplexer for our input pin (0=A, 1=B)
-    uint32_t startMask;
+    uint32_t id;                // unique ID
+    SimpleDMA *dma;             // DMA controller, if used
+    FunctionPointer _callback;  // interrupt callback
+    char ADCnumber;             // ADC number of our input pin
+    char ADCmux;                // multiplexer for our input pin (0=A, 1=B)
+    uint32_t sc1;               // SC1 register settings for this input
+    uint32_t sc2;               // SC2 register settings for this input
+    uint32_t sc3;               // SC3 register settings for this input
+    
+    // interrupt handler instance
+    //$$$static AltAnalogIn *intInstance;
 };
 
 #endif
--- a/AltAnalogIn/AltAnalogIn_KL25Z.cpp	Sun Feb 07 03:07:11 2016 +0000
+++ b/AltAnalogIn/AltAnalogIn_KL25Z.cpp	Mon Feb 15 20:30:32 2016 +0000
@@ -3,17 +3,7 @@
 #include "AltAnalogIn.h"
 #include "clk_freqs.h"
 
-// Maximum ADC clock for KL25Z in 12-bit mode.  The data sheet says this is
-// limited to 18MHz, but we seem to get good results at higher rates.  The
-// data sheet is actually slightly vague on this because it's only in the
-// table for the 16-bit ADC, even though the ADC we're using is a 12-bit ADC,
-// which seems to have slightly different properties.  So there's room to
-// think the data sheet omits the data for the 12-bit ADC.
-#define MAX_FADC_12BIT      25000000
-
-#define CHANNELS_A_SHIFT     5          // bit position in ADC channel number of A/B mux
-#define ADC_CFG1_ADLSMP      0x10       // long sample time mode
-#define ADC_SC2_ADLSTS(mode) (mode)     // long sample time select - bits 1:0 of CFG2
+//$$$AltAnalogIn *AltAnalogIn::intInstance = 0;
 
 #ifdef TARGET_K20D50M
 static const PinMap PinMap_ADC[] = {
@@ -31,8 +21,15 @@
 };
 #endif
 
-AltAnalogIn::AltAnalogIn(PinName pin, bool enabled)
+AltAnalogIn::AltAnalogIn(PinName pin, bool continuous)
 {
+    // set our unique ID
+    static uint32_t nextID = 1;
+    id = nextID++;
+    
+    // presume no DMA 
+    dma = 0;
+    
     // do nothing if explicitly not connected
     if (pin == NC)
         return;
@@ -57,38 +54,72 @@
     // run the ADC at up to 18 MHz per the KL25Z data sheet.  (16-bit mode
     // is limited to 12 MHz.)
     int clkdiv = 0;
-    uint32_t ourfreq = bus_frequency();
-    for ( ; ourfreq > MAX_FADC_12BIT ; ourfreq /= 2, clkdiv += 1) ;
+    uint32_t adcfreq = bus_frequency();
+    for ( ; adcfreq > MAX_FADC_12BIT ; adcfreq /= 2, clkdiv += 1) ;
     
-    // Set the "high speed" configuration only if we're right at the bus speed
-    // limit.  This bit is somewhat confusingly named, in that it actually
-    // *slows down* the conversions.  "High speed" means that the *other*
-    // options are set right at the limits of the ADC, so this option adds
-    // a few extra cycle delays to every conversion to compensate for living
-    // on the edge.
-    uint32_t adhsc_bit = (ourfreq == MAX_FADC_12BIT ? ADC_CFG2_ADHSC_MASK : 0);
+    // The "high speed configuration" bit is required if the ADC clock 
+    // frequency is above a certain threshold.  The actual threshold is 
+    // poorly documented: the reference manual only says that it's required
+    // when running the ADC at "high speed" but doesn't define how high
+    // "high" is.  The only numerical figure I can find is in the Freescale
+    // ADC sample time calculator tool (a Windows program downloadable from
+    // the Freescale site), which has a little notation on the checkbox for
+    // the ADHSC bit that says to use it when the ADC clock is 8 MHz or
+    // higher.
+    //
+    // Note that this bit is somewhat confusingly named.  It doesn't mean
+    // "make the ADC go faster".  It actually means just the opposite.
+    // What it really means is that the external clock is running so fast 
+    // that the ADC has to pad out its sample time slightly to compensate,
+    // by adding a couple of extra clock cycles to each sampling interval.
+    const uint32_t ADHSC_SPEED_LIMIT = 8000000;
+    uint32_t adhsc_bit = (adcfreq >= ADHSC_SPEED_LIMIT ? ADC_CFG2_ADHSC_MASK : 0);
     
-    printf("ADCnumber=%d, cfg2_muxsel=%d, bus freq=%ld, clkdiv=%d\r\n", ADCnumber, ADCmux, bus_frequency(), clkdiv);
+    // $$$
+    printf("ADCnumber=%d, cfg2_muxsel=%d, bus freq=%ld, clkdiv=%d, adc freq=%d, high speed config=%s\r\n", 
+        ADCnumber, ADCmux, bus_frequency(), clkdiv, adcfreq, adhsc_bit ? "Y" : "N");//$$$
 
-    // set up the ADC control registers 
-
+    // map the GPIO pin in the system multiplexer to the ADC
+    pinmap_pinout(pin, PinMap_ADC);
+    
+    // set up the ADC control registers - these are common to all users of this class
+    
     ADC0->CFG1 = ADC_CFG1_ADIV(clkdiv)  // Clock Divide Select (as calculated above)
+               //| ADC_CFG1_ADLSMP        // Long sample time
                | ADC_CFG1_MODE(1)       // Sample precision = 12-bit
                | ADC_CFG1_ADICLK(0);    // Input Clock = bus clock
 
     ADC0->CFG2 = adhsc_bit              // High-Speed Configuration, if needed
-               | ADC_CFG2_ADLSTS(3);    // Long sample time mode 3 -> 6 ADCK cycles total
+               //| ADC_CFG2_ADLSTS(0);    // Long sample time mode 0 -> 24 ADCK cycles total
+               //| ADC_CFG2_ADLSTS(1);    // Long sample time mode 1 -> 16 ADCK cycles total
+               //| ADC_CFG2_ADLSTS(2);    // Long sample time mode 2 -> 10 ADCK cycles total
+               | ADC_CFG2_ADLSTS(3);    // Long sample time mode 2 -> 6 ADCK cycles total
                
-    ADC0->SC2 = ADC_SC2_REFSEL(0);      // Default Voltage Reference
-    
-    ADC0->SC3 = 0;                      // Calibration mode off, single sample, averaging disabled
+    // Figure our SC1 register bits
+    sc1 = ADC_SC1_ADCH(ADCnumber & ~(1 << CHANNELS_A_SHIFT));
 
-    // map the GPIO pin in the system multiplexer to the ADC
-    pinmap_pinout(pin, PinMap_ADC);
-    
-    // figure our 'start' mask - this is the value we write to the SC1A register
-    // to initiate a new sample
-    startMask = ADC_SC1_ADCH(ADCnumber & ~(1 << CHANNELS_A_SHIFT));
+    // figure our SC2 register bits
+    sc2 = ADC_SC2_REFSEL(0);            // Default Voltage Reference
+
+    // Set our SC3 bits.  The defaults (0 bits) are calibration mode off,
+    // single sample, averaging disabled.
+    sc3 = (continuous ? ADC_SC3_CONTINUOUS : 0);    // enable continuous mode if desired
 }
 
+void AltAnalogIn::initDMA(SimpleDMA *dma)
+{
+    // remember the DMA interface object
+    this->dma = dma;
+    
+    // set to read from the ADC result register
+    dma->source(&ADC0->R[0], false, 16);
+    
+    // set to trigger on the ADC
+    dma->trigger(Trigger_ADC0);
+
+    // enable DMA in our SC2 bits
+    sc2 |= ADC_SC2_DMAEN;
+}
+
+
 #endif //defined TARGET_KLXX
--- a/SimpleDMA.lib	Sun Feb 07 03:07:11 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://mbed.org/users/Sissors/code/SimpleDMA/#876f3b55e6f5
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleDMA/SimpleDMA.h	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,210 @@
+#ifndef SIMPLEDMA_H
+#define SIMPLEDMA_H
+
+#ifdef RTOS_H
+#include "rtos.h"
+#endif
+
+#include "mbed.h"
+#include "SimpleDMA_KL25.h"
+#include "SimpleDMA_KL46.h"
+#include "SimpleDMA_LPC1768.h"
+
+
+/**
+* SimpleDMA, DMA made simple! (Okay that was bad)
+*
+* A class to easily make basic DMA operations happen. Not all features
+* of the DMA peripherals are used, but the main ones are: From and to memory
+* and peripherals, either continiously or triggered
+*/
+class SimpleDMA {
+public:
+/**
+* Constructor
+*
+* @param channel - optional parameter which channel should be used, default is automatic channel selection
+*/
+SimpleDMA(int channel = -1);
+
+/**
+* Set the source of the DMA transfer
+*
+* Autoincrement increments the pointer after each transfer. If the source
+* is an array this should be true, if it is a peripheral or a single memory
+* location it should be false.
+*
+* The source can be any pointer to any memory location. Automatically
+* the wordsize is calculated depending on the type, if required you can
+* also override this.
+*
+* @param pointer - pointer to the memory location
+* @param autoinc - should the pointer be incremented by the DMA module
+* @param size - wordsize in bits (optional, generally can be omitted)
+* @return - 0 on success
+*/
+template<typename Type>
+void source(Type* pointer, bool autoinc, int size = sizeof(Type) * 8, int mod = 0) {
+    _source = (uint32_t)pointer;
+    source_inc = autoinc;
+    source_size = size;
+    source_mod = mod;
+}
+
+/**
+* Set the destination of the DMA transfer
+*
+* Autoincrement increments the pointer after each transfer. If the source
+* is an array this should be true, if it is a peripheral or a single memory
+* location it should be false.
+*
+* The destination can be any pointer to any memory location. Automatically
+* the wordsize is calculated depending on the type, if required you can
+* also override this.
+*
+* @param pointer - pointer to the memory location
+* @param autoinc - should the pointer be incremented by the DMA module
+* @param size - wordsize in bits (optional, generally can be omitted)
+* @return - 0 on success
+*/
+template<typename Type>
+void destination(Type* pointer, bool autoinc, int size = sizeof(Type) * 8, int mod = 0) {
+    _destination = (uint32_t)pointer;
+    destination_inc = autoinc;
+    destination_size = size;
+    destination_mod = mod;
+}
+
+/**
+* Set cycle-steal mode.  In cycle-steal mode, we do one DMA transfer per
+* trigger.  In continuous mode, we do the entire transfer on a single trigger.
+*/
+void setCycleSteal(bool f) { cycle_steal = f; }
+
+/**
+* Set the trigger for the DMA operation
+*
+* In SimpleDMA_[yourdevice].h you can find the names of the different triggers.
+* Trigger_ALWAYS is defined for all devices, it will simply move the data
+* as fast as possible. Used for memory-memory transfers. If nothing else is set
+* that will be used by default.
+*
+* @param trig - trigger to use
+* @param return - 0 on success
+*/
+void trigger(SimpleDMA_Trigger trig) {
+    _trigger = trig;
+}
+
+/**
+* Set the DMA channel
+*
+* Generally you will not need to call this function, the constructor does so for you
+*
+* @param chan - DMA channel to use, -1 = variable channel (highest priority channel which is available)
+*/
+void channel(int chan);
+
+/**
+* Start the transfer
+*
+* @param length - number of BYTES to be moved by the DMA
+*/
+int start(uint32_t length);
+
+/**
+* Start a new transfer with the same parameters as last time
+*/
+int restart(uint32_t length);
+
+/**
+* Is the DMA channel busy
+*
+* @param channel - channel to check, -1 = current channel
+* @return - true if it is busy
+*/
+bool isBusy( int channel = -1 );
+
+/**
+* Number of bytes remaining in running transfer.  This reads the controller
+* register with the remaining byte count, which the hardware updates each
+* time it completes a destination transfer.
+*/
+uint32_t remaining(int channel = -1);
+
+/**
+* Attach an interrupt upon completion of DMA transfer or error
+*
+* @param function - function to call upon completion (may be a member function)
+*/
+void attach(void (*function)(void)) {
+    _callback.attach(function);
+    }
+    
+template<typename T>
+    void attach(T *object, void (T::*member)(void)) {
+        _callback.attach(object, member);
+    }
+
+#ifdef RTOS_H
+/**
+* Start a DMA transfer similar to start, however block current Thread
+* until the transfer is finished
+*
+* When using this function only the current Thread is halted.
+* The Thread is moved to Waiting state: other Threads will continue
+* to run normally. 
+*
+* This function is only available if you included rtos.h before 
+* including SimpleDMA.h.
+*
+* @param length - number of BYTES to be moved by the DMA
+*/
+void wait(int length) {
+    id = Thread::gettid();
+    this->attach(this, &SimpleDMA::waitCallback);
+    this->start(length);
+    Thread::signal_wait(0x1);
+}
+#endif
+
+protected:
+int _channel;
+SimpleDMA_Trigger _trigger;
+uint32_t _source;
+uint32_t _destination;
+bool source_inc;
+bool destination_inc;
+uint8_t source_size;
+uint8_t destination_size;
+uint32_t source_mod;
+uint32_t destination_mod;
+bool cycle_steal;
+
+bool auto_channel;
+
+//IRQ handlers
+FunctionPointer _callback;
+void irq_handler(void);
+
+static SimpleDMA *irq_owner[DMA_CHANNELS];
+
+static void irq_handler0( void ); 
+
+#if DMA_IRQS > 1
+static void irq_handler1( void );
+static void irq_handler2( void );
+static void irq_handler3( void );
+#endif
+
+//Keep searching until we find a non-busy channel, start with lowest channel number
+int getFreeChannel(void);
+
+#ifdef RTOS_H
+osThreadId id;
+void waitCallback(void) {
+    osSignalSet(id, 0x1);    
+}
+#endif
+};
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleDMA/SimpleDMA_KL25.h	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,45 @@
+#if defined TARGET_KL25Z
+
+#define DMA_CHANNELS        4
+#define DMA_IRQS            4
+
+enum SimpleDMA_Trigger {
+    Trigger_ALWAYS = 60,
+    Trigger_UART0_RX = 2,
+    Trigger_UART0_TX,
+    Trigger_UART1_RX,
+    Trigger_UART1_TX,
+    Trigger_UART2_RX,
+    Trigger_UART2_TX,
+    Trigger_SPI0_RX = 16,
+    Trigger_SPI0_TX,
+    Trigger_SPI1_RX,
+    Trigger_SPI1_TX,
+    Trigger_I2C0 = 22,
+    Trigger_I2C1,
+    Trigger_TPM0_C0,
+    Trigger_TPM0_C1,
+    Trigger_TPM0_C2,
+    Trigger_TPM0_C3,
+    Trigger_TPM0_C4,
+    Trigger_TPM0_C5,
+    Trigger_TPM1_C0 = 32,
+    Trigger_TPM1_C1,
+    Trigger_TPM2_C0,
+    Trigger_TPM2_C1,
+    Trigger_ADC0 = 40,
+    Trigger_CMP0 = 42,
+    Trigger_DAC0 = 45,
+    Trigger_PORTA = 49,
+    Trigger_PORTD = 52,
+    Trigger_TPM0 = 54,
+    Trigger_TPM1,
+    Trigger_TPM2,
+    Trigger_TSI,
+    Trigger_ALWAYS0 = 60,
+    Trigger_ALWAYS1,
+    Trigger_ALWAYS2,
+    Trigger_ALWAYS3,
+};    
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleDMA/SimpleDMA_KL25_46.cpp	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,149 @@
+#if defined TARGET_KL25Z || defined TARGET_KL46Z
+#include "SimpleDMA.h"
+
+
+
+SimpleDMA *SimpleDMA::irq_owner[4] = {NULL};
+
+SimpleDMA::SimpleDMA(int channel) {
+    this->channel(channel);
+       
+    //Enable DMA
+    SIM->SCGC6 |= 1<<1;     //Enable clock to DMA mux
+    SIM->SCGC7 |= 1<<8;     //Enable clock to DMA
+    
+    trigger(Trigger_ALWAYS);
+   
+    NVIC_SetVector(DMA0_IRQn, (uint32_t)&irq_handler0);
+    NVIC_SetVector(DMA1_IRQn, (uint32_t)&irq_handler1);
+    NVIC_SetVector(DMA2_IRQn, (uint32_t)&irq_handler2);
+    NVIC_SetVector(DMA3_IRQn, (uint32_t)&irq_handler3);
+    NVIC_EnableIRQ(DMA0_IRQn);
+    NVIC_EnableIRQ(DMA1_IRQn);
+    NVIC_EnableIRQ(DMA2_IRQn);
+    NVIC_EnableIRQ(DMA3_IRQn);
+    
+    // presume cycle-steal mode
+    cycle_steal = true;
+}
+
+// Figure the circular buffer MOD bit pattern (SMOD or DMOD)
+// for a given circular buffer size.  The buffer size is
+// required to be a power of 2 from 16 to 256K.
+static uint32_t modsize_to_modbits(uint32_t siz)
+{
+    // The bit pattern is such that 2^(bits+3), so we basically
+    // need to take the base-2 log of the size.  Zero has the
+    // special meaning that the circular buffer is disabled.
+    uint32_t bits = 0;
+    for (bits = 0 ; siz >= 16 ; siz >>= 1, ++bits) ;
+    
+    // return the result, which can't be over binary 1111
+    return bits & 0xF;
+}
+
+int SimpleDMA::start(uint32_t length) {  
+    if (auto_channel)
+        _channel = getFreeChannel();
+    else
+        while(isBusy());
+    
+    if (length > DMA_DSR_BCR_BCR_MASK)
+        return -1;
+
+    irq_owner[_channel] = this;
+    
+    DMA0->DMA[_channel].SAR = _source;
+    DMA0->DMA[_channel].DAR = _destination;
+    DMA0->DMA[_channel].DSR_BCR = length;
+    DMAMUX0->CHCFG[_channel] = _trigger;
+    
+    uint32_t config = 
+        DMA_DCR_EINT_MASK 
+        | DMA_DCR_ERQ_MASK 
+        | (cycle_steal ? DMA_DCR_CS_MASK : 0)
+        | (source_inc << DMA_DCR_SINC_SHIFT) 
+        | (modsize_to_modbits(source_mod) << DMA_DCR_SMOD_SHIFT)
+        | (destination_inc << DMA_DCR_DINC_SHIFT)
+        | (modsize_to_modbits(destination_mod) << DMA_DCR_DMOD_SHIFT);
+    switch (source_size) {
+        case 8:
+            config |= 1 << DMA_DCR_SSIZE_SHIFT;
+            break;
+        case 16:
+            config |= 2 << DMA_DCR_SSIZE_SHIFT; 
+            break;
+    }
+    switch (destination_size) {
+        case 8:
+            config |= 1 << DMA_DCR_DSIZE_SHIFT;
+            break;
+        case 16:
+            config |= 2 << DMA_DCR_DSIZE_SHIFT; 
+            break;
+    }
+    
+    DMA0->DMA[_channel].DCR = config;      
+           
+    //Start
+    DMAMUX0->CHCFG[_channel] |= 1<<7;
+    
+    return 0;
+}
+
+int SimpleDMA::restart(uint32_t length)
+{
+    DMA0->DMA[_channel].SAR = _source;
+    DMA0->DMA[_channel].DAR = _destination;
+    DMA0->DMA[_channel].DSR_BCR = length;
+    DMAMUX0->CHCFG[_channel] |= 1<<7;
+    return 0;
+}
+
+bool SimpleDMA::isBusy( int channel ) {
+    //Busy bit doesn't work as I expect it to do, so just check if counter is at zero
+    //return (DMA0->DMA[_channel].DSR_BCR & (1<<25) == 1<<25);
+    if (channel == -1)
+        channel = _channel;
+    
+    return (DMA0->DMA[channel].DSR_BCR & 0xFFFFF);
+}
+
+/*****************************************************************/
+uint32_t SimpleDMA::remaining(int channel) 
+{
+    // note that the BCR register always reads with binary 1110
+    // (if the configuration is correct) or 1111 (if there's an
+    // error in the configuration) in bits 23-20, so we need
+    // to mask these out - only keep bits 19-0 (low-order 20 
+    // bits = 0xFFFFF)
+    return (DMA0->DMA[channel < 0 ? _channel : channel].DSR_BCR & 0xFFFFF);
+}
+
+/*****************************************************************/
+void SimpleDMA::irq_handler(void) {
+    DMAMUX0->CHCFG[_channel] = 0;
+    DMA0->DMA[_channel].DSR_BCR |= DMA_DSR_BCR_DONE_MASK ; 
+    _callback.call();
+}
+
+void SimpleDMA::irq_handler0( void ) {
+    if (irq_owner[0]!=NULL)
+        irq_owner[0]->irq_handler();
+}
+
+void SimpleDMA::irq_handler1( void ) {
+    if (irq_owner[1]!=NULL)
+        irq_owner[1]->irq_handler();
+}
+
+void SimpleDMA::irq_handler2( void ) {
+    if (irq_owner[2]!=NULL)
+        irq_owner[2]->irq_handler();
+}
+
+void SimpleDMA::irq_handler3( void ) {
+    if (irq_owner[3]!=NULL)
+        irq_owner[3]->irq_handler();
+}
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleDMA/SimpleDMA_KL46.h	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,48 @@
+#if defined TARGET_KL46Z
+
+#define DMA_CHANNELS        4
+#define DMA_IRQS            4
+
+enum SimpleDMA_Trigger {
+    Trigger_ALWAYS = 60,
+    Trigger_UART0_RX = 2,
+    Trigger_UART0_TX,
+    Trigger_UART1_RX,
+    Trigger_UART1_TX,
+    Trigger_UART2_RX,
+    Trigger_UART2_TX,
+    Trigger_I2S0_RX = 14,
+    Trigger_I2S0_TX,
+    Trigger_SPI0_RX = 16,
+    Trigger_SPI0_TX,
+    Trigger_SPI1_RX,
+    Trigger_SPI1_TX,
+    Trigger_I2C0 = 22,
+    Trigger_I2C1,
+    Trigger_TPM0_C0,
+    Trigger_TPM0_C1,
+    Trigger_TPM0_C2,
+    Trigger_TPM0_C3,
+    Trigger_TPM0_C4,
+    Trigger_TPM0_C5,
+    Trigger_TPM1_C0 = 32,
+    Trigger_TPM1_C1,
+    Trigger_TPM2_C0,
+    Trigger_TPM2_C1,
+    Trigger_ADC0 = 40,
+    Trigger_CMP0 = 42,
+    Trigger_DAC0 = 45,
+    Trigger_PORTA = 49,
+    Trigegr_PORTC = 51,
+    Trigger_PORTD = 52,
+    Trigger_TPM0 = 54,
+    Trigger_TPM1,
+    Trigger_TPM2,
+    Trigger_TSI,
+    Trigger_ALWAYS0 = 60,
+    Trigger_ALWAYS1,
+    Trigger_ALWAYS2,
+    Trigger_ALWAYS3,
+};    
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleDMA/SimpleDMA_LPC1768.cpp	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,110 @@
+#ifdef TARGET_LPC1768
+
+#include "SimpleDMA.h"
+
+SimpleDMA *SimpleDMA::irq_owner[8] = {NULL};
+LPC_GPDMACH_TypeDef *LPC_GPDMACH[8] = {LPC_GPDMACH0, LPC_GPDMACH1, LPC_GPDMACH2, LPC_GPDMACH3, LPC_GPDMACH4, LPC_GPDMACH5, LPC_GPDMACH6, LPC_GPDMACH7};
+uint32_t getTransferType(SimpleDMA_Trigger trig, uint32_t source, uint32_t destination);
+
+SimpleDMA::SimpleDMA(int channel) {
+    this->channel(channel);
+    
+    //Power up
+    LPC_SC->PCONP |= 1<<29;
+    LPC_GPDMA->DMACConfig = 1;
+    trigger(Trigger_ALWAYS);
+    
+    NVIC_SetVector(DMA_IRQn, (uint32_t)&irq_handler0);
+    NVIC_EnableIRQ(DMA_IRQn);          
+}
+
+int SimpleDMA::start(uint32_t length) {
+    if (auto_channel)
+        _channel = getFreeChannel();
+    else
+        while(isBusy());
+    
+    uint32_t control = (source_inc << 26) | (destination_inc << 27) | (1UL << 31);
+    switch (source_size) {
+        case 16:
+            control |= (1<<18) | (length >> 1);
+            break;
+        case 32:
+            control |= (2<<18) | (length >> 2);  
+            break;
+        default:
+            control |= length;
+    }
+    switch (destination_size) {
+        case 16:
+            control |= (1<<21);
+            break;
+        case 32:
+            control |= (2<<21);  
+            break;
+    } 
+    
+    LPC_GPDMACH[_channel]->DMACCSrcAddr = _source;
+    LPC_GPDMACH[_channel]->DMACCDestAddr = _destination;
+    LPC_GPDMACH[_channel]->DMACCLLI = 0;
+    LPC_GPDMACH[_channel]->DMACCControl = control;     //Enable interrupt also
+    
+    irq_owner[_channel] = this;
+    
+    if (_trigger != Trigger_ALWAYS) {      
+        if (_trigger & 16) 
+            LPC_SC->DMAREQSEL |= 1 << (_trigger - 24);
+        else
+            LPC_SC->DMAREQSEL &= ~(1 << (_trigger - 24));
+        
+        LPC_GPDMACH[_channel]->DMACCConfig = ((_trigger & 15) << 1) + ((_trigger & 15) << 6) + (getTransferType(_trigger, _source, _destination) << 11) +  (1<<15) +1;        //Both parts of the transfer get triggered at same time
+    } else 
+        LPC_GPDMACH[_channel]->DMACCConfig = (getTransferType(_trigger, _source, _destination) << 11) + 1 + (1<<15);               //Enable channel
+    
+    return 0;
+}
+
+bool SimpleDMA::isBusy( int channel ) {
+    if (channel == -1)
+        channel = _channel;
+    return (LPC_GPDMA->DMACEnbldChns & (1<<channel));
+}
+
+void SimpleDMA::irq_handler0(void) {
+    while(LPC_GPDMA->DMACIntTCStat != 0) {
+        
+    uint32_t intloc = 31 - __CLZ(LPC_GPDMA->DMACIntTCStat & 0xFF);
+    if (irq_owner[intloc]!=NULL)
+        irq_owner[intloc]->irq_handler();
+    }
+}
+
+void SimpleDMA::irq_handler(void) {
+    LPC_GPDMA->DMACIntTCClear = 1<<_channel;
+    _callback.call();
+}
+
+static inline bool isMemory(uint32_t addr)
+{
+    return (addr >> 28) == 0 || (addr >> 28) == 1 || ((addr >= 0x2007C000) && (addr < (0x2007C000 + 0x8000)));
+}
+
+uint32_t getTransferType(SimpleDMA_Trigger trig, uint32_t source, uint32_t destination) {
+    //If it is always, simply put it on memory-to-memory
+    if (trig == Trigger_ALWAYS)
+        return 0;
+    else if (isMemory(source)) {       //if source is RAM/Flash
+        if (isMemory(destination))        //if destination is RAM/flash
+            return 3;                                                               //Return p2p for m2m with a trigger (since I have no idea wtf you are trying to do)
+        else
+            return 1;                                                               //Source is memory, destination is peripheral, so m2p
+        }
+    else {
+        if (isMemory(destination))
+            return 2;                                                               //Source is peripheral, destination is memory
+        else
+            return 3;                                                               //Both source and destination are peripherals
+        }
+        
+}
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleDMA/SimpleDMA_LPC1768.h	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,34 @@
+#ifdef TARGET_LPC1768
+
+#define DMA_CHANNELS        8
+#define DMA_IRQS            1
+
+enum SimpleDMA_Trigger {
+    Trigger_ALWAYS = -1,
+    Trigger_SSP0_TX,
+    Trigger_SSP0_RX,
+    Trigger_SSP1_TX,
+    Trigger_SSP1_RX,
+    Trigger_ADC,
+    Trigger_I2S0,
+    Trigger_I2S1,
+    Trigger_DAC,
+    Trigger_UART0_TX,
+    Trigger_UART0_RX,
+    Trigger_UART1_TX,
+    Trigger_UART1_RX,
+    Trigger_UART2_TX,
+    Trigger_UART2_RX,
+    Trigger_UART3_TX,
+    Trigger_UART3_RX,
+    Trigger_MATCH0_0 = 24,
+    Trigger_MATCH0_1,
+    Trigger_MATCH1_0,
+    Trigger_MATCH1_1,
+    Trigger_MATCH2_0,
+    Trigger_MATCH2_1,
+    Trigger_MATCH3_0,
+    Trigger_MATCH3_1
+};  
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleDMA/SimpleDMA_common.cpp	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,25 @@
+#include "SimpleDMA.h"
+
+void SimpleDMA::channel(int chan) {
+    if (chan == -1) {
+        auto_channel = true;
+        _channel = 0;
+    } else {
+        auto_channel = false;
+        if (chan >= 0 && chan < DMA_CHANNELS)
+            _channel = chan;
+        else
+            _channel = DMA_CHANNELS-1;
+    }
+}
+
+int SimpleDMA::getFreeChannel(void) {
+    int retval = 0;
+    while(1) {
+        if (!isBusy(retval))
+            return retval;
+        retval++;
+        if (retval >= DMA_CHANNELS)
+            retval = 0;
+    }  
+}
\ No newline at end of file
--- a/TSL1410R/tsl1410r.h	Sun Feb 07 03:07:11 2016 +0000
+++ b/TSL1410R/tsl1410r.h	Mon Feb 15 20:30:32 2016 +0000
@@ -1,3 +1,45 @@
+// DMA VERSION - NOT WORKING
+
+// I'm saving this code for now, since it was somewhat promising but doesn't
+// quite work.  The idea here was to read the ADC via DMA, operating the ADC
+// in continuous mode.  This speeds things up pretty impressively (by about 
+// a factor of 3 vs having the MCU read each result from the ADC sampling 
+// register), but I can't figure out how to get a stable enough signal out of 
+// it.  I think the problem is that the timing isn't precise enough in detecting 
+// when the DMA completes each write.  We have to clock the next pixel onto the 
+// CCD output each time we complete a sample, and we have to do so quickly so 
+// that the next pixel charge is stable at the ADC input pin by the time the 
+// ADC sample interval starts.  I'm seeing a ton of noise, which I think means 
+// that the new pixel isn't ready for the ADC in time. 
+//
+// I've tried a number of approaches, none of which works:
+//
+// - Skip every other sample, so that we can spend one whole sample just 
+// clocking in the next pixel.  We discard the "odds" samples that are taken
+// during pixel changes, and use only the "even" samples where the pixel is
+// stable the entire time.  I'd think the extra sample would give us plenty
+// of time to stabilize the next pixel, but it doesn't seem to work out that
+// way.  I think the problem might be that the latency of the MCU responding
+// to each sample completion is long enough relative to the sampling interval
+// that we can't reliably respond to the ADC done condition fast enough.  I've
+// tried basing the sample completion detection on the DMA byte counter and
+// the ADC interrupt.  The DMA byte counter is updated after the DMA transfer
+// is done, so that's probably just too late in the cycle.  The ADC interrupt
+// should be concurrent with the DMA transfer starting, but in practice it 
+// still doesn't give us good results.
+//
+// - Use DMA, but with the ADC in single-sample mode.  This bypasses the latency
+// problem by ensuring that the ADC doesn't start a new sample until we've
+// definitely finished clocking in the next pixel.  But it defeats the whole
+// purpose by eliminating the speed improvement - the speeds are comparable to
+// doing the transfers via the MCU.  This surprises me because I'd have expected
+// that the DMA would run concurrently with the MCU pixel clocking code, but
+// maybe there's enough bus contention between the MCU and DMA in this case that
+// there's no true overlapping of the operation.  Or maybe the interrupt dispatch
+// adds enough overhead to negate any overlapping.  I haven't actually been able
+// to get good data out of this mode, either, but I gave up early because of the
+// lack of any speed improvement.
+
 /*
  *  TSL1410R interface class.
  *
@@ -7,9 +49,11 @@
 #include "mbed.h"
 #include "config.h"
 #include "AltAnalogIn.h"
+#include "SimpleDMA.h"
  
 #ifndef TSL1410R_H
 #define TSL1410R_H
+#define TSL1410R_DMA
 
 // For faster GPIO on the clock pin, we write the IOPORT registers directly.
 // PORT_BASE gives us the memory mapped location of the IOPORT register set
@@ -49,11 +93,29 @@
         clear();
         clear();
         
+        // set up our DMA channel for reading from our analog in pin
+        ao1.initDMA(&adc_dma);
+        
+        // Set up our DMA channel for writing the sensor SCLK - we use the PTOR
+        // (toggle) register to flip the bit on each write.  To pad the timing
+        // to the rate required by the CCD, do a no-op 0 write to PTOR after
+        // each toggle.  This gives us a 16-byte buffer, which we can make
+        // circular in the DMA controller.
+        static const uint32_t clkseq[] = { clockMask, 0, clockMask, 0 };
+        clk_dma.destination(&clockPort->PTOR, false, 32);
+        clk_dma.source(clkseq, true, 32, 16);   // set up our circular source buffer
+        clk_dma.trigger(Trigger_ADC0);          // software trigger
+        clk_dma.setCycleSteal(false);           // do the entire transfer on each trigger
+        
         totalTime = 0.0; nRuns = 0; // $$$
     }
     
     float totalTime; int nRuns; // $$$
 
+    // ADC interrupt handler - on each ADC event, 
+    static TSL1410R *instance;
+    static void _aiIRQ() { }
+
     // Read the pixels.
     //
     // 'n' specifies the number of pixels to sample, and is the size of
@@ -91,11 +153,10 @@
     // the current pixels and start a fresh integration cycle.
     void read(register uint16_t *pix, int n)
     {
-        Timer t; t.start(); // $$$
+        Timer t; t.start(); //float tDMA, tPix; // $$$
         
         // get the clock pin pointers into local variables for fast access
-        register volatile uint32_t *clockPSOR = &clockPort->PSOR;
-        register volatile uint32_t *clockPCOR = &clockPort->PCOR;
+        register volatile uint32_t *clockPTOR = &clockPort->PTOR;
         register const uint32_t clockMask = this->clockMask;
         
         // start the next integration cycle by pulsing SI and one clock
@@ -111,8 +172,6 @@
 static int done=0;
 if (done++ == 0) printf("nPixSensor=%d, n=%d, skip=%d, parallel=%d\r\n", nPixSensor, n, skip, parallel);
 
-        // get the clock PSOR and PCOR register addresses for fast access
-
         // read all of the pixels
         int dst;
         if (parallel)
@@ -125,7 +184,7 @@
                 // Take the clock high.  The TSL1410R will connect the next
                 // pixel pair's hold capacitors to the A01 and AO2 lines 
                 // (respectively) on the clock rising edge.
-                *clockPSOR = clockMask;
+                *clockPTOR = clockMask;
 
                 // Start the ADC sampler for AO1.  The TSL1410R sample 
                 // stabilization time per the data sheet is 120ns.  This is
@@ -135,7 +194,7 @@
                 ao1.start();
                 
                 // take the clock low while we're waiting for the reading
-                *clockPCOR = clockMask;
+                *clockPTOR = clockMask;
                 
                 // Read the first half-sensor pixel from AO1
                 pix[dst] = ao1.read_u16();
@@ -152,46 +211,61 @@
                 // Clock through the skipped pixels
                 for (int i = skip ; i > 0 ; --i) 
                 {
-                    *clockPSOR = clockMask;
-                    *clockPCOR = clockMask;
+                    *clockPTOR = clockMask;
+                    *clockPTOR = clockMask;
+                    *clockPTOR = 0;         // pad the timing with an extra nop write
                 }
             }
         }
         else
         {
             // serial mode - read all pixels in a single file
-            for (dst = 0 ; dst < n ; ++dst)
+
+            // clock in the first pixel
+            clock = 1;
+            clock = 0;
+            
+            // start the ADC DMA transfer
+            ao1.startDMA(pix, n, true);
+            
+            // We do 4 clock PTOR writes per clocked pixel (the skipped pixels 
+            // plus the pixel we actually want to sample), at 32 bits (4 bytes) 
+            // each, giving 16 bytes per pixel for the overall write.
+            int clk_dma_len = (skip+1)*16;
+            clk_dma.start(clk_dma_len);
+            
+            // start the first sample
+            ao1.start();
+            
+            // read all pixels
+            for (dst = n*2 ; dst > 0 ; dst -= 2)
             {
-                // Clock the next pixel onto the sensor A0 line
-                *clockPSOR = clockMask;
+                // wait for the current ADC sample to finish
+                while (adc_dma.remaining() >= dst) { }
                 
-                // start the ADC sampler
+                // start the next analog read while we're finishing the DMA transfers
                 ao1.start();
                 
-                // take the clock low while we're waiting for the analog reading
-                *clockPCOR = clockMask;
-                
-                // wait for and read the ADC sample; plug it into the output
-                // array, and increment the output pointer to the next position
-                pix[dst] = ao1.read_u16();
-                
-                // clock through the skipped pixels
-                for (int i = skip ; i > 0 ; --i) 
-                {
-                    *clockPSOR = clockMask;
-                    *clockPCOR = clockMask;
-                }
+                // re-arm the clock DMA
+                //clk_dma.restart(clk_dma_len);
             }
+            
+            // wait for the DMA transfer to finish
+            while (adc_dma.isBusy()) { }
+            
+            // apply the 12-bit to 16-bit rescaling to all values
+            for (int i = 0 ; i < n ; ++i)
+                pix[i] <<= 4;
         }
         
 //$$$
 if (done==1) printf(". done: dst=%d\r\n", dst);
         
         // clock out one extra pixel to leave A1 in the high-Z state
-        clock = 1;
-        clock = 0;
+        *clockPTOR = clockMask;
+        *clockPTOR = clockMask;
         
-        if (n >= 80) { totalTime += t.read(); nRuns += 1; } // $$$
+        if (n >= 64) { totalTime += t.read(); nRuns += 1; } // $$$
     }
 
     // Clock through all pixels to clear the array.  Pulses SI at the
@@ -222,6 +296,9 @@
     }
 
 private:
+    SimpleDMA adc_dma;        // DMA controller for reading the analog input
+    SimpleDMA clk_dma;        // DMA controller for the sensor SCLK (writes the PTOR register to toggle the clock bit)
+    char *dmabuf;             // buffer for DMA transfers
     int nPixSensor;           // number of pixels in physical sensor array
     DigitalOut si;            // GPIO pin for sensor SI (serial data) 
     DigitalOut clock;         // GPIO pin for sensor SCLK (serial clock)
@@ -233,3 +310,4 @@
 };
  
 #endif /* TSL1410R_H */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TSL1410R/tsl1410r_dma.cpp	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,8 @@
+#include "tsl1410r.h"
+
+#ifdef TSL1410R_DMA
+
+// interrupt counters
+uint32_t TSL1410R::intCounter;
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TSL1410R/tsl1410r_orig.h	Mon Feb 15 20:30:32 2016 +0000
@@ -0,0 +1,238 @@
+/*
+ *  TSL1410R interface class.
+ *
+ *  This provides a high-level interface for the Taos TSL1410R linear CCD array sensor.
+ */
+ 
+#include "mbed.h"
+#include "config.h"
+#include "AltAnalogIn.h"
+ 
+#ifndef TSL1410R_H
+#define TSL1410R_H
+
+// For faster GPIO on the clock pin, we write the IOPORT registers directly.
+// PORT_BASE gives us the memory mapped location of the IOPORT register set
+// for a pin; PINMASK gives us the bit pattern to write to the registers.
+//
+// - To turn a pin ON:  PORT_BASE(pin)->PSOR |= PINMASK(pin)
+// - To turn a pin OFF: PORT_BASE(pin)->PCOR |= PINMASK(pin)
+// - To toggle a pin:   PORT_BASE(pin)->PTOR |= PINMASK(pin)
+//
+// When used in a loop where the port address and pin mask are cached in
+// local variables, this runs at the same speed as the FastIO library - about 
+// 78ns per pin write on the KL25Z.  Not surprising since it's doing the same
+// thing, and the compiler should be able to reduce a pin write to a single ARM
+// instruction when the port address and mask are in local register variables.
+// The advantage over the FastIO library is that this approach allows for pins
+// to be assigned dynamically at run-time, which we prefer because it allows for
+// configuration changes to be made on the fly rather than having to recompile
+// the program.
+#define GPIO_PORT(pin)        (((unsigned int)(pin)) >> PORT_SHIFT)
+#define GPIO_PORT_BASE(pin)   ((FGPIO_Type *)(FPTA_BASE + GPIO_PORT(pin) * 0x40))
+#define GPIO_PINMASK(pin)     gpio_set(pin)
+ 
+class TSL1410R
+{
+public:
+    TSL1410R(int nPixSensor, PinName siPin, PinName clockPin, PinName ao1Pin, PinName ao2Pin) 
+        : nPixSensor(nPixSensor), si(siPin), clock(clockPin), ao1(ao1Pin), ao2(ao2Pin)
+    {
+        // we're in parallel mode if ao2 is a valid pin
+        parallel = (ao2Pin != NC);
+        
+        // remember the clock pin port base and pin mask for fast access
+        clockPort = GPIO_PORT_BASE(clockPin);
+        clockMask = GPIO_PINMASK(clockPin);
+        
+        // clear out power-on random data by clocking through all pixels twice
+        clear();
+        clear();
+        
+        totalTime = 0.0; nRuns = 0; // $$$
+    }
+    
+    float totalTime; int nRuns; // $$$
+    
+    // Read the pixels.
+    //
+    // 'n' specifies the number of pixels to sample, and is the size of
+    // the output array 'pix'.  This can be less than the full number
+    // of pixels on the physical device; if it is, we'll spread the
+    // sample evenly across the full length of the device by skipping
+    // one or more pixels between each sampled pixel to pad out the
+    // difference between the sample size and the physical CCD size.
+    // For example, if the physical sensor has 1280 pixels, and 'n' is
+    // 640, we'll read every other pixel and skip every other pixel.
+    // If 'n' is 160, we'll read every 8th pixel and skip 7 between
+    // each sample.
+    // 
+    // The reason that we provide this subset mode (where 'n' is less
+    // than the physical pixel count) is that reading a pixel is the most
+    // time-consuming part of the scan.  For each pixel we read, we have
+    // to wait for the pixel's charge to transfer from its internal smapling
+    // capacitor to the CCD's output pin, for that charge to transfer to
+    // the KL25Z input pin, and for the KL25Z ADC to get a stable reading.
+    // This all takes on the order of 20us per pixel.  Skipping a pixel
+    // only requires a clock pulse, which takes about 350ns.  So we can
+    // skip 60 pixels in the time it takes to sample 1 pixel.
+    //
+    // We clock an SI pulse at the beginning of the read.  This starts the
+    // next integration cycle: the pixel array will reset on the SI, and 
+    // the integration starts 18 clocks later.  So by the time this method
+    // returns, the next sample will have been integrating for npix-18 clocks.  
+    // That's usually enough time to allow immediately reading the next
+    // sample.  If more integration time is required, the caller can simply
+    // sleep/spin for the desired additional time, or can do other work that
+    // takes the desired additional time.
+    //
+    // If the caller has other work to tend to that takes longer than the
+    // desired maximum integration time, it can call clear() to clock out
+    // the current pixels and start a fresh integration cycle.
+    void read(register uint16_t *pix, int n)
+    {
+        Timer t; t.start();//$$$
+        
+        // get the clock pin pointers into local variables for fast access
+        register volatile uint32_t *clockPSOR = &clockPort->PSOR;
+        register volatile uint32_t *clockPCOR = &clockPort->PCOR;
+        register const uint32_t clockMask = this->clockMask;
+        
+        // start the next integration cycle by pulsing SI and one clock
+        si = 1;
+        clock = 1;
+        si = 0;
+        clock = 0;
+        
+        // figure how many pixels to skip on each read
+        int skip = nPixSensor/n - 1;
+        
+///$$$
+static int done=0;
+if (done++ == 0) printf("nPixSensor=%d, n=%d, skip=%d, parallel=%d\r\n", nPixSensor, n, skip, parallel);
+
+        // read all of the pixels
+        int dst;
+        if (parallel)
+        {
+            // Parallel mode - read pixels from each half sensor concurrently.
+            // Divide 'n' (the output pixel count) by 2 to get the loop count,
+            // since we're going to do 2 pixels on each iteration.
+            for (n /= 2, dst = 0 ; dst < n ; ++dst)
+            {
+                // Take the clock high.  The TSL1410R will connect the next
+                // pixel pair's hold capacitors to the A01 and AO2 lines 
+                // (respectively) on the clock rising edge.
+                *clockPSOR = clockMask;
+
+                // Start the ADC sampler for AO1.  The TSL1410R sample 
+                // stabilization time per the data sheet is 120ns.  This is
+                // fast enough that we don't need an explicit delay, since
+                // the instructions to execute this call will take longer
+                // than that.
+                ao1.start();
+                
+                // take the clock low while we're waiting for the reading
+                *clockPCOR = clockMask;
+                
+                // Read the first half-sensor pixel from AO1
+                pix[dst] = ao1.read_u16();
+                
+                // Read the second half-sensor pixel from AO2, and store it
+                // in the destination array at the current index PLUS 'n',
+                // which you will recall contains half the output pixel count.
+                // This second pixel is halfway up the sensor from the first 
+                // pixel, so it goes halfway up the output array from the
+                // current output position.
+                ao2.start();
+                pix[dst + n] = ao2.read_u16();
+                
+                // Clock through the skipped pixels
+                for (int i = skip ; i > 0 ; --i) 
+                {
+                    *clockPSOR = clockMask;
+                    *clockPCOR = clockMask;
+                }
+            }
+        }
+        else
+        {
+            // serial mode - read all pixels in a single file
+
+            // clock in the first pixel
+            *clockPSOR = clockMask;
+            *clockPCOR = clockMask;
+            
+            // clock through the pixels            
+            for (dst = 0 ; dst < n ; ++dst)
+            {
+                // Read this sample
+                ao1.start();
+                pix[dst] = ao1.read_u16();
+                
+                // clock in the next pixel
+                for (int i = skip ; i >= 0 ; --i) 
+                {
+                    *clockPSOR = clockMask;
+                    *clockPCOR = clockMask;
+                    *clockPCOR = clockMask;
+                }
+            }
+
+            // we're done - stop the ADC sampler            
+            ao1.stop();
+        }
+        
+//$$$
+//static int xxx = 0; xxx = (xxx+1)%2500; if (xxx==0) printf("tPix=%f, tDMA=%f, diff=%f\r\n", tPix*1000, tDMA*1000, (tDMA - tPix)*1000);
+if (done==1) printf(". done: dst=%d\r\n", dst);
+        
+        // clock out one extra pixel to leave A1 in the high-Z state
+        clock = 1;
+        clock = 0;
+        
+        if (n >= 64) { totalTime += t.read(); nRuns += 1; } // $$$
+    }
+
+    // Clock through all pixels to clear the array.  Pulses SI at the
+    // beginning of the operation, which starts a new integration cycle.
+    // The caller can thus immediately call read() to read the pixels 
+    // integrated while the clear() was taking place.
+    void clear()
+    {
+        // get the clock pin pointers into local variables for fast access
+        register FGPIO_Type *clockPort = this->clockPort;
+        register uint32_t clockMask = this->clockMask;
+
+        // clock in an SI pulse
+        si = 1;
+        clockPort->PSOR = clockMask;
+        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 ? nPixSensor/2 : nPixSensor;
+        
+        // clock out all pixels
+        for (int i = 0 ; i < n + 1 ; ++i) {
+            clock = 1; // $$$clockPort->PSOR = clockMask;
+            clock = 0; // $$$clockPort->PCOR = clockMask;
+        }
+    }
+
+private:
+    SimpleDMA dma;            // DMA controller for reading the analog input
+    char *dmabuf;             // buffer for DMA transfers
+    int nPixSensor;           // number of pixels in physical sensor array
+    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
+    AltAnalogIn ao1;          // GPIO pin for sensor AO1 (analog output 1) - we read sensor data from this pin
+    AltAnalogIn 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/ccdSensor.h	Sun Feb 07 03:07:11 2016 +0000
+++ b/ccdSensor.h	Mon Feb 15 20:30:32 2016 +0000
@@ -200,20 +200,23 @@
         return true;
     }
     
-    // send an exposure report to the joystick interface
-    virtual void sendExposureReport(USBJoystick &js)
+    // Send an exposure report to the joystick interface.
+    // 
+    // Mode bits:
+    //    0x01  -> send processed pixels (default is raw pixels)
+    //    0x02  -> low res scan (default is high res scan)
+    virtual void sendExposureReport(USBJoystick &js, uint8_t mode)
     {
-        // Read a fresh high-res scan, then do another right away.  This
-        // gives us the shortest possible exposure for the sample we report,
-        // which helps ensure that the user inspecting the data sees something
-        // close to what we see when we calculate the plunger position.
-        ccd.read(pix, highResPix);
-        ccd.read(pix, highResPix);
+        // get the number of pixels according to the high res/low res mode
+        int npix = (mode & 0x02 ? lowResPix : highResPix);
+
+        // do a scan
+        ccd.read(pix, npix);
         
         // send reports for all pixels
         int idx = 0;
-        while (idx < highResPix)
-            js.updateExposure(idx, highResPix, pix);
+        while (idx < npix)
+            js.updateExposure(idx, npix, pix);
             
         // The pixel dump requires many USB reports, since each report
         // can only send a few pixel values.  An integration cycle has
@@ -226,7 +229,8 @@
     }
     
 protected:
-    // pixel buffer - we allocate this to be big enough for a high-res scan
+    // Pixel buffer.  We allocate this to be big enough for the high-res scan,
+    // which is the most pixels we'll need to capture.
     uint16_t *pix;
 
     // number of pixels in a high-res scan
@@ -252,7 +256,7 @@
 {
 public:
     PlungerSensorTSL1410R(PinName si, PinName clock, PinName ao1, PinName ao2) 
-        : PlungerSensorCCD(1280, 320, 64, si, clock, ao1, ao2)
+        : PlungerSensorCCD(1280, 256, 80, si, clock, ao1, ao2)
     {
     }
 };
@@ -262,7 +266,7 @@
 {
 public:
     PlungerSensorTSL1412R(PinName si, PinName clock, PinName ao1, PinName ao2)
-        : PlungerSensorCCD(1536, 384, 64, si, clock, ao1, ao2)
+        : PlungerSensorCCD(1536, 256, 128, si, clock, ao1, ao2)
     {
     }
 };
--- a/main.cpp	Sun Feb 07 03:07:11 2016 +0000
+++ b/main.cpp	Mon Feb 15 20:30:32 2016 +0000
@@ -2326,8 +2326,12 @@
 // to distinguish special request reply packets.
 uint16_t statusFlags;
     
-// flag: send a pixel dump after the next read
+// Pixel dump mode - the host requested a dump of image sensor pixels
+// (helpful for installing and setting up the sensor and light source)
 bool reportPix = false;
+uint8_t reportPixMode;  // pixel report mode bits: 
+                        // 0x01 -> raw pixels (0) / processed (1)
+                        // 0x02 -> high res scan (0) / low res (1)
 
 
 // ---------------------------------------------------------------------------
@@ -2508,8 +2512,11 @@
             
         case 3:
             // 3 = pixel dump
-            // (No parameters)
+            //     data[2] = mode bits:
+            //               0x01  -> return processed pixels (default is raw pixels)
+            //               0x02  -> low res scan (default is high res scan)
             reportPix = true;
+            reportPixMode = data[2];
             
             // show purple until we finish sending the report
             diagLED(1, 0, 1);
@@ -3390,7 +3397,7 @@
         if (reportPix)
         {
             // send the report            
-            plungerSensor->sendExposureReport(js);
+            plungerSensor->sendExposureReport(js, reportPixMode);
 
             // we have satisfied this request
             reportPix = false;
--- a/plunger.h	Sun Feb 07 03:07:11 2016 +0000
+++ b/plunger.h	Mon Feb 15 20:30:32 2016 +0000
@@ -50,7 +50,17 @@
     // through special joystick reports.  This is used for PC-side testing tools
     // to let the user check the sensor installation by directly viewing its
     // pixel output.
-    virtual void sendExposureReport(class USBJoystick &js) { }
+    //
+    // Mode bits:
+    //   0x01  -> send processed pixels (default is raw pixels)
+    //   0x02  -> low res scan (default is high res scan)
+    //
+    // If processed mode is selected, the sensor should apply any pixel
+    // processing it normally does when taking a plunger position reading,
+    // such as exposure correction, noise reduction, etc.  In raw mode, we
+    // simply send the pixels as read from the sensor.  Both modes are useful
+    // in setting up the physical sensor.
+    virtual void sendExposureReport(class USBJoystick &js, uint8_t mode) { }
 };
 
 #endif /* PLUNGER_H */