0

I have a simple script I found that I'm using to deactivate xscreensaver via PIR motion sensor. It's using nearly 40% of my CPU when it runs. How can I calm it down?

#!/usr/bin/env python
import RPi.GPIO as GPIO
import os
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
while True:
    if GPIO.input(17): # Waits for motion signal from PIR on GPIO pin 17 then complete rest and exit
        print ("deactivating screensaver")
        os.system("xscreensaver-command -deactivate")
3

Right now you are looping as fast as the CPU can process the loop. Try adding a sleep to back off the CPU. It is unlikely that you need to check the motion sensor as often as you are

#!/usr/bin/env python

import RPi.GPIO as GPIO
import os
import time

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
while True:
    if GPIO.input(17): # Waits for motion signal from PIR on GPIO pin 17 then complete rest and exit
        print ("deactivating screensaver")
        os.system("xscreensaver-command -deactivate")
    time.sleep(1) # sleeps for 1 second
  • I'm not so familiar with this but isn't there a possibility with exceptions? – Ingo Feb 24 '18 at 18:53
  • @ingo possibility of what? – Steve Robillard Feb 24 '18 at 18:55
  • I mean, maybe there is a way to use exceptions in python instead of polling with sleep. I don't know if RPi.GPIO can raise exceptions, maybe with use of built-in Exceptions? – Ingo Feb 25 '18 at 12:55
  • 1
    @Ingo: No... Exceptions are for when bad things happen. The keyword you're looking for is interrupts. – Jacobm001 Feb 26 '18 at 4:29
  • @Jacobm001 Yes, in higher programming languages interrupts are called exception because there is more done than interrupt a program flow by the cpu, jump to a interrupt vector and push the program status to the stack ;-) And exceptions not only used for error conditions. But we get off topic ... – Ingo Feb 26 '18 at 9:44

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.