I’m writing a Python extension for the functions provided by a GPIO driver. I made progress pretty easily on the simple functions like set_bit() and clear_bit(). But now I need to implement wait_int(), which sleeps until an event is sensed on an input pin and I’m not sure the right way to orchestrate this between c and python. Here’s a stripped down example of using the function in c:
main(int argc, char *argv[])
{
int c;
//some setup like testing port availability, clearing interrupts, etc
...
while(1)
{
printf("**\n");
c = wait_int(1);//sleeps until an interrupt occurs on chip 1
if(c > 0) {
printf("Event sense occured on Chip 1 bit %d\n",c);
++event_count;
}
else
break;
}
printf("Event count = %05d\r",event_count);
printf("\nExiting Now\n");
}
Do I just expose wait_int pretty much directly and then do whatever the python equivalent idiom of the infinite loop is? There’s also some debouncing that needs to be done. I’ve done it in c but maybe it could be moved to the python side.
You don’t need to do anything on the Python side, you can just treat it as a synchronous function. On the C side, you just block until the event occurs, possibly allowing interrupts. For example, take a look at the implementation of the
time.sleepfunction:All it does is use the
selectfunction to sleep for the given period of time.selectis used so that if any signal is received (such asSIGINTfrom hitting Ctrl+C at the terminal), the system call is interrupted and control returns to Python.Hence. your implementation can just call the C
wait_intfunction. If it supports being interrupted by signals, than great, that will allow the user to interrupt it by hitting Ctrl+C, but make sure to react appropriately such that an exception will be thrown (I’m not certain of how this works, but it looks like returningNULLfrom the top-level function (time_sleepin this example) will do the trick).Likewise, for better multithreaded performance, surround the wait call with a pair of
Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADSmacros, but this is not required, especially if you’re not using multithreading at all.