/ src / hal / components / knob2float.comp
knob2float.comp
 1  //   This is a component for EMC2 HAL
 2  //   Copyright 2007 John Kasunich <jmkasunich AT sourceforge DOT net>
 3  //
 4  //   This program is free software; you can redistribute it and/or modify
 5  //   it under the terms of the GNU General Public License as published by
 6  //   the Free Software Foundation; either version 2 of the License, or
 7  //   (at your option) any later version.
 8  //
 9  //   This program is distributed in the hope that it will be useful,
10  //   but WITHOUT ANY WARRANTY; without even the implied warranty of
11  //   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  //   GNU General Public License for more details.
13  //
14  //   You should have received a copy of the GNU General Public License
15  //   along with this program; if not, write to the Free Software
16  //   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  
18  component knob2float "Convert counts (probably from an encoder) to a float value";
19  
20  pin in s32 counts "Counts";
21  pin in bit enable "When TRUE, output is controlled by count, when FALSE, output is fixed";
22  pin in float scale "Amount of output change per count";
23  pin out float out "Output value";
24  
25  param rw float max_out=1.0 "Maximum output value, further increases in count will be ignored";
26  param rw float min_out=0.0 "Minimum output value, further decreases in count will be ignored";
27  
28  option data knob2float_data;
29  
30  function _;
31  license "GPL";
32  ;;
33  
34  typedef struct {
35      long old_counts;
36      double old_out;
37  } knob2float_data;
38  
39  FUNCTION(_) {
40      long delta_counts;
41      double tmp_out;
42  
43      if ( min_out > max_out ) {
44  	min_out = max_out;
45      }
46      delta_counts = counts - data.old_counts;
47      if ( enable ) {
48  	tmp_out = data.old_out + delta_counts * scale;
49  	if ( tmp_out > max_out ) {
50  	    data.old_out = max_out;
51  	} else if ( tmp_out < min_out ) {
52  	    data.old_out = min_out;
53  	} else {
54  	    data.old_out = tmp_out;
55  	}
56      }
57      out = data.old_out;
58      data.old_counts += delta_counts;
59  }