Now let's go over the code that runs on the sensor. The code checks the temperature and humidity, formats it, then publishes directly to the MQTT server.

MQTT Settings in settings.toml

Since the code publishes directly to the MQTT server, there are a few more 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 setup to be password protected by default.

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

Temperature Reading

You may notice the temperature comes across a bit higher than the actual room temperature. To see some techniques to improve it, take a look at our Temperature Logger example.

Download the Project Bundle

Your project will use a specific set of CircuitPython libraries and the code.py file. In order to get the libraries you need, click on the Download Project Bundle link below, and uncompress the .zip file.

Next, drag the contents of the uncompressed bundle directory onto you microcontroller board's CIRCUITPY drive, replacing any existing files or directories with the same names, and adding any new ones that are necessary.

The files on your FunHouse should look like this:

# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import os
import time
import json
from displayio import CIRCUITPYTHON_TERMINAL
from adafruit_display_shapes.circle import Circle
from adafruit_funhouse import FunHouse


PUBLISH_DELAY = 60
ENVIRONMENT_CHECK_DELAY = 5
ENABLE_PIR = True
MQTT_TOPIC = "funhouse/state"
LIGHT_STATE_TOPIC = "funhouse/light/state"
LIGHT_COMMAND_TOPIC = "funhouse/light/set"
INITIAL_LIGHT_COLOR = 0x008000
USE_FAHRENHEIT = True

funhouse = FunHouse(default_bg=0x0F0F00)
funhouse.peripherals.dotstars.fill(INITIAL_LIGHT_COLOR)

# Don't display the splash yet to avoid
# redrawing labels after each one is added
funhouse.display.root_group = CIRCUITPYTHON_TERMINAL

