Last active
January 7, 2021 15:20
-
-
Save m0nochr0me/778671be1166af0d9d6c4ec3013b9fa0 to your computer and use it in GitHub Desktop.
Soil moisture sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# BOOT.PY | |
import gc | |
import network | |
import esp | |
esp.osdebug(None) | |
gc.collect() | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
essid = "yourWiFiSSID" | |
password = "yourWiFiPassword" | |
TIMEZONE = 8 | |
server = "192.168.0.10" | |
port = 19780 | |
mqttuser = "mqttlogin" | |
mqttpwd = "MQttPassWord123" | |
TOPIC_PREFIX = 'plant0/' | |
UPDATE_INTERVAL = 5 # Minutes |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import machine | |
import time | |
import ntptime | |
import ubinascii | |
from umqtt.simple import MQTTClient | |
from config import * | |
def initmqtt(): | |
client_id = ubinascii.hexlify(machine.unique_id()) | |
client = MQTTClient(client_id, MQTTSERVER, MQTTPORT, MQTTUSER, MQTTPWD) | |
client.connect() | |
print("MQTT Connected") | |
return client | |
def connect(): | |
sta_if = network.WLAN(network.STA_IF) | |
if not sta_if.isconnected(): | |
print("Connecting to {}...".format(ESSID)) | |
sta_if.active(True) | |
sta_if.connect(ESSID, PWD) | |
while not sta_if.isconnected(): | |
pass | |
print("Network config:", sta_if.ifconfig()) | |
connect() | |
rtc = machine.RTC() | |
try: | |
ntptime.settime() | |
sec = time.time() + TIMEZONE * 3600 | |
localtime = time.localtime(sec) | |
except: | |
print('Error setting time') | |
time.sleep(10) | |
machine.reset() | |
try: | |
client = initmqtt() | |
except: | |
print('Error initializing MQTT') | |
time.sleep(10) | |
machine.reset() | |
adc = machine.ADC(0) | |
moisture = adc.read() | |
print(moisture) | |
time.sleep_ms(1) | |
try: | |
client.publish(TOPIC_PREFIX + "moisture", str(moisture), retain=True) | |
time.sleep(1) | |
except: | |
print('Error publishing to topic') | |
time.sleep(10) | |
reset() | |
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) | |
rtc.alarm(rtc.ALARM0, time.ticks_ms() + UPDATE_INTERVAL*60*1000) | |
print('Entering deepsleep') | |
machine.deepsleep() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment