I thinking about a efficient way of implementing a threshold check (with optional hysteresis and delay).
Requirement/situation:
I want to check e.g. an non-negative value (e.g. absolute pressure) against an upper threshold and an lower threshold resulting in an over pressure error bit or an under pressure error bit respectively. There are going to be multiple set and reset thresholds. (I want to organize in an array)
Considering hysteresis, There shall be different set and reset vlaues:
e.g. for the over pressure case a set threshold of pressure p_set
(error bit gets set) and a reset threshold of p_reset <= p_set
.
Same applies for the unde pressure but here p_reset >= p_set
, which causes the comparison operator to invert:
// Over pressure detection
if (pressure > overPressureSetThld){
// Over pressure -> set error bit
else if (pressure < overPressureResetThld){
// Reset over pressure error bit
}
// Under pressure detection
if (pressure < underPressureSetThld){ // Inverted comparison operator
// Under pressure -> set error bit
else if (pressure > underPressureResetThld){ // Inverted comparison operator
// Reset under pressure error bit
Alternatives:
Thinking about this, I see two alternatives:
- Implement it straigt forward like above -> bigger code size/"duplicate" code (especially with a delay considered)
Compare relative values (substraction and abs, requires a reference pressure) -> reduced code size because only one if-elseif needed but higher runtime load e.g.:
if (abs(pressure - REFRENCE_PRESSURE) > relSetThld){ // Threshold relative to reference and positive // Set over/under pressure error bit else if (abs(pressure - REFRENCE_PRESSURE) < relResetThld){ // Threshold relative to reference and positive // Reset over/under pressure error bit
Question:
I tend to use alternative 2 but I'm asking myself (and you) if there is an better way to do this. Suggestions welcome!
Best Christoph