Compare time differences instead of timestamps (#1648)

Comparing two results of millis() can result in erroneous
behavior when the value of millis() wraps around, which
happens after around 25 days of uptime. Comparing time
difference (by subtracting two timestamps) works well, provided
timestamps are not too old (less than 25 days old).
This commit is contained in:
flo-x authored and GitHub committed 2023-05-22 14:45:50 -05:00
1 parent 4b7b47c30c
commit 5b85c74230
1 file changed
+4 -3
+4 -3
View File
@@ -34,6 +34,8 @@
ADC_MODE(ADC_TOUT);
# endif
static int persistedadc = -1024; // so that the first reading will always be published
//Time used to wait for an interval before resending adc value
unsigned long timeadc = 0;
unsigned long timeadcpub = 0;
@@ -42,13 +44,12 @@ void setupADC() {
}
void MeasureADC() {
if (millis() > (timeadc + TimeBetweenReadingADC)) { //retrieving value of temperature and humidity of the box from DHT every xUL
if (millis() - timeadc > TimeBetweenReadingADC) { //retrieving value of temperature and humidity of the box from DHT every xUL
# if defined(ESP8266)
yield();
analogRead(ADC_GPIO); //the reliability of the readings can be significantly improved by discarding an initial reading and then averaging the results
# endif
timeadc = millis();
static int persistedadc;
int val = analogRead(ADC_GPIO);
int sum_val = val;
if (NumberOfReadingsADC > 1) { // add extra measurement for accuracy
@@ -60,7 +61,7 @@ void MeasureADC() {
if (isnan(val)) {
Log.error(F("Failed to read from ADC !" CR));
} else {
if (val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC || (MinTimeInSecBetweenPublishingADC > 0 && millis() > (timeadcpub + (MinTimeInSecBetweenPublishingADC * 1000UL)))) {
if (val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC || (MinTimeInSecBetweenPublishingADC > 0 && millis() - timeadcpub > (MinTimeInSecBetweenPublishingADC * 1000UL))) {
timeadcpub = millis();
Log.trace(F("Creating ADC buffer" CR));
StaticJsonDocument<JSON_MSG_BUFFER> jsonBuffer;