---
tags: IoT
---
# A simple plant monitor for Homeassistant
> [name=ja225hu][time=Tue, Jul 12, 2022] After running this for a while, the water level sensor has **corroded rather rapidly, leaking copper into the soil/water**, this is obviously not desirable, to prevent this a [capacitive moisture sensor](https://wiki.seeedstudio.com/Grove-Capacitive_Moisture_Sensor-Corrosion-Resistant/) would be ideal, but changing the setup so that the extant sensor is powered via one of the GPIO pins, and only powered in short, infrequent bursts while measuring would limit corosion and extend the lifespan of the sensor from a few days to several weeks or months.
Hello! I am John Ã…kerhielm (ja225hu), this is my tutorial for a simple IoT device for monitoring a plant's environment.
Time required; 1-2 hours.

## Objective
I'll be able to determine how fast my plants dry out, and automatically logging when I am watering them.
## Materials
| Item | Price | Link |
| -- |-- |-- |
| Esp32 development board |167 sek| [amazon.se](https://www.amazon.se/-/en/gp/product/B07RXTSZRC) |
| 37 Sensor kit |282 sek| [amazon.se](https://www.amazon.se/-/en/gp/product/B01M30ZWQR) |
Since I knew I wanted to stay in the smarthome arena, I decided that a wifi based device makes the most sense, both from a deployment (every home has wifi already), and development perspective.
I purchased the sensor kit since it was pretty cheap and a fun bunch of things to have. For this project I used:
* DHT11 Temperature & Humidity Sensor
* Water Level Sensor
## Computer setup
I use MicroPython which I downloaded from the Micropython website. My development board has an ***esp32-wrover-b*** so I used the [***esp32spiram*** release of MicroPython](https://micropython.org/download/esp32spiram/).
Flashing was unproblematic. I just followed the instructions and flashed the device with [esptool.py](https://github.com/espressif/esptool):
```bash
esptool.py --chip esp32 --port /dev/ttyUSB0 erase_flash
esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 460800 write_flash -z 0x1000 esp32-20190125-v1.10.bin
```
I prefer to use a simple text editor to write code, and manually upload to the device via terminal.
I found small script called [***mpfshell***](https://github.com/wendlers/mpfshell) that very neatly sends files to the device.
```bash
git clone https://github.com/wendlers/mpfshell
python3 setup.py install --user
#dont use pip to install it, version 0.92 is broken
```
I made two shell aliases to makes things neater.
```bash
#uploads all files in esp32/device_root to the esp32 device.
alias mpfs_USB_SYNC='mpfshell -n ttyUSB0 -c "lcd /home/john/d/p/esp32/device_root;mput .*"'
#opens a python interactive shell (REPL)
alias mpfs_USB_REPL='mpfshell -n ttyUSB0 -c "repl"'
```
## Putting everything together
The 'DHT11 Temperature Humidity sensor' and the 'Water Level Sensor' each use a single input pin, as well as 3.3V and GND.
I connect the DHT11 to pin 33 and the Water Level Sensor to pin 32.

### Platform
I run a local homeassistant instance and a mosquitto mqtt broker, this keeps all my data in-house. Homeassistant does the logging, display and processing of data.
homeassistant and mosquitto are run as docker containers, this makes install, reinstall migration very easy. Also: all the components are free and open source.
To install homeassistant using docker-compose (get it this from your distros repository).
create a file called docker-compose.yaml:
```docker-compose.yaml
services:
homeassistant:
image: homeassistant/home-assistant
network_mode: host
restart: always
volumes:
- ./homeassistant/config:/config
- /etc/localtime:/etc/localtime:ro
mosquitto:
image: eclipse-mosquitto
ports:
- 1883:1883
- 9001:9001
restart: always
volumes:
- ./mosquitto:/mosquitto/config
```
and then run
```bash.sh
docker-compose up -d
```
in the same folder. [More info here](https://hub.docker.com/r/homeassistant/home-assistant)
### The code
The code is very simple
> https://gist.github.com/fyra/2cfcfd639ed932714db77d038cbdfb2e
``` main.py
## Code for a plant-monitoring device.
#some builtin libraries, most notably; dht contains the driver for the temp-humidity sensor
import machine, time, dht, binascii, json
#using umqtt as mqttclient from https://github.com/micropython/micropython-lib/
from umqtt.robust import MQTTClient
#temphumidity sensor on pin 32
thsensor = dht.DHT11(machine.Pin(32))
#water level sensor on pin 33
water = machine.ADC(machine.Pin(33))
## ip address to my mqtt broker
server = "192.168.4.14"
identifier = binascii.b2a_base64(machine.unique_id())[:-1].decode()
# configuration for homeassistant sensor, makes the plant show up in Homeassistant automatically.
conf_t = { [...] }
conf_h = { [...] }
conf_w = { [...] }
#connect to the mqtt broker
c = MQTTClient("umqtt_client", server, keepalive=60)
c.connect()
time.sleep(0.2)
c.publish(f"homeassistant/sensor/{identifier}_humidity/config", json.dumps(conf_h).encode(), retain=True)
c.publish(f"homeassistant/sensor/{identifier}_waterlevel/config", json.dumps(conf_w).encode(), retain=True)
c.publish(f"homeassistant/sensor/{identifier}_temperature/config", json.dumps(conf_t).encode(), retain=True)
c.disconnect()
time.sleep(0.2)
#And finally an infinite loop that updates the sensor every five minutes.
while True:
thsensor.measure()
status = b"{" + f'\
"Temperature":"{str(thsensor.temperature())}",\
"Humidity":"{str(thsensor.humidity())}",\
"WaterLevel":"{str(water.read())}"\
' + b"}"
c.connect()
c.publish(f"tele/plant_{identifier}/STATUS", status, retain=True)
c.disconnect()
time.sleep(360)
```
### Transmitting the data / connectivity
Data is published to the local MQTT broker over wifi.
Homeassistant sees the topics in homeassistant/sensor/ and automatically recognizes them as sensor entities.
### Using the data
I am using Homeassistant to log and display the data.
Homeassistant is a very easy to use platform for automation, so I might add a small pump for automatic watering of some plants eventually.

### In Conclusion
This project produced a passable prototype, next refining step would be evaluating the Water Level Sensor and calculating a percentage rather than the unsigned 12bit value that it currently is.
After that i'd want to physically design the device.
Those wires are not pretty.

---