How to measure the time a pin is HIGH in microseconds?

I am trying to understand how ultrasonic distance sensors work by coding a program to measure distance without any libraries, but at some point I need to read how long a pin has been HIGH in milcroseconds, how do I do that?

As I recall, the ultrasonic library returns the time in microseconds, not milliseconds. You need to do the same.

oops yeah, i mean microseconds and i am not using libraries

so do you mind telling me how to measure the time a pin is high? or basically pulse duration

How would you measure the time taken to complete a phone call?

  1. write down the start time
  2. call
  3. write down the end time
  4. subtract the start time from the end time

Also, it happens, the internet is awash with the 9 lines of code that do what you ask. Just look around.

You are missing the way the ultrasonic measurement is done. A trigger pulse and then wait for an echo. save the time the trigger pulse is sent and test for an echo. The difference in time, microseconds, is the time the pulse travels to the object and returns.

On this note, have you looked at the data sheet?

hmmm, my one is sending a pulse into the trig pin on the sensor for 20 microseconds and waiting for a response and the length of the pulse is the time taken for the sound to travel to an object and back and then using math like: distance = speed of sound * time / 2 am I correct?

I don't mean in that way, i meant what commands to use like: time = lengthOfPulse(pulse);

Oh, you want to use built in Arduino functions. Did you consult the language reference page?

oh, never knew about that sorry, are you able to tell me now?

That depends on what you mean by a 'library'. If you can use the built-in function digitalRead(EchoPin), certainly you can use the built-in function pulseIn(EchoPin, HIGH). That returns the pulse length in microseconds.

It's on this site.
https://www.arduino.cc/reference/en/

I don't see how that will help you "understand" the sensor, though...

oh thank you, looks very helpful

i will read more about that function, thanks john. and by "library" i mean that thing you install that makes using servos and LCD screens way easier

95% of the beginner projects that use the sensor borrow the same tired 9 lines of code, so you won't discover anything new there. I'm pretty sure it uses pulseIn().

i know how the sensor works but controlling it without the use of libraries will help me understand them better

How? You already know what the HIGH pulse signifies.

then i think "pulseIn()" is the thing that i was looking for. thank you

If that's all you need, great. It won't help you to understand the sensor at all. Read the data sheet for that.