Accurate control of button repeat rate

From FlightGear wiki
Revision as of 06:14, 22 July 2013 by Macnab (talk | contribs)
Jump to navigation Jump to search
WIP.png Work in progress
This article or section will be worked on in the upcoming hours or days.
See history for the latest developments.

Background

Sometimes you might want to have control over the speed that a repeatable button works - maybe you want it to repeat exactly every 1.325 seconds, or you just want to slow it down. At the end of this article you will be shown how to use a button to set the frequency of a radio. This is certainly a time when the default (system) repeat rate of a button is too fast.

How it is done

The secret is in having a method of preventing a button from repeating until our chosen time has elapsed. It is possible, but messy, especially if you are doing this with a number of buttons, to do it inside the code for each button. It is much better to create a new type of button code. For this we need a class, and then create instances of this class for each controlled button. This, incidentally, is OOP, or Object Oriented Programming.

Here is thew code to create the new class. It is called timedControl. I have added (unnecessary) open lines between each member of the class to make understanding easier.

var timedControl = {
      last_busy: 0,

      timeout_dur: 1.0,

      new: func() {
          return { parents:[me] };
      },

      _call: func(fn, arg) {
        if (!arg) { me.last_busy = 0; me.tap = 0; return; } # Stop if arg = 0. Clear values.
        if (me.timeout_dur != nil) {
          if ((me.timeout_dur == -1) and me.last_busy != 0) return; # One-shot
          var time = systime();
          if (time < me.timeout_dur + me.last_busy) return; # check timeout_dur has elapsed
          me.last_busy = time;
        }
        return call(fn, [arg], me);
      }
};