henryhanselscott
Posts: 107
Joined: Sun Jan 18, 2015 1:31 pm

Threading and GPIO ?

Tue Nov 03, 2015 12:02 pm

I have a project where it would be beneficial to control and read GPIO pins in the background. For instance, one of my GPIO pins would be used to trigger an ultrasonic sensor and then another another used to read the response time from the sensor. I would like to do this in the back ground continuously while my script performs other tasks that may take too much time for the ultrasonic sensor readings to be accurate if it is in my main thread. In another application, I would like to count encoder pulses (relatively slow) while the main code performs other task. Variables would only be read by the main thread so that no two threads would be writing data to the same variable. Is this possible with the Rpi2 and would this be the preferred method if it is?

Thanks,
Henry

User avatar
joan
Posts: 14681
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Threading and GPIO ?

Tue Nov 03, 2015 12:51 pm

What you suggest is probably the most sensible way.

I suspect that if you use Python and (GPIO) callbacks what you suggest will automatically happen in the background. Certainly my pigpio Python module (and the pigpio C libraries) have a separate thread dedicated to callbacks.

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Threading and GPIO ?

Tue Nov 03, 2015 3:18 pm

joan wrote:What you suggest is probably the most sensible way.

I suspect that if you use Python and (GPIO) callbacks what you suggest will automatically happen in the background. Certainly my pigpio Python module (and the pigpio C libraries) have a separate thread dedicated to callbacks.
i think it depends on what you want to do. For example who triggers the "triggering" gpio?
if this is something you do within your main thread when you need it, as joan says i think you can do everything using callbacks (for example, you can set up 2 callbacks one checking the trigger and one checking the response - what's the format of the response?)
if you need the trigger to be "continuos", perhaps it's better with something different.
So please be more specific :)

Return to “General discussion”