0

I have just started working with the GPIO library and I would like to have a clarification on the way the library works. It's about the usage of add_event_detect when a callback function is used. From the examples I've seen I understand that if one wants to use a callback function the main thread must run forever hence there is a

while True:

statement at the end. What I do not understand is why this is usually followed by a

time.sleep(xxx)

statement. Since sleep() causes the program execution to pause how can the callbacks keep getting triggered (e.g from a sensor event or button press?).Are the callbacks triggered independently of the main thread?

  • 1
    Usually you want a short sleep to allow other Pi processes to continue. Otherwise you’ll probably see 100% processor utilisation for your app. – CoderMike Apr 7 '18 at 17:25
1

You need the while loop to do something. You could use pass instead of the sleep but that would consume 100% of the CPU in a busy spin. The sleep consumes hardly any CPU resources. You could just as well sleep 60 seconds rather than 1 second.

If the while loop is absent the main thread will finish and force the other threads to finish as well.

The callbacks have their own thread of execution, so yes, they are triggered independently of the main thread.

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.