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?
Raspberry Pi Stack Exchange is a question and answer site for users and developers of hardware and software for Raspberry Pi. It only takes a minute to sign up.Sign up to join this community
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:
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! ).
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()