88
99import time
1010import os
11- import ssl
1211import microcontroller
1312import supervisor
13+ import ssl
1414import socketpool
1515import wifi
1616import board
17+ import digitalio
1718import alarm
1819import neopixel
1920import adafruit_hcsr04
2223import adafruit_requests
2324import adafruit_max1704x
2425
26+
27+
28+ # Initialize the power pin for the sensor
29+ sensor_power = digitalio .DigitalInOut (board .A2 )
30+ sensor_power .direction = digitalio .Direction .OUTPUT
31+ sensor_power .value = False # Start with sensor powered off
32+
33+ def power_sensor_on ():
34+ """Turn on power to the ultrasonic sensor and wait for it to stabilize."""
35+ sensor_power .value = True
36+ time .sleep (0.55 ) # Give sensor time to power up and stabilize
37+
38+ def power_sensor_off ():
39+ """Turn off power to the ultrasonic sensor."""
40+ sensor_power .value = False
41+
2542# Initialize the sonar sensor
2643sonar = adafruit_hcsr04 .HCSR04 (trigger_pin = board .A0 , echo_pin = board .A1 )
2744
4663
4764# Operating hours (24-hour format with minutes, e.g., "6:35" and "16:00")
4865OPENING_TIME = "6:00"
49- CLOSING_TIME = "22 :30"
66+ CLOSING_TIME = "15 :30"
5067# Normal operation check interval
51- NORMAL_CHECK_MINUTES = 5
68+ NORMAL_CHECK_MINUTES = 10
5269# Sleep duration in seconds during operating hours
5370SLEEP_DURATION = 60 * NORMAL_CHECK_MINUTES
5471# Display duration in seconds
5875
5976def parse_time (time_str ):
6077 """Convert time string (HH:MM format) to hours and minutes."""
61- # pylint: disable=redefined-outer-name
6278 parts = time_str .split (':' )
6379 return int (parts [0 ]), int (parts [1 ])
6480
6581def get_average_distance ():
6682 """Take multiple distance readings and return the average."""
83+ power_sensor_on () # Power on the sensor before taking measurements
6784 distances = []
6885 for _ in range (NUM_SAMPLES ):
6986 try :
@@ -73,6 +90,7 @@ def get_average_distance():
7390 except RuntimeError :
7491 print ("Error reading distance" )
7592 continue
93+ power_sensor_off () # Power off the sensor after measurements
7694
7795 # Only average valid readings
7896 if distances :
@@ -103,9 +121,7 @@ def set_pixel_color(distance):
103121avg_distance = get_average_distance ()
104122
105123if avg_distance is not None :
106-
107124 if avg_distance >= 22 :
108- # pylint: disable=invalid-name
109125 avg_distance = 22
110126 print (f"Average distance: { avg_distance :.1f} cm" )
111127 # Set color based on average distance
@@ -118,7 +134,6 @@ def set_pixel_color(distance):
118134
119135 # Try connecting to WiFi
120136 try :
121-
122137 print ("Connecting to %s" % os .getenv ("CIRCUITPY_WIFI_SSID" ))
123138 # Show pink while attempting to connect
124139 pixel .fill (PINK )
@@ -127,7 +142,6 @@ def set_pixel_color(distance):
127142 # Show cyan on successful connection
128143 pixel .fill (CYAN )
129144 time .sleep (1 ) # Brief pause to show the connection success
130- # pylint: disable=broad-except
131145 except Exception as e :
132146 print ("Failed to connect to WiFi. Error:" , e , "\n Board will hard reset in 30 seconds." )
133147 pixel .fill (OFF )
@@ -160,7 +174,6 @@ def set_pixel_color(distance):
160174 aio_username = os .getenv ("ADAFRUIT_AIO_USERNAME" )
161175 aio_key = os .getenv ("ADAFRUIT_AIO_KEY" )
162176 timezone = os .getenv ("TIMEZONE" )
163- # pylint: disable=line-too-long
164177 TIME_URL = f"https://io.adafruit.com/api/v2/{ aio_username } /integrations/time/strftime?x-aio-key={ aio_key } &tz={ timezone } "
165178 TIME_URL += "&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z"
166179
@@ -209,7 +222,6 @@ def set_pixel_color(distance):
209222 time .sleep (DISPLAY_DURATION )
210223
211224 # Use normal check interval during operating hours
212- # # pylint: disable=invalid-name
213225 sleep_seconds = SLEEP_DURATION
214226 print (f"Next check in { NORMAL_CHECK_MINUTES } minutes" )
215227 else :
@@ -233,7 +245,6 @@ def set_pixel_color(distance):
233245
234246 response .close ()
235247
236- # pylint: disable=broad-except
237248 except Exception as e :
238249 print ("Failed to get or send data, or connect. Error:" , e ,
239250 "\n Board will hard reset in 30 seconds." )
@@ -244,14 +255,13 @@ def set_pixel_color(distance):
244255else :
245256 print ("Failed to get valid distance readings" )
246257 pixel .fill (OFF )
247- # pylint: disable=invalid-name
248258 sleep_seconds = SLEEP_DURATION # Use normal interval if we couldn't get readings
249259
250260# Prepare for deep sleep
251261pixel .brightness = 0 # Turn off NeoPixel
262+ power_sensor_off () # Make sure sensor is powered off before sleep
252263
253264# Flush the serial output before sleep
254- # pylint: disable=pointless-statement
255265supervisor .runtime .serial_bytes_available
256266time .sleep (0.05 )
257267
0 commit comments