# Add the labels
funhouse.add_text(
    text="Temperature:",
    text_position=(20, 30),
    text_color=0xFF8888,
    text_font="fonts/Arial-Bold-24.pcf",
)
temp_label = funhouse.add_text(
    text_position=(120, 60),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Humidity:",
    text_position=(20, 100),
    text_color=0x8888FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
hum_label = funhouse.add_text(
    text_position=(120, 130),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Pressure:",
    text_position=(20, 170),
    text_color=0xFF88FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
pres_label = funhouse.add_text(
    text_position=(120, 200),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)

# Now display the splash to draw all labels at once
funhouse.display.root_group = funhouse.splash

status = Circle(229, 10, 10, fill=0xFF0000, outline=0x880000)
funhouse.splash.append(status)

def connected(client, _userdata, _result, _payload):
    status.fill = 0x00FF00
    status.outline = 0x008800
    print("Connected to MQTT! Subscribing...")
    client.subscribe(LIGHT_COMMAND_TOPIC)


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


def message(_client, topic, payload):
    print("Topic {0} received new value: {1}".format(topic, payload))
    if topic == LIGHT_COMMAND_TOPIC:
        settings = json.loads(payload)
        if settings["state"] == "on":
            if "brightness" in settings:
                funhouse.peripherals.dotstars.brightness = settings["brightness"] / 255
            else:
                funhouse.peripherals.dotstars.brightness = 0.3
            if "color" in settings:
                funhouse.peripherals.dotstars.fill(settings["color"])
        else:
            funhouse.peripherals.dotstars.brightness = 0
        publish_light_state()


def publish_light_state():
    funhouse.peripherals.led = True
    publish_output = {
        "brightness": round(funhouse.peripherals.dotstars.brightness * 255),
        "state": "on" if funhouse.peripherals.dotstars.brightness > 0 else "off",
        "color": funhouse.peripherals.dotstars[0],
    }
    # Publish the Dotstar State
    print("Publishing to {}".format(LIGHT_STATE_TOPIC))
    funhouse.network.mqtt_publish(LIGHT_STATE_TOPIC, json.dumps(publish_output))
    funhouse.peripherals.led = False

# 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
funhouse.network.on_mqtt_message = message

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

last_publish_timestamp = None

last_peripheral_state = {
    "button_up": funhouse.peripherals.button_up,
    "button_down": funhouse.peripherals.button_down,
    "button_sel": funhouse.peripherals.button_sel,
    "captouch6": funhouse.peripherals.captouch6,
    "captouch7": funhouse.peripherals.captouch7,
    "captouch8": funhouse.peripherals.captouch8,
}

if ENABLE_PIR:
    last_peripheral_state["pir_sensor"] = funhouse.peripherals.pir_sensor

environment = {}
last_environment_timestamp = time.monotonic()

# Provide Initial light state
publish_light_state()

while True:
    if not environment or (
        time.monotonic() - last_environment_timestamp > ENVIRONMENT_CHECK_DELAY
    ):
        temp = funhouse.peripherals.temperature
        unit = "C"
        if USE_FAHRENHEIT:
            temp = temp * (9 / 5) + 32
            unit = "F"

        environment["temperature"] = temp
        environment["pressure"] = funhouse.peripherals.pressure
        environment["humidity"] = funhouse.peripherals.relative_humidity
        environment["light"] = funhouse.peripherals.light

        funhouse.set_text("{:.1f}{}".format(environment["temperature"], unit), temp_label)
        funhouse.set_text("{:.1f}%".format(environment["humidity"]), hum_label)
        funhouse.set_text("{}hPa".format(environment["pressure"]), pres_label)
        last_environment_timestamp = time.monotonic()
    output = environment

    peripheral_state_changed = False
    for peripheral in last_peripheral_state:
        current_item_state = getattr(funhouse.peripherals, peripheral)
        output[peripheral] = "on" if current_item_state else "off"
        if last_peripheral_state[peripheral] != current_item_state:
            peripheral_state_changed = True
            last_peripheral_state[peripheral] = current_item_state

    if funhouse.peripherals.slider is not None:
        output["slider"] = funhouse.peripherals.slider
        peripheral_state_changed = True

    # Every PUBLISH_DELAY, write temp/hum/press/light or if a peripheral changed
    if (
        last_publish_timestamp is None
        or peripheral_state_changed
        or (time.monotonic() - last_publish_timestamp) > PUBLISH_DELAY
    ):
        funhouse.peripherals.led = True
        print("Publishing to {}".format(MQTT_TOPIC))
        funhouse.network.mqtt_publish(MQTT_TOPIC, json.dumps(output))
        funhouse.peripherals.led = False
        last_publish_timestamp = time.monotonic()

    # Check any topics we are subscribed to
    funhouse.network.mqtt_loop(0.5)

How the Code Works

First there are our imports. Many of the imports include built-in modules such as json as well as the adafruit_display_shapes, and the adafruit_funhouse libraries.

import os
import time
import json
from adafruit_display_shapes.circle import Circle
from adafruit_funhouse import FunHouse

In the next section, there are quite a few settings that you can adjust.

First, the PUBLISH_DELAY setting is the amount of time in seconds to wait before updating the temperature and humidity.

The ENVIRONMENT_CHECK_DELAY is the amount of time to delay in between reading the environmental sensors such as temperature and humidity and updating the labels. The reason we have a delay is to give time to other events.

The ENABLE_PIR setting can be set to False if you either do not have a PIR sensor or would not like the sensor to automatically trigger anything.

The MQTT_TOPIC is the topic that holds the state of the FunHouse sensors. To read more about MQTT Topics, you can check out the MQTT Topics section of our All the Internet of Things Protocols guide.

The LIGHT_STATE_TOPIC is the topic that holds the state of the DotStar LEDs and is tells Home Assistant what the current state of the LEDS is to allow it to act like an RGB bulb.

The LIGHT_COMMAND_TOPIC is the topic that the FunHouse listens to in order to change the state of the DotStar LEDs through Home Assistant.

The INITIAL_LIGHT_COLOR setting is the initial color of the DotStar LEDs.

If USE_FAHRENHEIT is set to True, the temperature displayed on the screen will be in Fahrenheit. Changing this setting also affects the units that are sent to Home Assistant.

PUBLISH_DELAY = 60
ENVIRONMENT_CHECK_DELAY = 5
ENABLE_PIR = True
MQTT_TOPIC = "funhouse/state"
LIGHT_STATE_TOPIC = "funhouse/light/state"
LIGHT_COMMAND_TOPIC = "funhouse/light/set"
INITIAL_LIGHT_COLOR = 0x008000
USE_FAHRENHEIT = True

Next the FunHouse is initialized with a default background and the INITIAL_LIGHT_COLOR.

funhouse = FunHouse(default_bg=0x0F0F00)
funhouse.peripherals.dotstars.fill(INITIAL_LIGHT_COLOR)

In this next section, the display labels are created. funhouse.display.root_group = CIRCUITPYTHON_TERMINAL is called first first so that it doesn't draw each label sequentially and end the section with funhouse.display.root_group = funhouse.splash to trigger drawing everything that's in the splash group, which is the group all labels are added to when created.

funhouse.display.root_group = CIRCUITPYTHON_TERMINAL
funhouse.add_text(
    text="Temperature:",
    text_position=(20, 30),
    text_color=0xFF8888,
    text_font="fonts/Arial-Bold-24.pcf",
)
temp_label = funhouse.add_text(
    text_position=(120, 60),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Humidity:",
    text_position=(20, 100),
    text_color=0x8888FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
hum_label = funhouse.add_text(
    text_position=(120, 130),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.add_text(
    text="Pressure:",
    text_position=(20, 170),
    text_color=0xFF88FF,
    text_font="fonts/Arial-Bold-24.pcf",
)
pres_label = funhouse.add_text(
    text_position=(120, 200),
    text_anchor_point=(0.5, 0.5),
    text_color=0xFFFF00,
    text_font="fonts/Arial-Bold-24.pcf",
)
funhouse.display.root_group = funhouse.splash

Next the script creates the circle to indicated whether the board is connected to the MQTT server or not. It is created with a default color of red.

status = Circle(229, 10, 10, fill=0xFF0000, outline=0x880000)
funhouse.splash.append(status)

After that are the MQTT connect and disconnect handlers. These handle updating the connection status indicator and subscribing to any topics.

def connected(client, _userdata, _result, _payload):
    status.fill = 0x00FF00
    status.outline = 0x008800
    print("Connected to MQTT! Subscribing...")
    client.subscribe(LIGHT_COMMAND_TOPIC)


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

For the message handler, it will wait for the any new message that it is subscribed to. Then it will make sure the topic is the value of the LIGHT_COMMAND_TOPIC before proceeding. Next it will decode the payload as JSON. If the state is "on", it will look for additional settings in the payload.

If it finds brightness, it will convert it from 0-255 to 0-1.0 and set the DotStars to that brightness. If it finds color, it will set the DotStars to that color using the fill() command. After it changes the DotStars, it will publish the light state so the Home Assistant UI can update its settings.

def message(_client, topic, payload):
    print("Topic {0} received new value: {1}".format(topic, payload))
    if topic == LIGHT_COMMAND_TOPIC:
        settings = json.loads(payload)
        print(settings)
        if settings["state"] == "on":
            if "brightness" in settings:
                funhouse.peripherals.dotstars.brightness = settings["brightness"] / 255
            else:
                funhouse.peripherals.dotstars.brightness = 0.3
            if "color" in settings:
                funhouse.peripherals.dotstars.fill(settings["color"])
        else:
            funhouse.peripherals.dotstars.brightness = 0
        publish_light_state()

The publish_light_state() function will gather the current state of the DotStars and publish it in a way that is meaningful to Home Assistant.

def publish_light_state():
    funhouse.peripherals.led = True
    publish_output = {
        "brightness": round(funhouse.peripherals.dotstars.brightness * 255),
        "state": "on" if funhouse.peripherals.dotstars.brightness > 0 else "off",
        "color": funhouse.peripherals.dotstars[0],
    }
    # Publish the Dotstar State
    print("Publishing to {}".format(LIGHT_STATE_TOPIC))
    funhouse.network.mqtt_publish(LIGHT_STATE_TOPIC, json.dumps(publish_output))
    funhouse.peripherals.led = False

With the functions all defined, MQTT is initialized in the FunHouse library using the settings in the secrets file. The handler function are then set and the code attempts to connect to the MQTT server. The os.getenv() function is used to get settings from settings.toml.

# 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
funhouse.network.on_mqtt_message = message

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

After that, some data variables are set up with initial states. This includes a variable to hold the last time that we published the general FunHouse state to MQTT and the last values of the peripheral so we can monitor when they change.

We also update the environment and display with the update_enviro() function we defined earlier.

Finally we publish the current state of the DotStars with publish_light_state().

last_publish_timestamp = None

last_peripheral_state = {
    "button_up": funhouse.peripherals.button_up,
    "button_down": funhouse.peripherals.button_down,
    "button_sel": funhouse.peripherals.button_sel,
    "captouch6": funhouse.peripherals.captouch6,
    "captouch7": funhouse.peripherals.captouch7,
    "captouch8": funhouse.peripherals.captouch8,
}

if ENABLE_PIR:
    last_peripheral_state["pir_sensor"] = funhouse.peripherals.pir_sensor

environment = {}
last_environment_timestamp = time.monotonic()

# Provide Initial light state
publish_light_state()

Now we get to the main loop.

First the code checks if the amount of time in ENVIRONMENT_CHECK_DELAY has passed and if so, it will gather the environmental and light sensor settings, change the temperature to Fahrenheit if set to do so, update the environment dictionary, and change the labels on the display. The current environment dictionary is used as the basis for the output data.

if not environment or (time.monotonic() - last_environment_timestamp > ENVIRONMENT_CHECK_DELAY):
    temp = funhouse.peripherals.temperature
    unit = "C"
    if USE_FAHRENHEIT:
        temp = temp * (9 / 5) + 32
        unit = "F"

    environment["temperature"] = temp
    environment["pressure"] = funhouse.peripherals.pressure
    environment["humidity"] = funhouse.peripherals.relative_humidity
    environment["light"] = funhouse.peripherals.light

    funhouse.set_text("{:.1f}{}".format(environment["temperature"], unit), temp_label)
    funhouse.set_text("{:.1f}%".format(environment["humidity"]), hum_label)
    funhouse.set_text("{}hPa".format(environment["pressure"]), pres_label)
    last_environment_timestamp = time.monotonic()
output = environment

In the next section each of the peripherals is checked and updated. If anything has changed, the peripheral_state_changed variable is set to True which triggers publishing an update a bit later on.

peripheral_state_changed = False
for peripheral in last_peripheral_state:
    current_item_state = getattr(funhouse.peripherals, peripheral)
    output[peripheral] = "on" if current_item_state else "off"
    if last_peripheral_state[peripheral] != current_item_state:
        peripheral_state_changed = True
        last_peripheral_state[peripheral] = current_item_state

Since the slider returns a number between 0-1 or None if not touched, this needs to be checked separately from the other Peripherals and is only added if it is being used.

if funhouse.peripherals.slider is not None:
    output["slider"] = funhouse.peripherals.slider
    peripheral_state_changed = True

If the peripheral_state_changed variable is True or the amount of time in PUBLISH_DELAY has elapsed, the state of the FunHouse is published.

if (
    last_publish_timestamp is None
    or peripheral_state_changed
    or (time.monotonic() - last_publish_timestamp) > PUBLISH_DELAY
):
    funhouse.peripherals.led = True
    print("Publishing to {}".format(MQTT_TOPIC))
    funhouse.network.mqtt_publish(MQTT_TOPIC, json.dumps(output))
    funhouse.peripherals.led = False
    last_publish_timestamp = time.monotonic()

Finally the MQTT loop is run. In order to increase the responsiveness of the buttons, a timeout value of 0.5 seems to work well. If the value is too small, it won't have enough time to respond to MQTT messages and if it is too large, it is possible to miss peripheral change events.

# Check any topics we are subscribed to
funhouse.network.mqtt_loop(0.5)

Debugging the Sensor

If you would like to monitor what the sensor is doing, you can look at our guide on Connecting to the Serial Console with CircuitPython. Once you are connected, it can help with any troubleshooting.

This guide was first published on Apr 22, 2021. It was last updated on Mar 28, 2024.

This page (Code the Sensor) was last updated on Mar 28, 2024.

Text editor powered by tinymce.