0

I'm a Python beginner trying to write a script for a Raspberry Pi Zero.

The idea is to turn the lights on at dawn and off at dusk, keeping in mind those times change every day. So what i'm after (i guess) is something that will run 24/7 and evaluate whether lights should be on or off.

Here is what I have so far, which doesn't work. Can you guys tell me where I've gone wrong ?
I would be very grateful

#!/usr/bin/python

import pendulum
from time import sleep
from gpiozero import LED, PWMLED
from astral import LocationInfo
from astral.sun import dusk, dawn, midnight

now      = pendulum.now('Europe/Paris')
tomorrow = pendulum.tomorrow('Europe/Paris')
home     = LocationInfo("Mons-en-Baroeul", "France", "Europe/Paris", 50.6, 3.1)
dawn     = dawn(home.observer)
dusk     = dusk(home.observer)
midnight = midnight(home.observer)
blue     = LED(23)
red      = LED(24)

def lights_on():
  blue.on()
  red.on()

def lights_off():
  blue.off()
  red.off()

while True:
  while dawn <= now < dusk:
      lights_on()
      if now >= dusk:
        break
  while dusk <= now:
      lights_off()
      if now >= midnight:
        break
  else:
      lights_off()
1
  • You need to keep the variable now updated inside the while True loop, so just after the while True: line add the following line now = pendulum.now('Europe/Paris'). Also, the conditions to break the loops are not necessary, since the while already includes a condition to start looping Commented Nov 16, 2022 at 9:55

1 Answer 1

2

You need to update now inside the loop Also the logic is much more simple

Here's a proposal of the fixed code:

#!/usr/bin/python

import pendulum
from time import sleep
from gpiozero import LED, PWMLED
from astral import LocationInfo
from astral.sun import dusk, dawn, midnight

now      = pendulum.now('Europe/Paris')
tomorrow = pendulum.tomorrow('Europe/Paris')
home     = LocationInfo("Mons-en-Baroeul", "France", "Europe/Paris", 50.6, 3.1)
dawn     = dawn(home.observer)
dusk     = dusk(home.observer)
midnight = midnight(home.observer)
blue     = LED(23)
red      = LED(24)

def lights_on():
  blue.on()
  red.on()

def lights_off():
  blue.off()
  red.off()

while True:
  now = pendulum.now('Europe/Paris')
  if dawn <= now < dusk:
      lights_on()
  else:
      lights_off()
Sign up to request clarification or add additional context in comments.

2 Comments

Right ! So it's only re-evaluatedif inside the loop !? I knew it was something of the sort. Testing that right away. Thanks a bunch.
You need to update the variable every time you want to know the current time. Otherwise is like looking at your watch once and relying on that time for all future calculations.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.