Skip to content

Commit 0366814

Browse files
author
brentru
committed
add code for BHT1750 light sensor feedback
1 parent a09f775 commit 0366814

File tree

1 file changed

+173
-0
lines changed

1 file changed

+173
-0
lines changed
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
import time
2+
import board
3+
import busio
4+
from digitalio import DigitalInOut
5+
import neopixel
6+
import adafruit_bh1750
7+
from adafruit_esp32spi import adafruit_esp32spi
8+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
9+
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
10+
11+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
12+
13+
### Sensor Calibration ###
14+
15+
APPLIANCE_ON_LUX = 30.0
16+
APPLIANCE_OFF_LUX = 4.0
17+
# How often the light sensor will be read, in seconds
18+
SENSOR_READ_TIME = 5.0
19+
20+
### WiFi ###
21+
22+
# Get wifi details and more from a secrets.py file
23+
try:
24+
from secrets import secrets
25+
except ImportError:
26+
print("WiFi secrets are kept in secrets.py, please add them there!")
27+
raise
28+
29+
# If you are using a board with pre-defined ESP32 Pins:
30+
esp32_cs = DigitalInOut(board.ESP_CS)
31+
esp32_ready = DigitalInOut(board.ESP_BUSY)
32+
esp32_reset = DigitalInOut(board.ESP_RESET)
33+
34+
# If you have an externally connected ESP32:
35+
# esp32_cs = DigitalInOut(board.D9)
36+
# esp32_ready = DigitalInOut(board.D10)
37+
# esp32_reset = DigitalInOut(board.D5)
38+
39+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
40+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
41+
"""Use below for Most Boards"""
42+
status_light = neopixel.NeoPixel(
43+
board.NEOPIXEL, 1, brightness=0.2
44+
) # Uncomment for Most Boards
45+
"""Uncomment below for ItsyBitsy M4"""
46+
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
47+
# Uncomment below for an externally defined RGB LED
48+
# import adafruit_rgbled
49+
# from adafruit_esp32spi import PWMOut
50+
# RED_LED = PWMOut.PWMOut(esp, 26)
51+
# GREEN_LED = PWMOut.PWMOut(esp, 27)
52+
# BLUE_LED = PWMOut.PWMOut(esp, 25)
53+
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
54+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
55+
56+
# Set up a pin for controlling the relay
57+
power_pin = DigitalInOut(board.D3)
58+
power_pin.switch_to_output()
59+
60+
# Set up the light sensor
61+
i2c = board.I2C()
62+
sensor = adafruit_bh1750.BH1750(i2c)
63+
64+
### Feeds ###
65+
# Set up a feed named Relay for subscribing to the relay feed on Adafruit IO
66+
feed_relay = secrets["aio_username"] + "/feeds/relay"
67+
68+
# Set up a feed named status for subscribing to the status feed on Adafruit IO
69+
feed_status = secrets["aio_username"] + "/feeds/status"
70+
71+
### Code ###
72+
73+
# Define callback methods which are called when events occur
74+
# pylint: disable=unused-argument, redefined-outer-name
75+
def connected(client, userdata, flags, rc):
76+
# This function will be called when the client is connected
77+
# successfully to the broker.
78+
print("Connected to Adafruit IO!")
79+
80+
81+
def disconnected(client, userdata, rc):
82+
# This method is called when the client is disconnected
83+
print("Disconnected from Adafruit IO!")
84+
85+
86+
def subscribe(client, userdata, topic, granted_qos):
87+
# This method is called when the client subscribes to a new feed.
88+
print("Subscribed to {0}".format(topic))
89+
90+
91+
def unsubscribe(client, userdata, topic, pid):
92+
# This method is called when the client unsubscribes from a feed.
93+
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
94+
95+
def on_message(client, topic, message):
96+
# Method callled when a client's subscribed feed has a new value.
97+
print("New message on topic {0}: {1}".format(topic, message))
98+
99+
100+
def on_relay_msg(client, topic, value):
101+
# Called when relay feed obtains a new value
102+
print("Turning Relay %s"%value)
103+
if value == "ON":
104+
power_pin.value = True
105+
elif value == "OFF":
106+
power_pin.value = False
107+
else:
108+
print("Unexpected value received on relay feed.")
109+
110+
# Connect to WiFi
111+
print("Connecting to WiFi...")
112+
wifi.connect()
113+
print("Connected!")
114+
115+
MQTT.set_socket(socket, esp)
116+
117+
# Set up a MiniMQTT Client
118+
client = MQTT.MQTT(
119+
broker="io.adafruit.com",
120+
username=secrets["aio_username"],
121+
password=secrets["aio_key"],
122+
)
123+
124+
# Setup the callback methods above
125+
client.on_connect = connected
126+
client.on_disconnect = disconnected
127+
client.on_subscribe = subscribe
128+
client.on_unsubscribe = unsubscribe
129+
client.on_message = on_message
130+
# Add a callback to the relay feed
131+
client.add_topic_callback(feed_relay, on_relay_msg)
132+
133+
# Connect the client to Adafruit IO
134+
print("Connecting to Adafruit IO...")
135+
client.connect()
136+
137+
# Subscribe to all updates on relay feed
138+
client.subscribe(feed_relay)
139+
140+
# Holds state of light sensor
141+
prv_sensor_value = 0
142+
# Time in seconds since start
143+
start_time = time.monotonic()
144+
145+
while True:
146+
try:
147+
# Poll for new messages on feed_relay
148+
client.loop()
149+
now = time.monotonic()
150+
if now - start_time > 3.0:
151+
# Read light sensor
152+
print("Reading light sensor")
153+
sensor_value = sensor.lux
154+
print("%.2f Lux" % sensor.lux)
155+
if sensor_value != prv_sensor_value:
156+
# Light sensor value changed between readings
157+
if sensor_value > APPLIANCE_ON_LUX:
158+
# Appliance is ON, publish to feed_status
159+
print("Appliance ON, publishing to IO...")
160+
client.publish(feed_status, 1)
161+
print("Published!")
162+
else:
163+
# Appliance is OFF, publish to feed_status
164+
print("Appliance OFF, publishing to IO...")
165+
client.publish(feed_status, 2)
166+
print("Published!")
167+
start_time = now
168+
except (ValueError, RuntimeError) as e:
169+
print("Failed to get data, retrying\n", e)
170+
wifi.reset()
171+
client.reconnect()
172+
continue
173+
time.sleep(0.5)

0 commit comments

Comments
 (0)