title: Efficient threshold checks of absolute value in embedded C
body: <p>I thinking about a efficient way of implementing a threshold check (with optional hysteresis and delay).</p>
  
  <p><strong>Requirement/situation:</strong></p>
  
  <p>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)</p>
  
  <p>Considering hysteresis, There shall be different set and reset vlaues:
  e.g. for the over pressure case a set threshold of pressure <code>p_set</code> (error bit gets set) and a reset threshold of <code>p_reset &lt;= p_set</code>.
  Same applies for the unde pressure but here <code>p_reset &gt;= p_set</code>, which causes the comparison operator to invert: </p>
  
  <pre><code>// Over pressure detection
  if (pressure &gt; overPressureSetThld){
    // Over pressure -&gt; set error bit
  else if (pressure &lt; overPressureResetThld){
    // Reset over pressure error bit
  }
  
  // Under pressure detection
  if (pressure &lt; underPressureSetThld){              // Inverted comparison operator
    // Under pressure -&gt; set error bit
  else if (pressure &gt; underPressureResetThld){       // Inverted comparison operator
    // Reset under pressure error bit
  </code></pre>
  
  <p><strong>Alternatives:</strong></p>
  
  <p>Thinking about this, I see two alternatives:</p>
  
  <ol>
  <li>Implement it straigt forward like above -> bigger code size/"duplicate" code (especially with a delay considered)</li>
  <li><p>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.:</p>
  
  <p><code>if (abs(pressure - REFRENCE_PRESSURE) &gt; relSetThld){          // Threshold relative to reference and positive 
    // Set over/under pressure error bit
  else if (abs(pressure - REFRENCE_PRESSURE) &lt; relResetThld){    // Threshold relative to reference and positive 
    // Reset over/under pressure error bit</code></p></li>
  </ol>
  
  <p><strong>Question:</strong></p>
  
  <p>I tend to use alternative 2 but I'm asking myself (and you) if there is an better way to do this.
  Suggestions welcome!</p>
  
  <p>Best
  Christoph</p>