python - Efficiency of infinite loop to service GPIO -


i'm using python on raspbian (a type of linux) on raspberry pi (an embedded processor board) monitor gpio inputs.

see simplified version of code below. have infinite loop in python script waiting happen on gpio i/p. correct way it? i.e. mean cpu running @ full whack going round loop, leaving no cpu cycles other stuff? need running other things in parallel (e.g. browser).

also happens if cpu busy doing else , gpio i/p changes? gpio event stored somewhere serviced, or lost?

is there better way of doing this?

(for answers, please note i'm new linux, , v. new python , real-time programming)

#!/usr/bin/python import rpi.gpio gpio gpio.setmode(gpio.board) gpio.setup(16, gpio.in, pull_up_down=gpio.pud_up)  def buttonhandler(channel):     print "button pressed " + str(channel)     # stuff here  gpio.add_event_detect(16, gpio.falling, callback=buttonhandler, bouncetime=200)  while true:     pass 

yes, doing while true: pass burn 100% of cpu (or close possible) doing nothing.

from understand (hopefully documented somewhere), rpi.gpio module spawns background thread waits on gpio , calls callback function each event. main thread has nothing do. if want run service, make sleep long periods of time. if want run interactively (in case want easier cancel), sleep shorter periods of time, maybe 0.5 seconds, , add way exit loop.

it nicer if gpio select in main thread, or handle gpio background thread can join, either of burn no cpu @ all. however, module doesn't seem designed in way make easy.

however, looking @ the source, there wait_for_edge method. presumably loop around gpio.wait_for_edge instead of setting callback. without documentation, , without device test myself, i'm not sure i'd want recommend novice.

meanwhile:

also happens if cpu busy doing else , gpio i/p changes? gpio event stored somewhere serviced, or lost?

well, while your thread isn't doing anything, gpio background thread seems waiting on select, , select won't let miss events. (based on name, wait_for_edge function sounds might edge-triggered rather level-triggered, however, part of reason i'm wary of recommending it.)


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -