Python digitalRead() built-in delay


#1

In building my interactive application that involves GrovePi+ buttons and RGB LCD display, I came upon a really annoying delay in processing my polling calls to digitalRead(). The delay (100ms per call) made my application unusable because there is a call to digitalRead() for every button. With just 4 buttons, I’m polling each button twice a second, which make for very poor feedback to the user and just reaction in general.

I looked at the source code, and found this:

# Arduino Digital Read
def digitalRead(pin):
	write_i2c_block(address, dRead_cmd + [pin, unused, unused])
	time.sleep(.1)
	n = read_i2c_byte(address)
	return n

Is there a reason why that sleep() call is 100ms? If I look at the C version of the same call, I see this:

//Read a digital value from a pin
int digitalRead(int pin)
{
	write_block(dRead_cmd,pin,0,0);
	usleep(10000);
	return read_byte();
}

The C version of the call pauses for only 10ms!

In my own testing in the Python code, I’ve been using 0.005 seconds (5ms) with very consistent results, no faults whatsoever. The app is now extremely responsive, and everything is happy.

Is there a reason why the delay is 100ms in the Python library, and 1/10th as much in the C library? What is a “safe” value? I used 5ms in my code half-expecting it to break or occasionally not be able to read the value, but it’s just been working fine to my surprise!

Thanks.


#2

Hey gabriel,
The C library uses a better low level I2C library which does a much better job of throttling the I2C packets than the python functions. Also, for simpler functions like digitalRead, the delay does not matter much so that’s why you were able to get way with a 5ms delay. However, we have a seen a lot of problems when you go down to that much of a delay and try to much more complex thing like using multiple sensors together. The delay which we recommend using is 50ms or more because the code works flawlessly in that case with all the sensors and all conditions.

-Karan