PulseIn() Substitute needed!

Hello there!

I have a project that uses wireless serial.communication between two arduino's. However one of the arduino's is using the pulseIn() function for distance calculation from an ultrasonic sensor.

But the pulseIn() function is messing up my serial communication because it is a 'blocking' function.

So i wanted to know what substitute to use for pulseIn() that will not interrupt my serial communication that has to be uninterrupted the entire time the code is running (controlling a robot).\

Thank you!

you can use interrupt, or use an analog value as it does noot ned timing.just a simple capacitor.

Write your own using a global variable and micros() or millis().

Here is a sketch using an external interrupt on Pin 2

volatile unsigned long LastPulseTime;
int duration;
#define trigPin 7
#define echoPin 2
void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  attachInterrupt(0, EchoPinISR, CHANGE);  // Pin 2 interrupt on any change
void loop(){
  digitalWrite(trigPin, LOW); 
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  Serial.println(" cm");

void EchoPinISR() {
  static unsigned long startTime;

  if (digitalRead(2)) // Gone HIGH
    startTime = micros();
  else  // Gone LOW
  LastPulseTime = micros() - startTime;

Thank you!!!!

Thank you, cattledog!