Problem with ESP8266 printing differences of millis()

I use a Wemos D1 (ESP8266) to detect pulses of a reed sensor of a water meter. To debug my code I want to know how long the pulses are. This is the relevant part of my code:

boolean pulseStartDetected = false;

boolean inPinLevel = HIGH;

unsigned long pulseStartTime = 0;
unsigned long pulseEndTime = 0;
unsigned long pulseDuration = 0;

- - -

void loop() {
  
  client.loop(); 
  inPinLevel = digitalRead(inPin);

  if (inPinLevel == LOW) {
    pulseStartDetected = true;
    pulseStartTime = millis();
  } 
  if ((inPinLevel == HIGH) && (pulseStartDetected)) {
    pulseEndTime = millis();
    pulseDuration = (unsigned long)(pulseEndTime - pulseStartTime);
    
    pulseCounter ++;
    pulseStartDetected = false;
    if (debug) {
      Serial.println("Pulse detected");
      Serial.print("Pulse Duration [ms]: ");
      Serial.println(pulseDuration);
    }
  }

- - -

  }

I have the problem that "Serial.println(pulseDuration)" always gives "0".
If I print "pulseStartTime" and "pulseEndTime" I always get reasonable values.
I also omitted the cast operator "(unsigned long)" (used for millis() overflow) - no difference.

if (inPinLevel == LOW && !pulseStartDetected) {?

Should this be?

if (inPinLevel == LOW and not pulseStartDetected) {

Sorry, @Juraj, you got it first!

&& works perfectly - the peaks are detected.
Arduino Reference
I only have problems to print out the peak duration.

I think you missed the point @Juraj and I are trying to make. Because your first if-condition is not precisely correct, pulseStartTime keeps getting updated. So it's always equal to pulseEndTime when you calculate the difference.

@jwru you should really give the "solution" mark to @juraj's post.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.