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")
0

1 Answer 1

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
7
  • I'm not so familiar with this but isn't there a possibility with exceptions?
    – Ingo
    Commented Feb 24, 2018 at 18:53
  • @ingo possibility of what? Commented Feb 24, 2018 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
    Commented Feb 25, 2018 at 12:55
  • 1
    @Ingo: No... Exceptions are for when bad things happen. The keyword you're looking for is interrupts.
    – Jacobm001
    Commented Feb 26, 2018 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
    Commented Feb 26, 2018 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.