component toggle2nistv2 "toggle button to nist logic";

description
"""
toggle2nist can be used with a momentary push button connected to a
toggle component to control a device that has seperate on and off inputs
and has an is-on output.
If in changes states via the toggle output
  If is-on is true then on is false and off is true.
  If is-on is false the on true and off is false.
""";

pin_ptr in  bit in;
pin_ptr in  bit is_on;
pin_ptr out bit on;
pin_ptr out bit off;
variable hal_bit_t old_in = false;
variable hal_bit_t to_state=false;
function _;
license "GPL";
;;
FUNCTION(_)
{
if (gb(in) != old_in) /* a toggle has occurred */ {
    if (gb(is_on)) {   /* turn OFF if it's on */
        sb(on, false);
        sb(off, true);
        to_state=false;
    }
    else if (!gb(is_on)) { /* turn ON if it's off */
        sb(on, true);
        sb(off, false);
        to_state=true;
    }
}
else {
/* reset pins when we see the desired state */
    if (to_state == gb(is_on)) {
        sb(on, false);
        sb(off, false);
    }
}
old_in = gb(in);

return 0;

}
