Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dusk till dawn
#2
I made a couple changes to simplify your code. Instead of breaking your time up into hours, minutes, and seconds and running a calculation each time, I changed those to datetime.time objects. It makes the code much easier to read. Instantiating those variables has also been moved above the while loop so they only created once instead of every time, which should have a marginal performance boost.

The if statements have been consolidated into a if statement for simplicity.

The try-except-finally remains although it's superfluous so long as the except clause is commented out (which I changed to a block quote).

#!/usr/bin/python
# import os
from time import sleep
from datetime import datetime, time

import RPi.GPIO as GPIO
 
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering  
GPIO.setup(26, GPIO.OUT)   # set GPIO18 as an output (LED) 
GPIO.setup(6, GPIO.OUT)   # set GPIO18 as an output (LED) 

try:
    dawnStart = time(hour = 6)
    dawnEnd = time(hour = 6, minute = 30)
    duskStart = time(hour = 22)
    duskEnd = time(hour = 22, minute = 30)
    while True:
        now = datetime.now().time() 

        if dawnEnd <= now <= duskStart:
            GPIO.output(26,1)
            GPIO.output(6,1)
        elif dawnStart <= now < dawnEnd:
            GPIO.output(6,1)
        elif duskStart <= now < duskEnd:
            GPIO.output(6,1)
        else:
            GPIO.output(26,0)
            GPIO.output(6,0)

        sleep(0.3)
        """
        except Exception:
            print("error")
            os.system('chicken.py')
        """"
finally:
    GPIO.cleanup()
Reply


Messages In This Thread
Dusk till dawn - by lo75 - Oct-13-2018, 01:01 PM
RE: Dusk till dawn - by stullis - Oct-13-2018, 03:00 PM
RE: Dusk till dawn - by lo75 - Oct-13-2018, 04:57 PM
RE: Dusk till dawn - by lo75 - Oct-13-2018, 03:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] Read text file from some point till EOF? Winfried 1 2,020 Oct-10-2021, 10:29 PM
Last Post: Winfried
  How to run a loop till half of the string...without using inbuilt function krish 1 2,945 Sep-28-2017, 05:34 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020