Move GPIO writes to a separate thread. Fix some bugs.