Rewrite to improve reliability

The original code would occasionally result in random switches being triggered or the Arduino hanging.  This revised version is much more reliable.