@@ -325,7 +325,7 @@ bool Wippersnapper_AnalogIO::encodePinEvent(
325
325
*/
326
326
/* *********************************************************/
327
327
void calculateHysteresis (analogInputPin pin, uint16_t pinValRaw,
328
- uint16_t * pinValThreshHi, uint16_t * pinValThreshLow) {
328
+ uint16_t & pinValThreshHi, uint16_t & pinValThreshLow) {
329
329
// All boards ADC values scaled to 16bit, in future we may need to
330
330
// adjust dynamically
331
331
uint16_t maxDecimalValue = 65535 ;
@@ -342,10 +342,19 @@ void calculateHysteresis(analogInputPin pin, uint16_t pinValRaw,
342
342
} else {
343
343
CURRENT_HYSTERISIS = maxDecimalValue * DEFAULT_HYSTERISIS * 4 ;
344
344
}
345
-
346
- // get the threshold values for previous pin value
347
- *pinValThreshHi = pin.prvPinVal + CURRENT_HYSTERISIS;
348
- *pinValThreshLow = pin.prvPinVal - CURRENT_HYSTERISIS;
345
+ // get the threshold values for previous pin value, but don't overflow
346
+ float overflowableThHi = pin.prvPinVal + CURRENT_HYSTERISIS;
347
+ float overflowableThLow = pin.prvPinVal - CURRENT_HYSTERISIS;
348
+ if (overflowableThHi > maxDecimalValue) {
349
+ pinValThreshHi = maxDecimalValue;
350
+ } else {
351
+ pinValThreshHi = overflowableThHi;
352
+ }
353
+ if (overflowableThLow < 0 ) {
354
+ pinValThreshLow = 0 ;
355
+ } else {
356
+ pinValThreshLow = overflowableThLow;
357
+ }
349
358
}
350
359
351
360
/* *********************************************************/
@@ -425,14 +434,8 @@ void Wippersnapper_AnalogIO::update() {
425
434
426
435
// check if pin value has changed enough
427
436
uint16_t pinValThreshHi, pinValThreshLow;
428
- calculateHysteresis (_analog_input_pins[i], pinValRaw, &pinValThreshHi,
429
- &pinValThreshLow);
430
- WS_DEBUG_PRINT (" Returned pinValThreshHi: " );
431
- WS_DEBUG_PRINTLN (pinValThreshHi);
432
- WS_DEBUG_PRINT (" Returned pinValThreshLow: " );
433
- WS_DEBUG_PRINTLN (pinValThreshLow);
434
- WS_DEBUG_PRINT (" Current pinValRaw: " );
435
- WS_DEBUG_PRINTLN (pinValRaw);
437
+ calculateHysteresis (_analog_input_pins[i], pinValRaw, pinValThreshHi,
438
+ pinValThreshLow);
436
439
437
440
if (_analog_input_pins[i].prvPeriod == 0 ||
438
441
pinValRaw > pinValThreshHi || pinValRaw < pinValThreshLow) {
@@ -450,12 +453,10 @@ void Wippersnapper_AnalogIO::update() {
450
453
// mark last execution time
451
454
_analog_input_pins[i].prvPeriod = millis ();
452
455
453
- } else {
454
- // WS_DEBUG_PRINTLN("ADC has not changed enough, continue...");
456
+ } else { // ADC has not changed enough
455
457
continue ;
456
458
}
457
- // set the pin value in the digital pin object for comparison on next
458
- // run
459
+ // set the pin value in the digital pin object for comparison next run
459
460
_analog_input_pins[i].prvPinVal = pinValRaw;
460
461
}
461
462
}
0 commit comments