# Pet Bowl Water Level Sensing

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/102/144/medium800thumb/sensors_Main_Image.jpg?1620943096)

With the FunHouse and Home Assistant, you can automatically be alerted if your pet's bowl gets too low. For this project we are using the Simple Water Sensor. Even though it is designed to be a digital sensor, it will actually work in analog mode to give you a little more granularity. In this way, you can tell if your pet's water level is good, low, or needs water added.

In order to mitigate the effects of running electricity through water, the sensor is only on for a very short period of time to take a reading and turns back off. This is accomplished by using 2 of the ports on the FunHouse. One supplies the voltage to the sensor through the GPIO line and the other takes the reading.

We'll go over how to get your sensor set up and configure Home Assistant to read the status of the sensor and also send you notifications within the Home Assistant environment.

## Parts
### Adafruit FunHouse - WiFi Home Automation Development Board

[Adafruit FunHouse - WiFi Home Automation Development Board](https://www.adafruit.com/product/4985)
Home is where the heart is...it's also where we keep all our electronic bits. So why not wire it up with sensors and actuators to turn our house into an electronic wonderland. Whether it's tracking the environmental temperature and humidity in your laundry room, or notifying you when...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4985)
[Related Guides to the Product](https://learn.adafruit.com/products/4985/guides)
![Top-down video of Adafruit Funhouse PCB. The TFT display shows a data readout, and the NeoPixel LEDs glow rainbow colors.](https://cdn-shop.adafruit.com/product-videos/640x480/4985-00.jpg)

### Simple Water Detection Sensor with Digital Output

[Simple Water Detection Sensor with Digital Output](https://www.adafruit.com/product/4965)
Keep wet things wet&nbsp;and dry things dry by detecting when the dry things get wet by accident! This palm-sized cherry-red water sensor is simple and easy to implement in your wet-dry-sensing project.

Usage is very simple: connect the minus (-) pin to ground, connect the plus (+) pin...

In Stock
[Buy Now](https://www.adafruit.com/product/4965)
[Related Guides to the Product](https://learn.adafruit.com/products/4965/guides)
![Video of someone dunking the water sensor into a glass of water. The TFT on the FunHouse displays a wetness gauge that goes from 0 to 100.](https://cdn-shop.adafruit.com/product-videos/640x480/4965-03.jpg)

You'll need 2 of these STEMMA adapters.

### STEMMA JST PH 2mm 3-Pin to Female Socket Cable - 200mm

[STEMMA JST PH 2mm 3-Pin to Female Socket Cable - 200mm](https://www.adafruit.com/product/3894)
This cable will let you turn a JST PH 3-pin cable port into 3 individual wires with high-quality 0.1" female header sockets on the end. We're carrying these to match up with our Hallowing, for extending and connecting sensors or LEDs - and the wires are even color coded!

<a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/3894)
[Related Guides to the Product](https://learn.adafruit.com/products/3894/guides)
![Angled shot of STEMMA JST PH 3-Pin to Female Header Cable - 200mm.](https://cdn-shop.adafruit.com/640x480/3894-03.jpg)

### Servo Extension Cable - 50cm / 19.5" long

[Servo Extension Cable - 50cm / 19.5" long](https://www.adafruit.com/product/973)
Stretch out your servo connections with this flexible servo extension cord. It has a 3 pin shrouded "male" connection to plug your servo into and then, 50cm later, a 3 pin female connection. It even keeps the common red/black/white color coding. A great add-on to our <a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/973)
[Related Guides to the Product](https://learn.adafruit.com/products/973/guides)
![Three pin Servo Extension Cable - 50cm / 19.5" long.](https://cdn-shop.adafruit.com/640x480/973-02.jpg)

### Clear Adhesive Squares - 6 pack

[Clear Adhesive Squares - 6 pack](https://www.adafruit.com/product/4813)
 **UGlu Dashes** &nbsp;are perfect for a variety of small projects. These adhesive squares provide a stronger bond to most surfaces and are cleaner and easier to remove&nbsp;without the wait, mess, or hassle.

Adheres to a wide variety of surfaces, including, but not limited...

In Stock
[Buy Now](https://www.adafruit.com/product/4813)
[Related Guides to the Product](https://learn.adafruit.com/products/4813/guides)
![ 6 pack of Clear Adhesive Squares](https://cdn-shop.adafruit.com/640x480/4813-01.jpg)

### Mini Magnet Feet for RGB LED Matrices (Pack of 4)

[Mini Magnet Feet for RGB LED Matrices (Pack of 4)](https://www.adafruit.com/product/4631)
Got a glorious&nbsp;RGB Matrix project you want to mount and display in your workspace or home? If you have one of the matrix panels listed below, you'll need a pack of these **Mini-Magnet Feet.** &nbsp;We got these specifically&nbsp;for our RGB LED Matrices, which no longer...

In Stock
[Buy Now](https://www.adafruit.com/product/4631)
[Related Guides to the Product](https://learn.adafruit.com/products/4631/guides)
![Angled shot of four magnet feet.](https://cdn-shop.adafruit.com/640x480/4631-00.jpg)

### USB Type A to Type C Cable - 1ft - 0.3 meter

[USB Type A to Type C Cable - 1ft - 0.3 meter](https://www.adafruit.com/product/4473)
As technology changes and adapts, so does Adafruit. This&nbsp;&nbsp; **USB Type A to Type C** cable will help you with the transition to USB C, even if you're still totin' around a USB Type A hub, computer or laptop.

USB C is the latest industry-standard connector for...

In Stock
[Buy Now](https://www.adafruit.com/product/4473)
[Related Guides to the Product](https://learn.adafruit.com/products/4473/guides)
![Angled shot of a one-foot-long, black, USB Type A to Type C Cable](https://cdn-shop.adafruit.com/640x480/4473-02.jpg)

# Pet Bowl Water Level Sensing

## Wiring

Wiring the FunHouse to the water sensor is pretty straight forward. The only tricky bit we are doing here is we are using 2 JST ports to read the sensor. One of the JST ports is used for reading the sensor and the other port is powering the sensor with its signal wire. This is so the sensor isn't on all the time, which can lead to electrolyzing the traces fairly quickly.

Since this is a water sensor and we're dealing with electronics, we recommend connecting a servo extension cable between the JST cables and the sensor.

- Connect the&nbsp; **white wire** &nbsp;from the JST connector of **A0** to the positive or + pin on the water sensor.
- Connect the&nbsp; **black wire** &nbsp;from the JST connector of **A1** to the ground or - pin on the water sensor.
- Connect the&nbsp; **white wire** &nbsp;from the JST connector of **A1** to the signal or S pin on the water sensor.
- Leave any remaining wires unconnected.

![sensors_Pet_Bowl_Water_Sensor_bb.jpg](https://cdn-learn.adafruit.com/assets/assets/000/102/147/medium640/sensors_Pet_Bowl_Water_Sensor_bb.jpg?1620947742)

## Attaching the Sensor
Place some double-sided adhesive to the back side of the sensor.

![sensors_IMG_3212.jpg](https://cdn-learn.adafruit.com/assets/assets/000/102/153/medium640/sensors_IMG_3212.jpg?1621006771)

Attach the sensor to the side of the bowl. If it has trouble sticking due to the curve in the bowl, you can add more adhesive.

You'll want to align the bottom edge around where you would want to be alerted, so if your pet likes it changed more frequently and doesn't drink much, you may want to mount it a bit higher.

![sensors_IMG_3207.jpg](https://cdn-learn.adafruit.com/assets/assets/000/102/154/medium640/sensors_IMG_3207.jpg?1621006831)

Plug the servo extension cable into the sensor with the black wire towards the `-` and the white wire towards the `S` as shown in the image.

![sensors_IMG_3208.jpg](https://cdn-learn.adafruit.com/assets/assets/000/102/155/medium640/sensors_IMG_3208.jpg?1621006925)

# Pet Bowl Water Level Sensing

## CircuitPython

[CircuitPython](https://github.com/adafruit/circuitpython)&nbsp;is a derivative of&nbsp;[MicroPython](https://micropython.org/)&nbsp;designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the&nbsp; **CIRCUITPY** &nbsp;drive to iterate.

## Set Up CircuitPython

Follow the steps to get CircuitPython installed on your FunHouse.

[Download the latest CircuitPython for your board from circuitpython.org](https://circuitpython.org/board/adafruit_funhouse/)
 **Click the link above and download the latest .BIN and .UF2 file**

(depending on how you program the ESP32S2 board you may need one or the other, might as well get both)

Download and save it to your desktop (or wherever is handy).

![sensors_Download_Firmware.png](https://cdn-learn.adafruit.com/assets/assets/000/101/512/medium640/sensors_Download_Firmware.png?1618531628)

Plug your FunHouse into your computer using a known-good USB cable.

**A lot of people end up using charge-only USB cables and it is very frustrating! So make sure you have a USB cable you know is good for data sync.**

![sensors_4985-06.jpg](https://cdn-learn.adafruit.com/assets/assets/000/101/513/medium640/sensors_4985-06.jpg?1618531771)

## Option 1 - Load with UF2 Bootloader

This is by far the easiest way to load CircuitPython.&nbsp;**However it requires your board has the UF2 bootloader installed. Some early boards do not (we hadn't written UF2 yet!) - in which case you can load using the built in ROM bootloader.**

Still, try this first!

### Try Launching UF2 Bootloader

Loading CircuitPython by drag-n-drop UF2 bootloader is the easier way and we recommend it.

![sensors_Boot_Mode.jpg](https://cdn-learn.adafruit.com/assets/assets/000/101/514/medium640/sensors_Boot_Mode.jpg?1618534416)

Launch UF2 by&nbsp; **double-clicking** &nbsp;the Reset button (the one next to the USB C port). You may have to try a few times to get the timing right.

**About a half second pause between clicks while the DotStars are purple seems to work well.**

![sensors_Press_Reset.jpg](https://cdn-learn.adafruit.com/assets/assets/000/101/519/medium640/sensors_Press_Reset.jpg?1618586167)

If the UF2 bootloader is installed, you will see a new disk drive appear called&nbsp; **HOUSEBOOT**

![sensors_Windows_Drives.png](https://cdn-learn.adafruit.com/assets/assets/000/101/521/medium640/sensors_Windows_Drives.png?1618588909)

Copy the&nbsp; **UF2** &nbsp;file you downloaded at the first step of this tutorial onto the&nbsp; **HOUSEBOOT** &nbsp;drive

![sensors_Windows_Drag_Firmware.png](https://cdn-learn.adafruit.com/assets/assets/000/101/522/medium640/sensors_Windows_Drag_Firmware.png?1618589080)

If you're using Windows and you get an error at the end of the file copy that says&nbsp; **Error from the file copy, Error 0x800701B1: A device which does not exist was specified.&nbsp;** You can ignore this error, the bootloader sometimes disconnects without telling Windows, the install completed just fine and you can continue. [If its really annoying, you can also upgrade the bootloader (the latest version of the UF2 bootloader fixes this warning)](https://learn.adafruit.com/adafruit-funhouse/install-uf2-bootloader)

Your board should auto-reset into CircuitPython, or you may need to press reset. A&nbsp; **CIRCUITPY** &nbsp;drive will appear. You're done! Go to the next pages.

![sensors_Windows_CircuitPy.png](https://cdn-learn.adafruit.com/assets/assets/000/101/523/medium640/sensors_Windows_CircuitPy.png?1618589269)

## Option 2 - Use Chrome Browser To Upload BIN file
Warning: 

The next best option is to try using the Chrome-browser version of esptool we have written. This is handy if you don't have Python on your computer, or something is really weird with your setup that makes esptool not run (which happens sometimes and isn't worth debugging!) You can follow along on the&nbsp;[Install UF2 Bootloader](https://learn.adafruit.com/adafruit-funhouse/install-uf2-bootloader)&nbsp;page and either load the UF2 bootloader and then come back to Option 1 on this page, or you can download the CircuitPython BIN file directly using the tool in the same manner as the bootloader.

## Option 3 - Use esptool to load BIN file

For more advanced users, you can upload with&nbsp; **esptool** &nbsp;to the ROM (hardware) bootloader instead!

Follow the initial steps found in the&nbsp;[Run esptool and check connection section of the Install UF2 Bootloader page](https://learn.adafruit.com/adafruit-funhouse/install-uf2-bootloader)&nbsp;to verify your environment is set up, your board is successfully connected, and which port it's using.

**In the final command to write a binary file to the board, replace the port with your port, and replace "firmware.bin" with the the file you downloaded above.**

The output should look something like the output in the image.

![sensors_adafruit_products_Metro_ESP32_S2_binary_install.png](https://cdn-learn.adafruit.com/assets/assets/000/101/524/medium640/sensors_adafruit_products_Metro_ESP32_S2_binary_install.png?1618589586)

Press reset to exit the bootloader.

Your&nbsp; **CIRCUITPY** &nbsp;drive should appear!

You're all set! Go to the next pages.

![sensors_adafruit_products_Metro_ESP32_S2_CIRCUITPY.png](https://cdn-learn.adafruit.com/assets/assets/000/101/525/medium640/sensors_adafruit_products_Metro_ESP32_S2_CIRCUITPY.png?1618589627)

# Pet Bowl Water Level Sensing

## CircuitPython Internet Test

One of the great things about most Espressif microcontrollers are their built-in WiFi capabilities. This page covers the basics of getting connected using CircuitPython.

The first thing you need to do is update your **code.py** to the following (it will error until WiFi details are added). Click the **Download Project Bundle** button to download the necessary libraries and the&nbsp; **code.py** file in a zip file. Extract the contents of the zip file, and copy the **entire**  **lib**  **folder** and the **code.py** file to your **CIRCUITPY** drive.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/ESP32_S2_WiFi_Tests/CPy_Native_WiFi_Test/code.py

Your **CIRCUITPY** drive should resemble the following.

![CIRCUITPY](https://adafruit.github.io/Adafruit_Learning_System_Guides/ESP32_S2_WiFi_Tests_CPy_Native_WiFi_Test.png )

To get connected, the next thing you need to do is update the **settings.toml** file.

## The settings.toml File

We expect people to share tons of projects as they build CircuitPython WiFi widgets. What we want to avoid is people accidentally sharing their passwords or secret tokens and API keys. So, we designed all our examples to use a **settings.toml** file, that is on your&nbsp; **CIRCUITPY** &nbsp;drive, to hold secret/private/custom data. That way you can share your main project without worrying about accidentally sharing private stuff.

If you have a fresh install of CircuitPython on your board, the initial **settings.toml** file on your **CIRCUITPY** drive is empty.

To get started, you can update the **settings.toml** on your **CIRCUITPY** drive to contain the following code.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/ESP32_S2_WiFi_Tests/CPy_Native_WiFi_Test/settings.toml

This file should contain a series of Python variables, each assigned to a string. Each variable should describe what it represents (say&nbsp;`wifi_ssid`), followed by an **=&nbsp;** (equals sign), followed by the data in the form of a Python string (such as `"my-wifi-password"` including the quote marks).

**At a minimum you'll need to add/update your WiFi SSID and WiFi password, so do that now!**

As you make projects you may need more tokens and keys, just add them one line at a time. See for example other tokens such as one for accessing GitHub or the Hackaday API. Other non-secret data like your timezone can also go here.

For the correct time zone string, look at&nbsp;[http://worldtimeapi.org/timezones](http://worldtimeapi.org/timezones)&nbsp;and remember that if your city is not listed, look for a city in the same time zone, for example Boston, New York, Philadelphia, Washington DC, and Miami are all on the same time as New York.

Of course, don't share your **settings.toml** - keep that out of GitHub, Discord or other project-sharing sites.

Warning: 

If you connect to the serial console, you should see something like the following:

![](https://cdn-learn.adafruit.com/assets/assets/000/097/014/medium800/adafruit_products_1__screen__Users_brentrubell__screen_.png?1605218222)

In order, the example code...

Checks the ESP32's MAC address.

```python
print(f"My MAC address: {[hex(i) for i in wifi.radio.mac_address]}")
```

Performs a scan of all access points and prints out the access point's name (SSID), signal strength (RSSI), and channel.

```python
print("Available WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
                                             network.rssi, network.channel))
wifi.radio.stop_scanning_networks()
```

Connects to the access point you defined in the **settings.toml** file, and prints out its local IP address.

```python
print(f"Connecting to {os.getenv('WIFI_SSID')}")
wifi.radio.connect(os.getenv("WIFI_SSID"), os.getenv("WIFI_PASSWORD"))
print(f"Connected to {os.getenv('WIFI_SSID')}")
print(f"My IP address: {wifi.radio.ipv4_address}")
```

Attempts to ping a Google DNS server to test connectivity. If a ping fails, it returns `None`. Initial pings can sometimes fail for various reasons. So, if the initial ping is successful (`is not None`), it will print the echo speed in ms. If the initial ping fails, it will try one more time to ping, and then print the returned value. If the second ping fails, it will result in `"Ping google.com: None ms"` being printed to the serial console. Failure to ping does not always indicate a lack of connectivity, so the code will continue to run.

```python
ping_ip = ipaddress.IPv4Address("8.8.8.8")
ping = wifi.radio.ping(ip=ping_ip) * 1000
if ping is not None:
    print(f"Ping google.com: {ping} ms")
else:
    ping = wifi.radio.ping(ip=ping_ip)
    print(f"Ping google.com: {ping} ms")
```

The code creates a socketpool using the wifi radio's available sockets. This is performed so we don't need to re-use sockets. Then, it initializes a a new instance of the [requests](http://docs.python-requests.org/en/master/) interface - which makes getting data from the internet _really really easy._

```python
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
```

To read in plain-text from a web URL, call `requests.get` - you may pass in either a http, or a http **s** url for SSL connectivity.&nbsp;

```python
print(f"Fetching text from {TEXT_URL}")
response = requests.get(TEXT_URL)
print("-" * 40)
print(response.text)
print("-" * 40)
```

Requests can also display a JSON-formatted response from a web URL using a call to `requests.get`.&nbsp;

```python
print(f"Fetching json from {JSON_QUOTES_URL}")
response = requests.get(JSON_QUOTES_URL)
print("-" * 40)
print(response.json())
print("-" * 40)
```

Finally, you can fetch and parse a JSON URL using `requests.get`. This code snippet obtains the `stargazers_count` field from a call to the GitHub API.

```python
print(f"Fetching and parsing json from {JSON_STARS_URL}")
response = requests.get(JSON_STARS_URL)
print("-" * 40)
print(f"CircuitPython GitHub Stars: {response.json()['stargazers_count']}")
print("-" * 40)
```

OK you now have your ESP32 board set up with a proper **settings.toml** file and can connect over the Internet. If not, check that your **settings.toml** file has the right SSID and password and retrace your steps until you get the Internet connectivity working!

## IPv6 Networking

Starting in CircuitPython 9.2, IPv6 networking is available on most Espressif wifi boards. Socket-using libraries like **adafruit\_requests** and **adafruit\_ntp** will need to be updated to use the new APIs and for now can only connect to services on IPv4.

### IPv6 connectivity & privacy

IPv6 addresses are divided into many special kinds, and many of those kinds (like those starting with&nbsp; **FC** , **FD** , **FE** ) are private or local; Addresses starting with other prefixes like&nbsp; **2002:** and **2001:** are globally routable. In 2024, far from all ISPs and home networks support IPv6 internet connectivity. For more info consult resources like [Wikipedia](https://en.wikipedia.org/wiki/IPv6_address#Local_addresses). If you're interested in global IPv6 connectivity you can use services like [Hurricane Electric](https://www.he.net/) to create an "IPv6 tunnel" (free as of 2024, but requires expertise and a compatible router or host computer to set up)

It's also important to be aware that, as currently implemented by Espressif, there are privacy concerns especially when these devices operate on the global IPv6 network: The device's unique identifier (its EUI-64 or MAC address) is used by default as part of its IPv6 address. This means that the device identity can be tracked across multiple networks by any service it connects to.

### Enable IPv6 networking

Due to the privacy consideration, IPv6 networking is not automatically enabled. Instead, it must be explicitly enabled by a call to `start_dhcp_client` with the `ipv6=True` argument specified:

```python
wifi.start_dhcp_client(ipv6=True)
```

### Check IP addresses

The read-only&nbsp;`addresses` property of the `wifi.radio` object holds all addresses, including IPv4 and IPv6 addresses:

```python
&gt;&gt;&gt; wifi.radio.addresses
('FE80::7EDF:A1FF:FE00:518C', 'FD5F:3F5C:FE50:0:7EDF:A1FF:FE00:518C', '10.0.3.96')
```

The `wifi.radio.dns` servers can be IPv4 or IPv6:

```python
&gt;&gt;&gt; wifi.radio.dns
('FD5F:3F5C:FE50::1',)
&gt;&gt;&gt; wifi.radio.dns = ("1.1.1.1",)
&gt;&gt;&gt; wifi.radio.dns
('1.1.1.1',)
```

### Ping v6 networks

`wifi.radio.ping` accepts v6 addresses and names:

```python
&gt;&gt;&gt; wifi.radio.ping("google.com")
0.043
&gt;&gt;&gt; wifi.radio.ping("ipv6.google.com")
0.048
```

### Create & use IPv6 sockets

Use the address family `socket.AF_INET6`. After the socket is created, use methods like `connect`, `send`, `recfrom_into`, etc just like for IPv4 sockets. This code snippet shows communicating with a private-network NTP server; this IPv6 address will not work on your network:

```python
&gt;&gt;&gt; ntp_addr = ("fd5f:3f5c:fe50::20e", 123)
&gt;&gt;&gt; PACKET_SIZE = 48
&gt;&gt;&gt; 
&gt;&gt;&gt; buf = bytearray(PACKET_SIZE)
&gt;&gt;&gt; with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as s:
...     s.settimeout(1)
...     buf[0] = 0b0010_0011
...     s.sendto(buf, ntp_addr)
...     print(s.recvfrom_into(buf))
...     print(buf)
... 
48
(48, ('fd5f:3f5c:fe50::20e', 123))
bytearray(b'$\x01\x03\xeb\x00\x00\x00\x00\x00\x00\x00GGPS\x00\xeaA0h\x07s;\xc0\x00\x00\x00\x00\x00\x00\x00\x00\xeaA0n\xeb4\x82-\xeaA0n\xebAU\xb1')
```

# Pet Bowl Water Level Sensing

## Coding the Water Sensor

Let's start out with the code that goes onto the FunHouse.

## MQTT Secrets Settings

Since the code publishes directly to the MQTT server, there are a few more **secrets.py** file settings that the code expects to find. If your MQTT server has no username and password, you can change the value to `None`, however in general, the Home Assistant MQTT broker is set up to be password protected by default.

```python
MQTT_BROKER = "192.168.1.1"
MQTT_PORT = 1883
MQTT_USERNAME = "myusername"
MQTT_PASSWORD = "mypassword"
```

To add code and libraries to your FunHouse, click the **Download Project Bundle** button to get the code and all of the libraries.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/FunHouse_Pet_Bowl_Sensor/code.py

Copy these over to the **CIRCUITPY** drive for your FunHouse board in the root directory along with your **secrets.py** file. The files on your board should look like this:

![](https://cdn-learn.adafruit.com/assets/assets/000/102/012/medium800/projects_Files.png?1620169322)

## Code Walkthrough

Now to cover the code in sections. First are library&nbsp;imports. This includes the `FunHouse` library, the `Circle` to display if the board is connected, `time` for checking in intervals, and finally `board`, `analogio`, and `digitalio` for enabling and reading the sensor itself.

```python
import os
import time
import board
import digitalio
import analogio
from adafruit_display_shapes.circle import Circle
from adafruit_funhouse import FunHouse
```

Next up is the MQTT topic, `BOWL_STATE_TOPIC`. The script will publish to the **state topic** if the reading has changed enough to let Home Assistant know the new state of the bowl.

`LOW_VALUE` is the raw analog reading for the sensor when the water is low. Anything above this value is considered full. `EMPTY_VALUE` is the raw analog reading for the sensor when the water is empty. Anything at or below this value is considered empty.

`UPDATE_INTERVAL` is the amount of time to wait in seconds for the FunHouse to check readings. By default this is once every half hour, which should be sufficient for something that changes very little over the course of a day.

```python
BOWL_STATE_TOPIC = "funhouse/catbowl/state"
LOW_VALUE = 4000
EMPTY_VALUE = 2000
UPDATE_INTERVAL = 1800	# Every 30 minutes
```

This section contains a dict of different states. This is a convenient way to change the text that is shown on the display for each of these states.

```python
# Text labels for the Display
states = {
    "empty": "Add Water",
    "low": "Low",
    "full": "Full",
}
```

This function will publish the current state of the bowl to MQTT, and thus Home Assistant. The output in this case is a raw text string value corresponding to one of the keys in the above dict that is published to the&nbsp; `BOWL_STATE_TOPIC`.

```python
def publish_bowl_state(state):
    funhouse.peripherals.led = True
    # Publish the Bowl Level State
    print("Publishing to {}".format(BOWL_STATE_TOPIC))
    funhouse.network.mqtt_publish(BOWL_STATE_TOPIC, state)
    funhouse.peripherals.led = False
```

The next couple of functions are used for changing the circle to red or green depending on the connection status.

```python
def connected(_client, _userdata, _result, _payload):
    status.fill = 0x00FF00
    status.outline = 0x008800

def disconnected(_client):
    status.fill = 0xFF0000
    status.outline = 0x880000
```

The code in the `get_bowl_reading()` function is meant to briefly enable the sensor, take a reading, and then shut it off. This is done to reduce electrolysis that may occur with the metal being in the water.

The code in the `get_bowl_state()` function just looks at the `level` value given to it, compares it to the thresholds that were set above and returns the state of the bowl.

The code in the `bowl_level_display()` function checks if the select button is held down and either returns a raw value or the text label for the current state.

```python
def get_bowl_reading():
    water_enable.value = True
    level = water_level_sensor.value
    water_enable.value = False
    return level
  
def get_bowl_state(level):
    if level &lt;= EMPTY_VALUE:
        return "empty"
    elif level &lt;= LOW_VALUE:
        return "low"
    return "full"
  
def bowl_level_display(level):
    if funhouse.peripherals.button_sel:
        return level
    return states[get_bowl_state(level)]
```

The next bit of code creates a few of the variables with their initial states, including the `funhouse` object, the `water_enable` Digital IO, the `water_level_sensor` Analog IO and creates and draws the text labels.

```python
# Set Initial States
funhouse = FunHouse(default_bg=0x0F0F00)
funhouse.peripherals.dotstars.fill(0)
water_enable = digitalio.DigitalInOut(board.A0)
water_enable.switch_to_output()
water_level_sensor = analogio.AnalogIn(board.A1)
funhouse.display.root_group = CIRCUITPYTHON_TERMINAL
funhouse.add_text(
    text="Bowl Level:",
    text_position=(120, 60),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFF0000,
    text_font="fonts/Arial-Bold-24.pcf",
)
level_label = funhouse.add_text(
    text_position=(120, 100),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.display.root_group = funhouse.graphics.root_group
```

This section initializes MQTT using the secrets, sets up the handler functions that were defined earlier, and connects. The `last_reading_timestamp` and `last_bowl_state` are then initialized and set to `None`. The `os.getenv()` function is used to get settings from settings.toml.

```python
# Initialize a new MQTT Client object
funhouse.network.init_mqtt(
    os.getenv("MQTT_BROKER"),
    os.getenv("MQTT_PORT"),
    os.getenv("MQTT_USERNAME"),
    os.getenv("MQTT_PASSWORD"),
)
funhouse.network.on_mqtt_connect = connected
funhouse.network.on_mqtt_disconnect = disconnected

print("Attempting to connect to {}".format(os.getenv("MQTT_BROKER")))
funhouse.network.mqtt_connect()

last_reading_timestamp = None
last_bowl_state = None
```

Finally, there is the main loop. In the loop, it keeps looping and waits until the `UPDATE_INTERVAL` has passed. Once it has, it gets a reading and stores it in a variable so the sensor only has to be read once. It sets the display to show the appropriate message depending on the reading.

It next checks the state of the bowl and if the value differs from the last reading, it publishes the result to MQTT.

```python
while True:
    if (
        last_reading_timestamp is None
        or time.monotonic() &gt; last_reading_timestamp + UPDATE_INTERVAL
    ):
        # Take Reading
        water_level = get_bowl_reading()
        # Update Display
        funhouse.set_text(bowl_level_display(water_level), level_label)
        # If changed, publish new result
        bowl_state = get_bowl_state(water_level)
        if bowl_state != last_bowl_state:
            publish_bowl_state(bowl_state)
            last_bowl_state = bowl_state
        last_reading_timestamp = time.monotonic()
```

# Pet Bowl Water Level Sensing

## Home Assistant Configuration

This guide assumes you already have a working and running Home Assistant server. If you don't, be sure to visit our [Set up Home Assistant with a Raspberry Pi](https://learn.adafruit.com/set-up-home-assistant-with-a-raspberry-pi) guide first.

## Check Your Add-Ons

Start out by logging in and opening up your Home Assistant dashboard and checking that the File editor is installed.&nbsp;

As part of the setup, you should have an add-on either called **configurator** or **File editor** with a wrench icon next to it. Go ahead and select it.

![temperature___humidity_File_editor.png](https://cdn-learn.adafruit.com/assets/assets/000/099/122/medium640/temperature___humidity_File_editor.png?1611960615)

If you don't see it, it may not be installed. You can find it under&nbsp; **Settings** &nbsp; **→ Add-ons** &nbsp; **→&nbsp;**** Add-on Store **&nbsp;** → **&nbsp;** File editor**&nbsp;and go through the installation procedure.

![temperature___humidity_Add_On_Store.png](https://cdn-learn.adafruit.com/assets/assets/000/099/123/medium640/temperature___humidity_Add_On_Store.png?1611960560)

If you already have it, but it's just not showing up, be sure it is started and the option to show in the sidebar is selected.

![temperature___humidity_File_Editor_Addon.png](https://cdn-learn.adafruit.com/assets/assets/000/099/124/medium640/temperature___humidity_File_Editor_Addon.png?1611960653)

## Adding the Sensor

In order to add the Water Level Sensor to Home Assistant, you'll want to add the following code to your configuration. This will create an MQTT sensor that listens on the `funhouse/catbowl/state` topic. It will translate the value it recives to one of the state labels. Feel free to update the states to your liking.

```python
mqtt:
  sensor:
  - name: "Cat Water Bowl"
    unique_id: "funhouse_catwater"
    state_topic: "funhouse/catbowl/state"
    icon: mdi:bowl
    value_template:  &gt;-
      {% set states =  {
          'empty' : 'Add Water',
          'low' : 'Water Low',
          'full' : 'Full'
      } %}
      {{ states[value] if value in states else 'Unknown' }}
```

Click the save button at the top.

![temperature___humidity_FE_Save.png](https://cdn-learn.adafruit.com/assets/assets/000/099/128/medium640/temperature___humidity_FE_Save.png?1611961553)

From the **Developer Tools** menu,&nbsp;you can check that the configuration is valid and click on **Restart** to load the configuration changes you made. You can just click **Quick reload** to reload any changes you made.

![sensors_Check_Configuration.png](https://cdn-learn.adafruit.com/assets/assets/000/124/172/medium640/sensors_Check_Configuration.png?1693502061)

![sensors_Quick_Reload.png](https://cdn-learn.adafruit.com/assets/assets/000/124/173/medium640/sensors_Quick_Reload.png?1693502078)

With the latest releases of Home Assistant, a LoveLace dashboard was added. If you haven't edited the Dashboard, it should automatically appear.

Otherwise, you may need to manually add a **Sensor** card to the dashboard.

The **Cat Water Bowl** sensor should appear under your sensors.

![sensors_Cat_Bowl_Home_Assistant.png](https://cdn-learn.adafruit.com/assets/assets/000/102/156/medium640/sensors_Cat_Bowl_Home_Assistant.png?1621007819)

## Adding Notifications

This project wouldn't be complete without having Home Assistant notify you of when the bowl gets low or empty. Home Assistant uses Persistent Notifications as its main way of notifying you, which is what we'll be showing you how to add.

Start by going to the File Editor again and click the folder icon at the top.

![sensors_File_Editor_Open.png](https://cdn-learn.adafruit.com/assets/assets/000/102/157/medium640/sensors_File_Editor_Open.png?1621008457)

Open the **automations.yaml** file.

![sensors_Automations.png](https://cdn-learn.adafruit.com/assets/assets/000/102/158/medium640/sensors_Automations.png?1621008500)

Add the following code. This will create 2 notification triggers. The first is when the state goes from **full** to **low**. The second is when it goes from any state to **empty**. Feel free to customize the messages.

```python
- id: water_low_notif
  alias: "Cat Water Low"
  trigger:
  - entity_id: sensor.cat_water_bowl
    from: "full"
    platform: state
    to: "low"
  action:
    service: persistent_notification.create
    data:
      title: "Water is Low"
      message: "Cat's water is low. Consider filling it."

- id: water_empty_notif
  alias: "Cat Water Empty"
  trigger:
  - entity_id: sensor.cat_water_bowl
    platform: state
    to: "empty"
  action:
    service: persistent_notification.create
    data:
      title: "Water is Empty"
      message: "Cat's water is empty. Fill the bowl and give your cat some love."
```

Once that's added, go ahead and check the configuration and restart the server as you did before. If you made changes to the water bowl code above, you may need to update this code to reflect those changes.

To test alerts, you may need to temporarily increase the `UPDATE_INTERVAL` in your sensor code so it checks more frequently.&nbsp;

![sensors_Alerts.png](https://cdn-learn.adafruit.com/assets/assets/000/102/159/medium640/sensors_Alerts.png?1621009028)

## Troubleshooting

If you see the icons, but there is no data, it is easiest to start by checking the MQTT messages. Adafruit has a guide on how to use [Desktop MQTT Client for Adafruit.io](https://learn.adafruit.com/desktop-mqtt-client-for-adafruit-io), which can be used for the Home Assistant MQTT server as well.

Go ahead and configure a username and password to match your MQTT server and connect. Under **subscribe** , you can subscribe to the `#` topic to get all messages.

If you are seeing messages from the sensor, you may want to double check your Home Assistant configuration.

If you don't see any messages, you will want to follow the debugging section on the **Coding the Water Sensor** page.


## Featured Products

### Adafruit FunHouse - WiFi Home Automation Development Board

[Adafruit FunHouse - WiFi Home Automation Development Board](https://www.adafruit.com/product/4985)
Home is where the heart is...it's also where we keep all our electronic bits. So why not wire it up with sensors and actuators to turn our house into an electronic wonderland. Whether it's tracking the environmental temperature and humidity in your laundry room, or notifying you when...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4985)
[Related Guides to the Product](https://learn.adafruit.com/products/4985/guides)
### Simple Water Detection Sensor with Digital Output

[Simple Water Detection Sensor with Digital Output](https://www.adafruit.com/product/4965)
Keep wet things wet&nbsp;and dry things dry by detecting when the dry things get wet by accident! This palm-sized cherry-red water sensor is simple and easy to implement in your wet-dry-sensing project.

Usage is very simple: connect the minus (-) pin to ground, connect the plus (+) pin...

In Stock
[Buy Now](https://www.adafruit.com/product/4965)
[Related Guides to the Product](https://learn.adafruit.com/products/4965/guides)
### STEMMA JST PH 2mm 3-Pin to Female Socket Cable - 200mm

[STEMMA JST PH 2mm 3-Pin to Female Socket Cable - 200mm](https://www.adafruit.com/product/3894)
This cable will let you turn a JST PH 3-pin cable port into 3 individual wires with high-quality 0.1" female header sockets on the end. We're carrying these to match up with our Hallowing, for extending and connecting sensors or LEDs - and the wires are even color coded!

<a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/3894)
[Related Guides to the Product](https://learn.adafruit.com/products/3894/guides)
### Servo Extension Cable - 50cm / 19.5" long

[Servo Extension Cable - 50cm / 19.5" long](https://www.adafruit.com/product/973)
Stretch out your servo connections with this flexible servo extension cord. It has a 3 pin shrouded "male" connection to plug your servo into and then, 50cm later, a 3 pin female connection. It even keeps the common red/black/white color coding. A great add-on to our <a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/973)
[Related Guides to the Product](https://learn.adafruit.com/products/973/guides)
### Clear Adhesive Squares - 6 pack

[Clear Adhesive Squares - 6 pack](https://www.adafruit.com/product/4813)
 **UGlu Dashes** &nbsp;are perfect for a variety of small projects. These adhesive squares provide a stronger bond to most surfaces and are cleaner and easier to remove&nbsp;without the wait, mess, or hassle.

Adheres to a wide variety of surfaces, including, but not limited...

In Stock
[Buy Now](https://www.adafruit.com/product/4813)
[Related Guides to the Product](https://learn.adafruit.com/products/4813/guides)
### Mini Magnet Feet for RGB LED Matrices (Pack of 4)

[Mini Magnet Feet for RGB LED Matrices (Pack of 4)](https://www.adafruit.com/product/4631)
Got a glorious&nbsp;RGB Matrix project you want to mount and display in your workspace or home? If you have one of the matrix panels listed below, you'll need a pack of these **Mini-Magnet Feet.** &nbsp;We got these specifically&nbsp;for our RGB LED Matrices, which no longer...

In Stock
[Buy Now](https://www.adafruit.com/product/4631)
[Related Guides to the Product](https://learn.adafruit.com/products/4631/guides)
### USB Type A to Type C Cable - 1ft - 0.3 meter

[USB Type A to Type C Cable - 1ft - 0.3 meter](https://www.adafruit.com/product/4473)
As technology changes and adapts, so does Adafruit. This&nbsp;&nbsp; **USB Type A to Type C** cable will help you with the transition to USB C, even if you're still totin' around a USB Type A hub, computer or laptop.

USB C is the latest industry-standard connector for...

In Stock
[Buy Now](https://www.adafruit.com/product/4473)
[Related Guides to the Product](https://learn.adafruit.com/products/4473/guides)

## Related Guides

- [Adafruit FunHouse](https://learn.adafruit.com/adafruit-funhouse.md)
- [Adafruit IO IOT Hub with the Adafruit FunHouse](https://learn.adafruit.com/adafruit-io-hub-with-the-adafruit-funhouse.md)
- [Using ItsaSNAP for HomeKit PIR Motion Detection](https://learn.adafruit.com/itsasnap-homekit-pir-motion-detection.md)
- [No-Code Room Occupancy Status ](https://learn.adafruit.com/no-code-room-occupancy-status.md)
- [Creating FunHouse Projects with CircuitPython](https://learn.adafruit.com/creating-funhouse-projects-with-circuitpython.md)
- [FunHouse Parking Assistant](https://learn.adafruit.com/funhouse-parking-assistant.md)
- [FunHouse 3D Printed Stand](https://learn.adafruit.com/funhouse-3d-printed-stand.md)
- [Quickstart: Adafruit IO WipperSnapper ](https://learn.adafruit.com/quickstart-adafruit-io-wippersnapper.md)
- [Using the Adafruit FunHouse with Home Assistant](https://learn.adafruit.com/using-the-adafruit-funhouse-with-home-assistant.md)
- [CircuitPython Web Workflow Code Editor Quick Start](https://learn.adafruit.com/getting-started-with-web-workflow-using-the-code-editor.md)
- [Motion Activated Outlet with the Adafruit FunHouse](https://learn.adafruit.com/motion-activated-outlet-with-the-adafruit-funhouse.md)
- [Track a Turtle with WipperSnapper](https://learn.adafruit.com/track-a-turtle-with-wippersnapper.md)
- [Karel The Robot In CircuitPython](https://learn.adafruit.com/karel-the-robot-in-circuitpython.md)
- [No-Code WipperSnapper Action Counter](https://learn.adafruit.com/no-code-wippersnapper-action-counter.md)
- [Funhouse Door Alert with Email Notification](https://learn.adafruit.com/funhouse-door-alert-email-notification.md)
- [No-Code WipperSnapper IoT Power Switch Outlet](https://learn.adafruit.com/no-code-wippersnapper-iot-power-switch-outlet.md)
