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()
Gé Fa
  • 96
  • 1
  • 7
  • 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 – Sembei Norimaki Nov 16 '22 at 09:55

1 Answers1

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()
Sembei Norimaki
  • 745
  • 1
  • 4
  • 11
  • 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. – Gé Fa Nov 16 '22 at 10:48
  • 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. – Sembei Norimaki Nov 16 '22 at 10:50