uilfut
Posts: 72
Joined: Sat Mar 03, 2018 1:20 am
Location: Toronto

waiting for GPIO button press eating resources

Thu Feb 14, 2019 9:28 pm

Hey guys

Running my script to wait for a GPIO button press (which prints some stats on al oled screen) takes my processor from 2% to 25%.

As soon as I press the button it goes down to 2% from 25% for 10 seconds while stats are displayed).

I have a simple while loop:

Code: Select all

while True:
    if GPIO.input(15):
        display_on_oled()


Can I do anything to make it use less resources?

Many thanks

Will

User avatar
B.Goode
Posts: 10356
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: waiting for GPIO button press eating resources

Thu Feb 14, 2019 9:34 pm

I have no idea if it would use less CPU, but the gpiozero python library module has a Button class that implements a wait_for_press() method. (A timeout can be specified.)

Worth a comparison?

mattmiller
Posts: 2243
Joined: Thu Feb 05, 2015 11:25 pm

Re: waiting for GPIO button press eating resources

Thu Feb 14, 2019 9:49 pm

Can I do anything to make it use less resources?
stick a small time.sleep() in the loop

Your loop is running around in a very small circle very fast wearing itself out :)

uilfut
Posts: 72
Joined: Sat Mar 03, 2018 1:20 am
Location: Toronto

Re: waiting for GPIO button press eating resources

Thu Feb 14, 2019 10:05 pm

(Thanks both for suggestions!)
mattmiller wrote:
Thu Feb 14, 2019 9:49 pm
Can I do anything to make it use less resources?
stick a small time.sleep() in the loop
Yes I thought of this - but if I had, say a time.sleep(2), would I have to hold the button down for up to 2 seconds before it registered?

Sorry if this is basic misunderstanding... :)

uilfut
Posts: 72
Joined: Sat Mar 03, 2018 1:20 am
Location: Toronto

Re: waiting for GPIO button press eating resources

Thu Feb 14, 2019 10:13 pm

uilfut wrote:
Thu Feb 14, 2019 10:05 pm
(Thanks both for suggestions!)
mattmiller wrote:
Thu Feb 14, 2019 9:49 pm
Can I do anything to make it use less resources?
stick a small time.sleep() in the loop
Yes I thought of this - but if I had, say a time.sleep(2), would I have to hold the button down for up to 2 seconds before it registered?
This fixed it, thank you... I just hold the button down until the screen comes on.

I wonder how small I can make the sleep interval....

User avatar
rpiMike
Posts: 1386
Joined: Fri Aug 10, 2012 12:38 pm
Location: Cumbria, UK

Re: waiting for GPIO button press eating resources

Thu Feb 14, 2019 10:54 pm

time.sleep(0.1) should work fine

Return to “Python”