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 real plunger, button inputs, and feedback device control.

In case you haven't heard of the concept 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 serve as the "backglass" display. A third smaller monitor can serve as the "DMD" (the Dot Matrix Display used for scoring on newer machines), or you can even install a real pinball plasma DMD. A computer 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 hardware.

A few small companies build and sell complete, finished virtual pinball machines, but I think it's more fun as a 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 potentionmeter (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 VirtuaPin kit uses the same KL25Z microcontroller that Pinscape uses, but the rest of its hardware is different and incompatible. In particular, the Pinscape firmware doesn't include support for the IR proximity sensor used in the VirtuaPin plunger kit, so you won't be able to use your plunger device with the Pinscape firmware. In addition, the VirtuaPin setup uses a different set of GPIO pins for the button inputs from the Pinscape defaults, so if you do install the Pinscape firmware, you'll have to go into the Config Tool and reassign all of the buttons to match the VirtuaPin wiring.

Revision:
51:57eb311faafa
Parent:
50:40015764bbe6
Child:
52:8298b2a73eb2
--- a/main.cpp	Sat Feb 27 06:41:17 2016 +0000
+++ b/main.cpp	Tue Mar 01 23:21:45 2016 +0000
@@ -1,48 +1,4 @@
-// NEW PLUNGER PROCESSING 1 - 26 Feb 2016
-// This version takes advantage of the new, faster TSL1410R DMA processing
-// to implement better firing event detection.  This attempt works basically
-// like the old version, but uses the higher time resolution to detect firing
-// events more reliably.  The scheme here watches for accelerations (the old
-// TSL1410R code wasn't fast enough to do that).  We observed that a release
-// takes about 65ms from the maximum retraction point to crossing the zero
-// point.  Our 2.5ms snapshots allow us to see about 25 frames over this
-// span.  The first 5-10 frames will show the position moving forward, but
-// we don't see a clear acceleration trend in that first section.  After
-// that we see almost perfectly uniform acceleration for the rest of the
-// release until we cross the zero point.  "Almost" in that we often have
-// one or two frames where the velocity is just slightly lower than the
-// previous frame's.  I think this is probably imprecision in the sensor;
-// realistically, our time base is probably good to only +/- 1ms or so,
-// since the shutter time for each frame is about 2.3ms.  We assume that
-// each frame captures the midpoint time of the shutter span, but that's
-// a crude approximation; the scientifically right way to look at this is
-// that our snapshot times have an uncertainty on the order of the shutter
-// time.  Those error bars of course propagate into the velocity readings.
-// Fortunately, the true acceleration is high enough that it overwhelms
-// the error bars on almost every sample.  It appears to solve this
-// entirely if we simply skip a sample where we don't see acceleration
-// once we think a release has started - this takes our time between
-// samples up to about 5ms, at which point the acceleration does seem to
-// overwhelm the error bars 100% of the time.
-//
-// I'm capturing a snapshot of this implementation because I'm going to
-// try something different.  It would be much simpler if we could put our
-// readings on a slight time delay, and identify firing events
-// retrospectively when we actually cross the zero point.  I'm going to
-// experiment first with a time delay to see what the maximum acceptable
-// delay time is.  I expect that I can go up to about 30ms without it
-// becoming noticeable, but I need to try it out.  If we can go up to
-// 70ms, we can capture firing events perfectly because we can delay
-// reports long enough to have an entire firing event in history before
-// we report anything.  That will let us fix up the history to report an
-// idealized firing event to VP every time, with no false positives.
-// But I suspect a 70ms delay is going to be way too noticeable.  If
-// a 30ms delay works, I think we can still do a pretty good job - that
-// gets us about halfway into a release motion, at which point it's
-// pretty certain that it's really a release.
-
-
-/* Copyright 2014, 2015 M J Roberts, MIT License
+/* Copyright 2014, 2016 M J Roberts, MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without
@@ -2353,6 +2309,55 @@
 }
 
 // Plunger reader
+//
+// This class encapsulates our plunger data processing.  At the simplest
+// level, we read the position from the sensor, adjust it for the
+// calibration settings, and report the calibrated position to the host.
+//
+// In addition, we constantly monitor the data for "firing" motions.
+// A firing motion is when the user pulls back the plunger and releases
+// it, allowing it to shoot forward under the force of the main spring.
+// When we detect that this is happening, we briefly stop reporting the
+// real physical position that we're reading from the sensor, and instead
+// report a synthetic series of positions that depicts an idealized 
+// firing motion.
+//
+// The point of the synthetic reports is to correct for distortions
+// created by the joystick interface conventions used by VP and other
+// PC pinball emulators.  The convention they use is simply to have the
+// plunger device report the instantaneous position of the real plunger.
+// The PC software polls this reported position periodically, and moves 
+// the on-screen virtual plunger in sync with the real plunger.  This
+// works fine for human-scale motion when the user is manually moving
+// the plunger.  But it doesn't work for the high speed motion of a 
+// release.  The plunger simply moves too fast.  VP polls in about 10ms
+// intervals; the plunger takes about 50ms to travel from fully
+// retracted to the park position when released.  The low sampling
+// rate relative to the rate of change of the sampled data creates
+// a classic digital aliasing effect.  
+//
+// The synthetic reporting scheme compensates for the interface
+// distortions by essentially changing to a coarse enough timescale
+// that VP can reliably interpret the readings.  Conceptually, there
+// are three steps involved in doing this.  First, we analyze the
+// actual sensor data to detect and characterize the release motion.
+// Second, once we think we have a release in progress, we fit the 
+// data to a mathematical model of the release.  The model we use is 
+// dead simple: we consider the release to have one parameter, namely
+// the retraction distance at the moment the user lets go.  This is an 
+// excellent proxy in the real physical system for the final speed 
+// when the plunger hits the ball, and it also happens to match how 
+// VP models it internally.  Third, we construct synthetic reports
+// that will make VP's internal state match our model.  This is also
+// pretty simple: we just need to send VP the maximum retraction
+// distance for long enough to be sure that it polls it at least
+// once, and then send it the park position for long enough to 
+// ensure that VP will complete the same firing motion.  The 
+// immediate jump from the maximum point to the zero point will
+// cause VP to move its simulation model plunger forward from the
+// starting point at its natural spring acceleration rate, which 
+// is exactly what the real plunger just did.
+//
 class PlungerReader
 {
 public:
@@ -2397,9 +2402,8 @@
                 return;
             }
             
-            // Pull the last two readings from the history
+            // Pull the previous reading from the history
             const PlungerReading &prv = nthHist(0);
-            const PlungerReading &prv2 = nthHist(1);
             
             // If the new reading is within 2ms of the previous reading,
             // ignore it.  We require a minimum time between samples to
@@ -2445,6 +2449,7 @@
             // since we only use the velocity for comparison purposes,
             // to detect acceleration trends.  We therefore save ourselves
             // a little CPU time by using the natural units of our inputs.
+            const PlungerReading &prv2 = nthHist(1);
             float v = float(r.pos - prv2.pos)/float(r.t - prv2.t);
             
             // presume we'll report the latest instantaneous reading
@@ -2651,8 +2656,7 @@
     inline void firingMode(int m) 
     {
         firing = m;
-    
-        // $$$
+#if 0 // $$$   
         lwPin[3]->set(0);
         lwPin[4]->set(0);
         lwPin[5]->set(0);
@@ -2663,7 +2667,7 @@
         case 3: lwPin[5]->set(255); break;       // blue
         case 4: lwPin[3]->set(255); lwPin[5]->set(255); break;   // purple
         }
-        //$$$
+#endif //$$$
     }
     
     // Find the most recent local maximum in the history data, up to
@@ -2769,98 +2773,12 @@
 
     // Firing event state.
     //
-    // A "firing event" happens when we detect that the physical plunger
-    // is moving forward fast enough that it was probably released.  When
-    // we detect a firing event, we momentarily disconnect the joystick
-    // readings from the physical sensor, and instead feed in a series of
-    // synthesized readings that simulate an idealized release motion.
-    //
-    // The reason we create these synthetic readings is that they give us
-    // better results in VP and other PC pinball players.  The joystick
-    // interface only lets us report the instantaneous plunger position.
-    // VP only reads the position at certain intervals, so it picks up
-    // a series of snapshots of the position, which it uses to infer the
-    // plunger velocity.  But the plunger release motion is so fast that
-    // VP's sampling rate creates a classic digital "aliasing" problem.
-    //
-    // Our synthesized report structure is designed to overcome the
-    // aliasing problem by removing the intermediate position reports 
-    // and only reporting the starting and ending positions.  This
-    // allows the PC side to reliably read the extremes of the travel
-    // and work entirely in the simulation domain to simulate a plunger
-    // release of the detected distance.  This produces more realistic
-    // results than feeding VP the real data, ironically.
-    //
-    // DETECTING A RELEASE MOTION
-    //
-    // How do we tell when the plunger is being released?  The basic
-    // idea is to monitor the sensor data and look for a series of
-    // readings that match the profile of a release motion.  For an
-    // idealized, mathematical model of a plunger, a release causes
-    // the plunger to start accelerating under the spring force.
-    //
-    // The real system has a couple of complications.  First, there
-    // are some mechanical effects that make the motion less than
-    // ideal (in the sense of matching the mathematical model),
-    // like friction and wobble.  This seems to be especially
-    // significant for the first 10-20ms of the release, probably
-    // because friction is a bigger factor at slow speeds, and
-    // also because of the uneven forces as the user lets go.
-    // Second, our sensor doesn't have infinite precision, and
-    // our clock doesn't either, and these error bars compound
-    // when we combine position and time to compute velocity.
-    //
-    // To deal with these real-world complications, we have a couple
-    // of strategies.  First, we tolerate a little bit of non-uniformity
-    // in the acceleration, by waiting a little longer if we get a
-    // reading that doesn't appear to be accelerating.  We still
-    // insist on continuous acceleration, but we basically double-check
-    // a reading by extending the time window when necessary.  Second,
-    // when we detect a series of accelerating readings, we go back
-    // to prior readings from before the sustained acceleration
-    // began to find out when the motion really began.
-    //
-    // PROCESSING A RELEASE MOTION
-    //
-    // We continuously monitor the sensor data.  When we see the position
-    // moving forward, toward the zero point, we start watching for
-    // sustained acceleration .  If we see acceleration for more than a 
-    // minimum threshold time (about 20ms), we freeze the reported 
-    // position at the recent local maximum (from the recent history of 
-    // readings) and wait for the acceleration to stop or for the plunger
-    // to cross the zero position.  If it crosses the zero position
-    // while still accelerating, we initiate a firing event.  Otherwise
-    // we return to instantaneous reporting of the actual position.
-    //
-    // HOW THIS LOOKS TO THE USER
-    // 
-    // The typical timing to reach the zero point during a release
-    // is about 60-80ms.  This is essentially the longest that we can
-    // stay in phase 1, so it's the longest that the readings will be
-    // frozen while we try to decide about a firing event.  This is
-    // fast enough that it should be barely perceptible to the user.
-    // The synthetic firing event should trigger almost immediately
-    // upon releasing the plunger, from the user's perspective.
-    //
-    // The big danger with this approach is "false positives":
-    // mistaking manual motion under the user's control for a possible 
-    // firing event.  A false positive would produce a highly visible 
-    // artifact, namely the on-screen plunger freezing in place while 
-    // the player moves the real plunger.  The strategy we use makes it 
-    // almost impossible for this to happen long enough to be 
-    // perceptible.  To fool the system, you have to accelerate the 
-    // plunger very steadily - with about 5ms granularity.  It's
-    // really hard to do this, and especially unlikely that a user
-    // would do so accidentally.
-    //
-    // FIRING STATE VARIABLE
-    //
-    // The firing states are:
-    //
     //   0 - Default state.  We report the real instantaneous plunger 
     //       position to the joystick interface.
     //
-    //   1 - Phase 1 - acceleration
+    //   1 - Possible release in progress.  We enter this state when
+    //       we see the plunger start to move forward, and stay in this
+    //       state as long as we see *accelerating* forward motion.
     //
     //   2 - Firing event started.  We report the "bounce" position for
     //       a minimum time.
@@ -2871,11 +2789,12 @@
     //
     int firing;
     
-    // Position/timestamp at start of firing phase 1.  We freeze the
-    // joystick reports at this position until we decide whether or not 
-    // we're actually in a firing event.  This isn't set until we're
-    // confident that we've been in the accleration phase for long
-    // enough; pos is non-zero when this is valid.
+    // Position/timestamp at start of firing phase 1.  When we see a
+    // sustained forward acceleration, we freeze joystick reports at
+    // the recent local maximum, on the assumption that this was the
+    // start of the release.  If this is zero, it means that we're
+    // monitoring accelerating motion but haven't seen it for long
+    // enough yet to be confident that a release is in progress.
     PlungerReading f1;
     
     // Position/timestamp at start of firing phase 2.  The position is
@@ -2886,7 +2805,7 @@
     
     // Position/timestamp of start of stability window during phase 3.
     // We use this to determine when the plunger comes to rest.  We set
-    // this at the beginning of phase 4, and then reset it when the 
+    // this at the beginning of phase 3, and then reset it when the 
     // plunger moves too far from the last position.
     PlungerReading f3s;
     
@@ -2968,7 +2887,7 @@
         {                
             int znew = plungerReader.getPosition();
             const int cockThreshold = JOYMAX/3;
-            const uint16_t pushThreshold = uint16_t(-JOYMAX/3.0 * cfg.plunger.zbLaunchBall.pushDistance/1000.0 * 65535.0);
+            const int pushThreshold = int(-JOYMAX/3.0 * cfg.plunger.zbLaunchBall.pushDistance/1000.0);
             int newState = lbState;
             switch (lbState)
             {
@@ -3153,7 +3072,7 @@
     js.disconnect();
     
     // wait a few seconds to make sure the host notices the disconnect
-    wait(5);
+    wait(2.5f);
     
     // reset the device
     NVIC_SystemReset();
@@ -3208,7 +3127,7 @@
 // (helpful for installing and setting up the sensor and light source)
 bool reportPix = false;
 uint8_t reportPixFlags;    // pixel report flag bits (see ccdSensor.h)
-uint8_t reportPixVisMode;  // pixel report visualization mode (see ccdSensor.h)
+uint8_t reportPixVisMode;  // pixel report visualization mode (not currently used)
 
 
 // ---------------------------------------------------------------------------
@@ -3529,17 +3448,6 @@
 
 // ---------------------------------------------------------------------------
 //
-// Pre-connection diagnostic flasher
-//
-void preConnectFlasher()
-{
-    diagLED(1, 1, 0);
-    wait(0.05);
-    diagLED(0, 0, 0);
-}
-
-// ---------------------------------------------------------------------------
-//
 // Main program loop.  This is invoked on startup and runs forever.  Our
 // main work is to read our devices (the accelerometer and the CCD), process
 // the readings into nudge and plunger position data, and send the results
@@ -3562,10 +3470,6 @@
     // initialize the diagnostic LEDs
     initDiagLEDs(cfg);
 
-    // set up the pre-connected ticker
-    Ticker preConnectTicker;
-    preConnectTicker.attach(preConnectFlasher, 3);
-
     // we're not connected/awake yet
     bool connected = false;
     Timer connectChangeTimer;
@@ -3599,10 +3503,26 @@
     
     // Create the joystick USB client.  Note that we use the LedWiz unit
     // number from the saved configuration.
-    MyUSBJoystick js(cfg.usbVendorID, cfg.usbProductID, USB_VERSION_NO, true, cfg.joystickEnabled, kbKeys);
-    
-    // we're now connected - kill the pre-connect ticker
-    preConnectTicker.detach();
+    MyUSBJoystick js(cfg.usbVendorID, cfg.usbProductID, USB_VERSION_NO, false, 
+        cfg.joystickEnabled, kbKeys);
+        
+    // Wait for the connection
+    Timer connectTimer;
+    connectTimer.start();
+    while (!js.configured())
+    {
+        // show one short yellow flash at 2-second intervals
+        if (connectTimer.read_us() > 2000000)
+        {
+            // short yellow flash
+            diagLED(1, 1, 0);
+            wait(0.05);
+            diagLED(0, 0, 0);
+            
+            // reset the flash timer
+            connectTimer.reset();
+        }
+    }
     
     // Last report timer for the joytick interface.  We use the joystick timer 
     // to throttle the report rate, because VP doesn't benefit from reports any 
@@ -3956,17 +3876,46 @@
         }
         
         // if we're disconnected, initiate a new connection
-        if (!connected && !js.isConnected())
+        if (!connected)
         {
-            // show connect-wait diagnostics
-            diagLED(0, 0, 0);
-            preConnectTicker.attach(preConnectFlasher, 3);
+            // The "connected" variable means that we're either disconnected
+            // or that the connection has been suspended (e.g., the host is in 
+            // a sleep mode).  If the connection was lost entirely, explicitly
+            // initiate a reconnection.
+            if (!js.isConnected())
+                js.connect(false);
+            
+            // set up a timer to monitor the reboot timeout
+            Timer rebootTimer;
+            rebootTimer.start();
             
-            // wait for the connection
-            js.connect(true);
-            
-            // remove the connection diagnostic ticker
-            preConnectTicker.detach();
+            // wait for reconnect or reboot
+            connectTimer.reset();
+            connectTimer.start();
+            while (!js.isConnected() || js.isSuspended())
+            {
+                // show a diagnostic flash every 2 seconds
+                if (connectTimer.read_us() > 2000000)
+                {
+                    // flash once if suspended or twice if disconnected
+                    for (int j = js.isConnected() ? 1 : 2 ; j > 0 ; --j)
+                    {
+                        // short red flash
+                        diagLED(1, 0, 0);
+                        wait(0.05f);
+                        diagLED(0, 0, 0);
+                        wait(0.05f);
+                    }
+                    
+                    // reset the flash timer
+                    connectTimer.reset();
+                }
+                
+                // if the disconnect reboot timeout has expired, reboot
+                if (cfg.disconnectRebootTimeout != 0 
+                    && rebootTimer.read() > cfg.disconnectRebootTimeout)
+                    reboot(js);
+            }
         }
 
     // $$$
@@ -3988,26 +3937,7 @@
         // provide a visual status indication on the on-board LED
         if (calBtnState < 2 && hbTimer.read_us() > 1000000) 
         {
-            if (!newConnected)
-            {
-                // suspended - turn off the LED
-                diagLED(0, 0, 0);
-
-                // show a status flash every so often                
-                if (hbcnt % 3 == 0)
-                {
-                    // disconnected = short red/red flash
-                    // suspended = short red flash
-                    for (int n = js.isConnected() ? 1 : 2 ; n > 0 ; --n)
-                    {
-                        diagLED(1, 0, 0);
-                        wait(0.05);
-                        diagLED(0, 0, 0);
-                        wait(0.25);
-                    }
-                }
-            }
-            else if (jsOKTimer.read() > 5)
+            if (jsOKTimer.read() > 5)
             {
                 // USB freeze - show red/yellow.
                 // Our outgoing joystick messages aren't going through, even though we