attachInterrupt and UltraSonicSensors

Good Evening together,

I am currently trying to read my Ultrasonic sensor with an "attachIntterupt" function. But somehow it seems to just count the time, instead of telling me the durration of my interrupt. Any suggestions anyone?
I am kind of new to the arduino, so it would be great if someone could explain in "easy words" what was wrong :slight_smile:

Here the code:

volatile long unsigned time;
volatile long unsigned Echo=2;
volatile long unsigned Trigger=36;
boolean flag;

void pinChange ()
{
  time = micros();
  flag = true;
}

void setup ()
{
  Serial.begin(9600);
  pinMode(Trigger, OUTPUT);
  pinMode(Echo, INPUT);
  digitalWrite(Echo, HIGH);
  attachInterrupt(0,pinChange,HIGH);
  
}

void loop()
{
  digitalWrite(Trigger, LOW);
  delayMicroseconds(2);
  digitalWrite(Trigger, HIGH);
  delayMicroseconds(10);

  
  if (flag)
  {
  Serial.print(time);
  Serial.print("\n");  
  flag = false;
  time = 0;
  delay(100); 
  }
}

And here the output:

540
1004
101772
202112
302552
402996
503440
603892
704344
804804
905244
1005688
1106136
1206628

Looking forward knowing what's wrong :slight_smile:

Thanks, notoriou5

You don't need to use interrupts for this. If I remember correctly, pulseIn() should do what you want.

All you need to do is make a simple if/else statement to not let the serial monitor get flooded with data.
Something like this:
Where count is the value returned from pulseIn(...) and lastcount is of type long (both are type long).

if(count != lastCount)
{
Serial.println(count);
lastCount = count;
}

I already know the pulseIn function... But it is to slow for the project where I would like to use it. Is there no way to read the time of how long my Interrupt was HIGH?

Thanks

Not that I know of.

Is there no way to read the time of how long my Interrupt was HIGH?

If you use CHANGE as the type, then in the interrupt handler you can record when the pin goes HIGH or when it goes LOW, by determining the state of the pin at the time the interrupt happens.

But, the NewPing library does all that for you. Why aren't you using it?