updated espresso code to power down sensor
This commit is contained in:
parent
e5757ccc0d
commit
93c450259a
1 changed files with 23 additions and 13 deletions
|
|
@ -8,12 +8,13 @@ Feather ESP32-S2 with RCWL-1601 Ultrasonic distance sensor
|
||||||
|
|
||||||
import time
|
import time
|
||||||
import os
|
import os
|
||||||
import ssl
|
|
||||||
import microcontroller
|
import microcontroller
|
||||||
import supervisor
|
import supervisor
|
||||||
|
import ssl
|
||||||
import socketpool
|
import socketpool
|
||||||
import wifi
|
import wifi
|
||||||
import board
|
import board
|
||||||
|
import digitalio
|
||||||
import alarm
|
import alarm
|
||||||
import neopixel
|
import neopixel
|
||||||
import adafruit_hcsr04
|
import adafruit_hcsr04
|
||||||
|
|
@ -22,6 +23,22 @@ from adafruit_io.adafruit_io import IO_MQTT
|
||||||
import adafruit_requests
|
import adafruit_requests
|
||||||
import adafruit_max1704x
|
import adafruit_max1704x
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Initialize the power pin for the sensor
|
||||||
|
sensor_power = digitalio.DigitalInOut(board.A2)
|
||||||
|
sensor_power.direction = digitalio.Direction.OUTPUT
|
||||||
|
sensor_power.value = False # Start with sensor powered off
|
||||||
|
|
||||||
|
def power_sensor_on():
|
||||||
|
"""Turn on power to the ultrasonic sensor and wait for it to stabilize."""
|
||||||
|
sensor_power.value = True
|
||||||
|
time.sleep(0.55) # Give sensor time to power up and stabilize
|
||||||
|
|
||||||
|
def power_sensor_off():
|
||||||
|
"""Turn off power to the ultrasonic sensor."""
|
||||||
|
sensor_power.value = False
|
||||||
|
|
||||||
# Initialize the sonar sensor
|
# Initialize the sonar sensor
|
||||||
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.A0, echo_pin=board.A1)
|
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.A0, echo_pin=board.A1)
|
||||||
|
|
||||||
|
|
@ -46,9 +63,9 @@ pixel.fill(YELLOW)
|
||||||
|
|
||||||
# Operating hours (24-hour format with minutes, e.g., "6:35" and "16:00")
|
# Operating hours (24-hour format with minutes, e.g., "6:35" and "16:00")
|
||||||
OPENING_TIME = "6:00"
|
OPENING_TIME = "6:00"
|
||||||
CLOSING_TIME = "22:30"
|
CLOSING_TIME = "15:30"
|
||||||
# Normal operation check interval
|
# Normal operation check interval
|
||||||
NORMAL_CHECK_MINUTES = 5
|
NORMAL_CHECK_MINUTES = 10
|
||||||
# Sleep duration in seconds during operating hours
|
# Sleep duration in seconds during operating hours
|
||||||
SLEEP_DURATION = 60 * NORMAL_CHECK_MINUTES
|
SLEEP_DURATION = 60 * NORMAL_CHECK_MINUTES
|
||||||
# Display duration in seconds
|
# Display duration in seconds
|
||||||
|
|
@ -58,12 +75,12 @@ NUM_SAMPLES = 5
|
||||||
|
|
||||||
def parse_time(time_str):
|
def parse_time(time_str):
|
||||||
"""Convert time string (HH:MM format) to hours and minutes."""
|
"""Convert time string (HH:MM format) to hours and minutes."""
|
||||||
# pylint: disable=redefined-outer-name
|
|
||||||
parts = time_str.split(':')
|
parts = time_str.split(':')
|
||||||
return int(parts[0]), int(parts[1])
|
return int(parts[0]), int(parts[1])
|
||||||
|
|
||||||
def get_average_distance():
|
def get_average_distance():
|
||||||
"""Take multiple distance readings and return the average."""
|
"""Take multiple distance readings and return the average."""
|
||||||
|
power_sensor_on() # Power on the sensor before taking measurements
|
||||||
distances = []
|
distances = []
|
||||||
for _ in range(NUM_SAMPLES):
|
for _ in range(NUM_SAMPLES):
|
||||||
try:
|
try:
|
||||||
|
|
@ -73,6 +90,7 @@ def get_average_distance():
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
print("Error reading distance")
|
print("Error reading distance")
|
||||||
continue
|
continue
|
||||||
|
power_sensor_off() # Power off the sensor after measurements
|
||||||
|
|
||||||
# Only average valid readings
|
# Only average valid readings
|
||||||
if distances:
|
if distances:
|
||||||
|
|
@ -103,9 +121,7 @@ time.sleep(0.1)
|
||||||
avg_distance = get_average_distance()
|
avg_distance = get_average_distance()
|
||||||
|
|
||||||
if avg_distance is not None:
|
if avg_distance is not None:
|
||||||
|
|
||||||
if avg_distance >= 22:
|
if avg_distance >= 22:
|
||||||
# pylint: disable=invalid-name
|
|
||||||
avg_distance = 22
|
avg_distance = 22
|
||||||
print(f"Average distance: {avg_distance:.1f} cm")
|
print(f"Average distance: {avg_distance:.1f} cm")
|
||||||
# Set color based on average distance
|
# Set color based on average distance
|
||||||
|
|
@ -118,7 +134,6 @@ if avg_distance is not None:
|
||||||
|
|
||||||
# Try connecting to WiFi
|
# Try connecting to WiFi
|
||||||
try:
|
try:
|
||||||
|
|
||||||
print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID"))
|
print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID"))
|
||||||
# Show pink while attempting to connect
|
# Show pink while attempting to connect
|
||||||
pixel.fill(PINK)
|
pixel.fill(PINK)
|
||||||
|
|
@ -127,7 +142,6 @@ if avg_distance is not None:
|
||||||
# Show cyan on successful connection
|
# Show cyan on successful connection
|
||||||
pixel.fill(CYAN)
|
pixel.fill(CYAN)
|
||||||
time.sleep(1) # Brief pause to show the connection success
|
time.sleep(1) # Brief pause to show the connection success
|
||||||
# pylint: disable=broad-except
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Failed to connect to WiFi. Error:", e, "\nBoard will hard reset in 30 seconds.")
|
print("Failed to connect to WiFi. Error:", e, "\nBoard will hard reset in 30 seconds.")
|
||||||
pixel.fill(OFF)
|
pixel.fill(OFF)
|
||||||
|
|
@ -160,7 +174,6 @@ if avg_distance is not None:
|
||||||
aio_username = os.getenv("ADAFRUIT_AIO_USERNAME")
|
aio_username = os.getenv("ADAFRUIT_AIO_USERNAME")
|
||||||
aio_key = os.getenv("ADAFRUIT_AIO_KEY")
|
aio_key = os.getenv("ADAFRUIT_AIO_KEY")
|
||||||
timezone = os.getenv("TIMEZONE")
|
timezone = os.getenv("TIMEZONE")
|
||||||
# pylint: disable=line-too-long
|
|
||||||
TIME_URL = f"https://io.adafruit.com/api/v2/{aio_username}/integrations/time/strftime?x-aio-key={aio_key}&tz={timezone}"
|
TIME_URL = f"https://io.adafruit.com/api/v2/{aio_username}/integrations/time/strftime?x-aio-key={aio_key}&tz={timezone}"
|
||||||
TIME_URL += "&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z"
|
TIME_URL += "&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z"
|
||||||
|
|
||||||
|
|
@ -209,7 +222,6 @@ if avg_distance is not None:
|
||||||
time.sleep(DISPLAY_DURATION)
|
time.sleep(DISPLAY_DURATION)
|
||||||
|
|
||||||
# Use normal check interval during operating hours
|
# Use normal check interval during operating hours
|
||||||
# # pylint: disable=invalid-name
|
|
||||||
sleep_seconds = SLEEP_DURATION
|
sleep_seconds = SLEEP_DURATION
|
||||||
print(f"Next check in {NORMAL_CHECK_MINUTES} minutes")
|
print(f"Next check in {NORMAL_CHECK_MINUTES} minutes")
|
||||||
else:
|
else:
|
||||||
|
|
@ -233,7 +245,6 @@ if avg_distance is not None:
|
||||||
|
|
||||||
response.close()
|
response.close()
|
||||||
|
|
||||||
# pylint: disable=broad-except
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Failed to get or send data, or connect. Error:", e,
|
print("Failed to get or send data, or connect. Error:", e,
|
||||||
"\nBoard will hard reset in 30 seconds.")
|
"\nBoard will hard reset in 30 seconds.")
|
||||||
|
|
@ -244,14 +255,13 @@ if avg_distance is not None:
|
||||||
else:
|
else:
|
||||||
print("Failed to get valid distance readings")
|
print("Failed to get valid distance readings")
|
||||||
pixel.fill(OFF)
|
pixel.fill(OFF)
|
||||||
# pylint: disable=invalid-name
|
|
||||||
sleep_seconds = SLEEP_DURATION # Use normal interval if we couldn't get readings
|
sleep_seconds = SLEEP_DURATION # Use normal interval if we couldn't get readings
|
||||||
|
|
||||||
# Prepare for deep sleep
|
# Prepare for deep sleep
|
||||||
pixel.brightness = 0 # Turn off NeoPixel
|
pixel.brightness = 0 # Turn off NeoPixel
|
||||||
|
power_sensor_off() # Make sure sensor is powered off before sleep
|
||||||
|
|
||||||
# Flush the serial output before sleep
|
# Flush the serial output before sleep
|
||||||
# pylint: disable=pointless-statement
|
|
||||||
supervisor.runtime.serial_bytes_available
|
supervisor.runtime.serial_bytes_available
|
||||||
time.sleep(0.05)
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue