Skip to content

Instantly share code, notes, and snippets.

@sdcharle
Last active June 23, 2021 08:55
Show Gist options
  • Save sdcharle/f0599ff998667a48822f1bd8d6490781 to your computer and use it in GitHub Desktop.
Save sdcharle/f0599ff998667a48822f1bd8d6490781 to your computer and use it in GitHub Desktop.
My goofy ESP32 moisture sensor delay
"""
Fun thing that wakes up every x seconds and posts info to Adafruit IO from the moisture sensor
A transistor turns on/off the power to the sensor.
"""
import network
from umqtt.simple import MQTTClient
import machine
import time
USER_NAME = secret
AIO_KEY = secret
FEED = secret
SLEEP_MS = 600000 # sleep a while (10 min)
def connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect(secret, secret)
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
return sta_if
def create_client():
client = MQTTClient("umqtt_client",
"io.adafruit.com",
port = 1883,
user=USER_NAME,
password=AIO_KEY)
client.connect()
return client
# turn on transistor, wait, read ADC, connect, broadcast, sleep
print("Hello, son.")
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
print('woke from a deep sleep')
adc = machine.ADC(machine.Pin(33))
adc.atten(adc.ATTN_11DB)
onPin = machine.Pin(15,machine.Pin.OUT)
onPin.value(1)
connect()
# give it time
time.sleep(5)
cli = create_client()
moist = adc.read()
print(moist)
onPin.value(0)
cli.publish(topic=FEED, msg=str(moist))
time.sleep(2) # need?
# put the device to sleep for how long we want
machine.deepsleep(SLEEP_MS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment