updown.comp
1 component updown "Counts up or down, with optional limits and wraparound behavior"; 2 pin in bit countup "Increment count when this pin goes from 0 to 1"; 3 pin in bit countdown "Decrement count when this pin goes from 0 to 1"; 4 pin in bit reset "Reset count when this pin goes from 0 to 1"; 5 pin out s32 count "The current count"; 6 param rw bit clamp "If TRUE, then clamp the output to the min and max parameters."; 7 param rw bit wrap "If TRUE, then wrap around when the count goes above or below the min and max parameters. Note that wrap implies (and overrides) clamp."; 8 param rw s32 max = 0x7FFFFFFF "If clamp or wrap is set, count will never exceed this number"; 9 param rw s32 min "If clamp or wrap is set, count will never be less than this number"; 10 variable int oldup; 11 variable int olddown; 12 variable int first = 1; 13 function _ nofp "Process inputs and update count if necessary"; 14 license "GPL"; 15 16 ;; 17 18 FUNCTION(_) { 19 hal_s32_t temp_count = count; 20 if (first) { 21 oldup=countup; 22 olddown=countdown; 23 first=0; 24 } 25 if ((!oldup) && (countup)) { // positive edge, count up 26 temp_count++; 27 } 28 if ((!olddown) && (countdown)) { // positive edge, count down 29 temp_count--; 30 } 31 if (reset) { 32 temp_count=0; 33 } 34 if (wrap) { 35 if (temp_count > max) 36 temp_count = min; 37 else if (temp_count < min) 38 temp_count = max; 39 } else if (clamp) { 40 if (temp_count > max) 41 temp_count = max; 42 else if (temp_count < min) 43 temp_count = min; 44 } 45 count = temp_count; 46 oldup = countup; 47 olddown = countdown; 48 }