SkalTura
Posts: 8
Joined: Sun Oct 18, 2015 7:13 am
Location: Tilburg, The Netherlands

time.sleep outside while loop

Sun Oct 18, 2015 7:26 am

I'm a beginner with the Raspberry and Python and have a question about running a program that has the "time.sleep" command in it.

So, here's the program:

Code: Select all

import RPi.GPIO as GPIO
import time
import os

GPIO.setmode(GPIO.BOARD)
GPIO.setup(40, GPIO.OUT)
GPIO.output(40, True)
time.sleep(1)
GPIO.setup(38, GPIO.IN)
while True:
    if(GPIO.input(38)):
        os.system("sudo shutdown -h now")
        break
    time.sleep(1)
When the Raspberry is started, GPIO40 turns on a LED. I'm using the same output to trigger the input, so I inserted the time delay, otherwise the Raspberry should start the shutdown procedure immediately.

My question:
Using the program as it is now, does it have a 1 second delay only because of the time.sleep in the while loop, or do I have 2 seconds in total because the whole program running ?

Many thanks in advance...
In the beginning there was nothing, but even that exploded

AndersM
Posts: 33
Joined: Sun Sep 06, 2015 1:18 pm

Re: time.sleep outside while loop

Sun Oct 18, 2015 4:59 pm

You have 1 second delay when the program starts before the GPIO pin 38 is set to input.
Then you have 1 second between each new round in the loop. That means that the GPIO pin is checked every second but that the first check is made directly after setting the pin.
If you want to have a delay before the first check of pin 38 you can move the time.sleep(1) in the loop to directly after the while-statement and delete the sleep before the loop.

SkalTura
Posts: 8
Joined: Sun Oct 18, 2015 7:13 am
Location: Tilburg, The Netherlands

Re: time.sleep outside while loop

Sun Oct 18, 2015 6:18 pm

Okay, I will try that.
Thank you very much.
In the beginning there was nothing, but even that exploded

Return to “Python”