1

I am trying to get the Raspberry Pi to shut down when a GPIO input is triggered. I have a c version of a small program and a python version which both do what I want to do but both cause high CPU load.

The c example:

#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (void)
{
    wiringPiSetup ();
    pinMode (5, INPUT);
    for(;;)
    {
        if(digitalRead (5) == HIGH)
        {
                printf("Sleepy Pi requesting shutdown on pin 24\n");
                system("sudo shutdown -h now");
                break;
         }
     }
     usleep(50000);
     return 0;
}

Here the example in python:

#!/usr/bin/python

import RPi.GPIO as GPIO
import os, time

GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, GPIO.HIGH)
print ("[Info] Telling Sleepy Pi we are running pin 25")

while True:
        if (GPIO.input(24)):
                print ("Sleepy Pi requesting shutdown on pin 24")
                os.system("sudo shutdown -h now")
                break
time.sleep(5)

Is this the right approach to what I am trying to do or is there some other way getting this done without causing high CPU load ?

Kind Regards Jan

goldilocks
  • 56,430
  • 17
  • 109
  • 217
Jan P.
  • 13
  • 2
  • 1
    If you want to do your own; Rather than polling, create a process which waits for an interrupt, then run it as a background process. This will consume minimal resources. – Milliways Nov 19 '17 at 10:45
  • There are many similar poweroff questions on this site. The process I use is https://raspberrypi.stackexchange.com/a/42945/8697, although if I were starting again I would explore the inbuilt `gpio-shutdown` which should do this (although I have not tried it). – Milliways Nov 19 '17 at 11:53

1 Answers1

2

Put a small delay in each while loop. Perhaps a sleep of a tenth or a hundredth of a second. That will test the GPIO 10 or 100 times a second but still give plenty of time for other activities.

joan
  • 67,803
  • 5
  • 67
  • 102