# Count time between two pulses in nano seconds

How can i count time between two pulses in nano seconds by using raspberry pi?

• how far apart are the pulses? – jsotola Oct 26 '18 at 21:41

As @joan said, you could write a C program or a program in a another language that measures subtracts the time at first pulse from the time at second pulse. This would be very easy.

Keep in mind, though, that the raspberry pi board might not be the best thing for measuring exact times. First, because the oscillator (internal clock) itself is not designed to be extremely accurate (it's not the most accurate kind) and second, because the raspberry pi has many processes running at once, your program (depending on how you write it) might not be able to record the time exactly when the second pulses happens. So if extreme accuracy is necessary for your purposes, you might want to consider using a good oscillator or RTC (real-time clock).

In C++, you could use the `chrono` library to measure the time between pulses. Check out this article

This might work in python (although I think C++ might be a bit more accurate):

``````import time
start = 0

def pulse_1(): # call pulse_1() when the first pulse happens
start = time.time()

def pulse_2():
end = time.time()
difference = end - start
difference_nanoseconds = difference * 1,000,000,000 # 1 billion nanoseconds in a second
print("The duration between the first and second pulse was {0} nanoseconds.".format(difference_nanoseconds))
``````
• If resolution - the rate at which the change of state of the GPIO pin can be read - is in the tens of microseconds (which other answers here suggest) the accuracy of the the oscillator is really not a concern. – Ghanima Oct 26 '18 at 19:29
• True @Ghanima , but if the duration needs to be measured accurately in nanoseconds, would the pi's built-in oscillator be steady/constant enough? I don't know much about oscillators... – scitronboy Oct 26 '18 at 23:42

You can't.

If you want to try write a C program and record the time at pulse 1 and then pulse 2. Subtract to get the time difference.