Skip to content

pulseIn() returns incorrect values when called soon after Serial.print() #34

Closed
@per1234

Description

@per1234

Arduino megaAVR Boards @ c8f8d76, ArduinoCore-API @ arduino/ArduinoCore-API@e1eb8de, Arduino IDE Hourly Build 2019/04/18 12:33, Windows 10 64 bit

If pulseIn() is called soon after Serial.print(), the values returned are incorrect.

When the below code is run on the Uno WiFi Rev2 with a ~1 kHz square wave input on pin 2:

const byte pulsePin = 2;
unsigned long pulseDuration;

void setup() {
  pinMode(pulsePin, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.print("Pulse duration: ");
  Serial.println(pulseDuration);
  pulseDuration = pulseIn(pulsePin, HIGH);
  delay(1000);
}

Serial Monitor shows:

Pulse duration: 0
Pulse duration: 507
Pulse duration: 466
Pulse duration: 2
Pulse duration: 2
Pulse duration: 2
Pulse duration: 5
Pulse duration: 22
Pulse duration: 302
Pulse duration: 514
Pulse duration: 506
Pulse duration: 509
Pulse duration: 2
Pulse duration: 8
Pulse duration: 123
Pulse duration: 323
Pulse duration: 2
Pulse duration: 210

...and so on.

If I call noInterrupts() or Serial.flush() before calling pulseIn(), the values returned are as expected (~500).

I know there is a comment on the pulseIn() definition:

* This function performs better with short pulses in noInterrupt() context

So maybe this is simply a matter of me misusing pulseIn()? I thought I would bring the subject up here because I don't see these erratic return values when I run the same code on Uno, MKR1000, or Due.

If there is nothing that can be changed in the code to make pulseIn() work better in this situation, I can instead improve the pulseIn() reference page, which currently makes no mention of disabling interrupts.

Originally reported at:
https://forum.arduino.cc/index.php?topic=613933

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions