I want to time the duration a input GPIO pin is HIGH with microsecond precision.

I tried while loop with time.time() , but it adds a lot of rogue delays.

How can I achieve this in python?

  • 2
    python and microsecond do not usually belong to the same sentence =) you'd better think about using C/C++ instead. – lenik May 11 '13 at 9:54

You'd be best implementing this in a C library, it could be trivially done with WiringPi and then wrapped in a Python wrapper to return the number of microseconds. I'd suggest a function prototype of:


Where GPIO_PIN is the input we're watching, HIGH/LOW is the state we want to time, and TIMEOUT is the number of millis or micros we would want to wait before returning a failure code- or the C call could hang your Python script indefinitely.

At the moment the waitForInterrupt function in wiringPi, and subsequently wiringPi2-Python, is a lot like this, it returns the result of a poll() call which ( although I'm not sure ) could very well be the number of milliseconds or microseconds it has waited.

Unfortunately waitForInterrupt doesn't necessarily time how long the pin is in a specific state, but just when the next state change is. But it's close!

Out of interest, why are you attempting to time the input? I can certainly think of reasons to do so ( infra-red signals spring immediately to mind! ).

| improve this answer | |
  • I didn't know there was a wiringpi 2... let me try it out... and I am doing ultrasound... :) – ATOzTOA May 10 '13 at 17:15
  • I couldn't find waitForInterrupt() in python wiringpi2, only in C. – ATOzTOA May 11 '13 at 4:31
  • I time the input to determine what letter is trasmitted; I'm working on a project to make raspberry pies communicate. – Matthew Aug 10 '13 at 17:34

It is doable in Python without C. You will get down to 10us approx on the B+ model with tight code. Use wiringpi.micros() -- documented only in C, but available in python (undocumented). I use it all the time in complex code. For wiringpi, see https://pypi.python.org/pypi/wiringpi2 -- and beginners install guide, see http://raspi.tv/how-to-install-wiringpi2-for-python-on-the-raspberry-pi#install .. This is an example of it's general use in Python..

import wiringpi2
for n1 in range(1,10): print wiringpi2.micros()
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.