I wanted to control a Dual Govee Smart Plug and saw one of Lady Ada shows, showing off her latest design the STHS34PF80 ID #6426. So built one that would control a Govee Dual Smart Plug.
REQUIRED: you must have a Govee account and apply for a Govee API key thru the phone app only. You make a request and they will email you an API key... Don't loose it. You can over load their API so keep your request to a minimum. They will throttle you account if you get carried away.
Object of this project: I wanted to control a Govee Dual Smart Plug. The plug is used to turn on all my Adafruit projects in my office. So when I leave they all turn off and back on when I enter my office. This sensor is fairly sensitive and I can be about 10-12 feet away when it senses me. The sensitivity various with room temperature. Its not perfect, Its like the sensor gets use to you in the room and starts to ignore you unless you move around a lot or leave the room for a bit. Its sensing the heat around the room
Programming: I can NOT take total credit for programming this. I spent many, many hours coding and working with Copilot. Together we came up with what appears solid. I spent about 3 weeks on and off working on this project. You can add your own ideas in.
Parts are:
- Adafruit STHS34PF80 IR Presence / Motion Sensor - STEMMA QT / Qwiic ID 6426
- Adafruit ESP32-S3 Revers TFT Feather ID 5691
- Stemma QT / QWii JST SH 4-Pin ID 4399
OS is CircuitPython version 10.0.3 as of 2-2026
The object of this project design was simple
- Display the current date and time since it will be sitting on my desk
- Initialize the time and sensor
- Display option below for 5 seconds. If a selection is not made then select the last selected mode.
- Three buttons in the from to
- Button D0 to select Outlet A
- Button D1 to select Outlet B
- Button D2 to select Both Outlets A & B
- Once a option is selected lock out the buttons until the unit is rebooted or power off.
- Three buttons in the from to
- Once the unit has power one it should display the following
- Date and time
- A green pixel (i am alive) flashes
- Flashes blue every 30 seconds to insure the Internet is still alive
- Turns red if the internet goes down and returns green once alive again
- Display which Outlet is on or off Green for ON, Red for OFF
- A ON, A OFF | B ON, B OFF | Both On, Both OFF
- Display in english Plug A On/Off | Plug B On/Off | Plug Both On/Off
- If the sensor detects movement or present it will send a Govee Smart Plug command out the internet
- If the sensor no longer sees movement or presents then the following happens
- Program wait for 10 cycles and if movement or presents is detected resets to true
- If after 10 cycles and no movement or presents is detected then a countdown timer is started
- The count down timer will be displayed in the lower left for 150secs.
- Should the timer count to zero the Govee command to turn off is sent out to the internet
- If for the sensor see movement or presents then the timer is reset and terminated until there is no movement or presents.
- Turn off the Display at 10pm and turn it back on at 8am. Just to save the display wear.
- I used the Ruiz Brothers 3D Case (IoT Battery Monitor) and modified the size of the face & rear place to make room for the IR Sensor. I used FreeCad to make the modification. I liked how the case back panel snapped in and I didn't know how this was done do I slice the case in half and added about 1/2" to the original .stp file. Came out great. I hope the Reiz Brothers don't mind, you guys ROCK!
Below is the code I used and I am still very new at all this so if you think I did something wrong let me know
import time
import board
import wifi
import os
import digitalio
import displayio
import terminalio
import microcontroller
import neopixel
import adafruit_ntp
import rtc
from adafruit_display_text import label
import adafruit_connection_manager
import adafruit_requests
import adafruit_sths34pf80
from presence_plug_controller import PresencePlugController
# --- Control Display Backlight ---
display_is_off = False
# --- Wi-Fi ---
SSID = os.getenv("CIRCUITPY_WIFI_SSID")
PASS = os.getenv("CIRCUITPY_WIFI_PASSWORD")
GOVEE_KEY = os.getenv("GOVEE_API_KEY")
# --- Timezone ---
val = os.getenv("TZ_OFFSET", "-7")
try:
TZ_OFFSET = int(val.strip().replace('"', '').replace("'", ""))
except Exception:
TZ_OFFSET = -7
# --- Govee Devices ---
GOVEE_DEVICES = {
"A": {"device": os.getenv("DEVICE_1"), "model": os.getenv("MODEL_1")},
"B": {"device": os.getenv("DEVICE_2"), "model": os.getenv("MODEL_2")},
"C": {"device": os.getenv("DEVICE_3"), "model": os.getenv("MODEL_3")},
}
# --- Buttons ---
button_a = digitalio.DigitalInOut(board.BUTTON)
button_a.switch_to_input(pull=digitalio.Pull.UP)
button_b = digitalio.DigitalInOut(board.D1)
button_b.switch_to_input(pull=digitalio.Pull.DOWN)
button_c = digitalio.DigitalInOut(board.D2)
button_c.switch_to_input(pull=digitalio.Pull.DOWN)
# --- Button state tracking ---
last_button_a = False
last_button_b = False
last_button_c = False
def check_button_selection():
global last_button_a, last_button_b, last_button_c
current_a = not button_a.value
current_b = button_b.value
current_c = button_c.value
selection = None
if current_a and not last_button_a:
selection = "A"
elif current_b and not last_button_b:
selection = "B"
elif current_c and not last_button_c:
selection = "C"
last_button_a = current_a
last_button_b = current_b
last_button_c = current_c
if selection:
microcontroller.nvm[0] = ord(selection)
return selection
return None
# --- NeoPixel Heartbeat ---
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
heartbeat = False
last_heartbeat = time.monotonic()
# --- LED ---
led = digitalio.DigitalInOut(board.LED)
led.switch_to_output(value=False)
# --- Display ---
display = board.DISPLAY
group = displayio.Group()
display.root_group = group
text_label = label.Label(terminalio.FONT, text="Initializing...", x=10, y=display.height - 30, scale=2)
group.append(text_label)
status_label = label.Label(
terminalio.FONT,
text="",
scale=4,
color=0xFFFFFF,
anchor_point=(0.5, 0.5),
anchored_position=(display.width // 2, display.height // 2)
)
group.append(status_label)
countdown_label = label.Label(
terminalio.FONT,
text="",
scale=2,
color=0xFFFF00,
anchor_point=(1.0, 1.0),
anchored_position=(display.width - 5, display.height - 5)
)
group.append(countdown_label)
# --- Date/Time Label ---
datetime_label = label.Label(
terminalio.FONT,
text="",
scale=2,
color=0x00FFFF,
anchor_point=(0.5, 0.0),
anchored_position=(display.width // 2, 5)
)
group.append(datetime_label)
# --- TFT Heartbeat Dot ---
heartbeat_bitmap = displayio.Bitmap(6, 6, 2)
heartbeat_palette = displayio.Palette(2)
heartbeat_palette[0] = 0x000000
heartbeat_palette[1] = 0x00FF00
for x in range(6):
for y in range(6):
heartbeat_bitmap[x, y] = 1
heartbeat_tile = displayio.TileGrid(
heartbeat_bitmap,
pixel_shader=heartbeat_palette,
x=display.width - 10,
y=10
)
group.append(heartbeat_tile)
tft_heartbeat = False
last_tft_heartbeat = time.monotonic()
# --- Internet health state ---
internet_ok = True
ping_flash_until = 0
# --- Connect Wi-Fi ---
print(f"Connecting to {SSID}...")
wifi.radio.connect(SSID, PASS)
print("Connected to Wi-Fi:", wifi.radio.ipv4_address)
# --- Create ONE socket pool ---
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
# --- NTP Time Sync ---
print("Syncing time with NTP...")
ntp = adafruit_ntp.NTP(pool, tz_offset=TZ_OFFSET)
rtc.RTC().datetime = ntp.datetime
print("Time synced:", time.localtime())
# --- HTTPS session ---
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
requests.timeout = 5
# --- Sensor ---
i2c = board.I2C()
sths = adafruit_sths34pf80.STHS34PF80(i2c)
# --- Controller ---
controller = PresencePlugController(
sensor=sths,
requests=requests,
devices=GOVEE_DEVICES,
api_key=GOVEE_KEY
)
controller.set_display_label(text_label)
controller.set_status_label(status_label)
controller.set_countdown_label(countdown_label)
controller.set_led(led)
# --- Prompt for button selection ---
selection = None
selection_locked = False
text_label.text = "Select an option\nButton A, B, or C"
text_label.y = display.height - 45
status_label.text = ""
start_time = time.monotonic()
while (time.monotonic() - start_time) < 5:
selection = check_button_selection()
if selection:
print(f"Button pressed during prompt: {selection}")
controller.set_active_device(selection)
button_a.switch_to_input()
button_b.switch_to_input()
button_c.switch_to_input()
selection_locked = True
break
time.sleep(0.05)
# --- Restore last plug selection ---
try:
if not selection:
stored = microcontroller.nvm[0]
if stored in (ord("A"), ord("B"), ord("C")):
default_key = chr(stored)
print(f"Restoring last selected plug: {default_key}")
controller.set_active_device(default_key)
else:
print(f"NVM[0] invalid: {stored} — defaulting to A")
controller.set_active_device("A")
except IndexError:
if not selection:
print("NVM[0] not initialized — defaulting to A")
controller.set_active_device("A")
# --- Keepalive timer ---
last_ping = time.monotonic()
# --- Clock update timer ---
last_clock_update = 0
# --- Main loop ---
print("Starting motion detection loop...")
print("Raw NVM[0] value:", microcontroller.nvm[0])
text_label.y = display.height - 15
while True:
if not selection_locked:
selection = check_button_selection()
if selection:
print("Button pressed:", selection)
if selection == "A":
controller.set_active_device("A")
elif selection == "B":
controller.set_active_device("B")
elif selection == "C":
print("[DEBUG] Calling set_both_outlets(turn_on=True) from code.py")
if hasattr(controller, "set_both_outlets"):
controller.set_both_outlets(turn_on=True)
else:
print("set_both_outlets() not implemented in controller!")
button_a.switch_to_input()
button_b.switch_to_input()
button_c.switch_to_input()
selection_locked = True
time.sleep(0.5)
# --- Wi-Fi keepalive every 30 seconds ---
now = time.monotonic()
if now - last_ping > 30:
try:
print("Pinging Wi-Fi...")
ping_flash_until = time.monotonic() + 0.5
requests.get("http://connectivitycheck.gstatic.com/generate_204", timeout=3)
print("Ping OK")
internet_ok = True
except Exception as e:
print("Ping failed:", e)
internet_ok = False
last_ping = now
# --- TFT Heartbeat Logic ---
now = time.monotonic()
if not internet_ok:
heartbeat_palette[1] = 0xFF0000
last_tft_heartbeat = now
else:
if now < ping_flash_until:
heartbeat_palette[1] = 0x0000FF
else:
if now - last_tft_heartbeat > 1:
tft_heartbeat = not tft_heartbeat
heartbeat_palette[1] = 0x00FF00 if tft_heartbeat else 0x000000
last_tft_heartbeat = now
# --- NeoPixel Heartbeat ---
now = time.monotonic()
if not internet_ok:
pixel[0] = (50, 0, 0)
elif now < ping_flash_until:
pixel[0] = (0, 0, 50)
else:
if now - last_heartbeat > 1:
heartbeat = not heartbeat
pixel[0] = (0, 50, 0) if heartbeat else (0, 0, 0)
last_heartbeat = now
# --- Date/Time Display (update once per second) ---
now = time.monotonic()
if now - last_clock_update >= 1:
now_struct = time.localtime()
hour_12 = now_struct.tm_hour % 12
if hour_12 == 0:
hour_12 = 12
am_pm = "a" if now_struct.tm_hour < 12 else "p"
month_names = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
day = now_struct.tm_mday
if 11 <= day <= 13:
suffix = "th"
else:
suffix = {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")
month_str = month_names[now_struct.tm_mon - 1]
datetime_label.text = "{} {}{} {:2d}:{:02d}{}".format(
month_str, day, suffix,
hour_12, now_struct.tm_min, am_pm
)
last_clock_update = now
# --- Auto display sleep/wake ---
hour = now_struct.tm_hour
if (hour >= 22 or hour < 6):
if not display_is_off:
print("Turning display OFF for night mode")
display.brightness = 0.0
display_is_off = True
else:
if display_is_off:
print("Turning display ON for daytime")
display.brightness = 1.0
display_is_off = False
controller.update()
time.sleep(0.02)
import time
import json
import wifi
import os
class PresencePlugController:
def __init__(self, sensor, requests, devices, api_key,
debounce_sec=0.12, timeout_sec=120, min_api_interval=5):
self.sensor = sensor
self.requests = requests
self.devices = devices
self.api_key = api_key
self.debounce_sec = debounce_sec
self.timeout_sec = timeout_sec
self.min_api_interval = min_api_interval
self.device_id = None
self.model_id = None
self.current_key = None
self.last_change_candidate = 0
self.last_motion_time = 0
self.last_api_time = 0
self.motion_state = False
self.last_raw = self.sensor.presence
self.display_label = None
self.status_label = None
self.countdown_label = None
self.led = None
self.candidate_state = None
self.committed_state = None
self.last_candidate_change = 0.0
self.consecutive_false_count = 0
self.required_consecutive_false = 10
self.device_states = {key: None for key in self.devices}
# --- UI hooks ---
def set_status_label(self, lbl):
self.status_label = lbl
def set_countdown_label(self, lbl):
self.countdown_label = lbl
def set_display_label(self, label_obj):
self.display_label = label_obj
def set_led(self, led_obj):
self.led = led_obj
def set_both_outlets(self, turn_on=True):
print(f"[DEBUG] set_both_outlets called with turn_on={turn_on}")
"""
Send a Govee API command to turn both outlets ON or OFF at the same time.
"""
headers = {
"Content-Type": "application/json",
"Govee-API-Key": self.api_key
}
# Hardcoded device/model for both outlets (update if needed)
device_id = "2A:FE:60:74:F4:54:97:7A"
model_id = "H5082"
value = "on" if turn_on else "off"
body = {
"device": device_id,
"model": model_id,
"cmd": {
"name": "turn",
"value": value
}
}
# Update display label immediately
if self.display_label:
self.display_label.text = f"Both Plugs {'On' if turn_on else 'Off'}"
print(f"Sending BOTH OUTLETS {value.upper()} command: {body}")
try:
response = self.requests.put(
"https://developer-api.govee.com/v1/devices/control",
headers=headers,
data=json.dumps(body),
timeout=5
)
print("Status:", response.status_code)
print("Response:", response.text)
if self.status_label:
self.status_label.text = f"Both {value.upper()}"
self.status_label.color = 0x00FF00 if turn_on else 0xFF0000
except Exception as e:
print("Govee BOTH OUTLETS command failed:", e)
# --- Device selection ---
def set_active_device(self, key):
if key in self.devices:
self.device_id = self.devices[key]["device"]
self.model_id = self.devices[key]["model"]
self.current_key = key
print(f"Switched to Plug {key}: {self.device_id}")
self.update_display("Off")
if self.status_label:
if key == "C":
self.status_label.text = "Both OFF"
else:
self.status_label.text = f"{key} OFF"
self.status_label.color = 0xFF0000
self.motion_state = False
self.device_states[key] = None
else:
print(f"Device key {key} not found")
def update_display(self, state):
if self.display_label and self.current_key:
if self.current_key == "C":
self.display_label.text = f"Both Plugs {state}"
else:
self.display_label.text = f"Plug {self.current_key} {state}"
# --- Govee payload ---
def build_payload(self, value):
return {
"device": self.device_id,
"model": self.model_id,
"cmd": {
"name": "toggle",
"value": value
}
}
# --- Govee API with Wi-Fi keepalive ---
def send_govee_put(self, value):
desired_state = "on" if value == "1_1" else "off"
if self.status_label:
outlet = self.current_key if self.current_key else "?"
# Show 'Both ON/OFF' for C, 'A ON/OFF' or 'B ON/OFF' for A/B
if outlet == "C":
if value == "1_1":
self.status_label.text = "Both ON"
self.status_label.color = 0x00FF00
else:
self.status_label.text = "Both OFF"
self.status_label.color = 0xFF0000
elif outlet in ("A", "B"):
if value == "1_1":
self.status_label.text = f"{outlet} ON"
self.status_label.color = 0x00FF00
else:
self.status_label.text = f"{outlet} OFF"
self.status_label.color = 0xFF0000
else:
if value == "0_1":
self.status_label.text = f"Outlet {outlet} ON"
self.status_label.color = 0x00FF00
else:
self.status_label.text = f"Outlet {outlet} OFF"
self.status_label.color = 0xFF0000
current_state = self.device_states.get(self.current_key)
if current_state == desired_state:
print(f"Skipping redundant '{desired_state}' command for device {self.current_key}")
return
now = time.monotonic()
if now - self.last_api_time < self.min_api_interval:
print("Skipping API call: too soon")
return
self.last_api_time = now
# Wi-Fi keepalive before API call
try:
print("Pinging Wi-Fi before PUT...")
self.requests.get(
"http://connectivitycheck.gstatic.com/generate_204",
timeout=3
)
except Exception as e:
print("Ping failed, reconnecting:", e)
try:
wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"),
os.getenv("CIRCUITPY_WIFI_PASSWORD"))
print("Reconnected Wi-Fi")
except Exception as e2:
print("Reconnect failed:", e2)
return
headers = {
"Content-Type": "application/json",
"Govee-API-Key": self.api_key
}
body = self.build_payload(value)
print("Sending PUT:", body)
try:
response = self.requests.put(
"https://developer-api.govee.com/v1/devices/control",
headers=headers,
data=json.dumps(body),
timeout=5
)
print("Status:", response.status_code)
print("Response:", response.text)
self.device_states[self.current_key] = desired_state
if self.led:
self.led.value = (value == "1_1")
self.update_display("On" if value == "1_1" else "Off")
except Exception as e:
print("Govee PUT failed:", e)
# --- Presence logic ---
def update(self):
if not self.sensor.data_ready or not self.device_id:
return
now = time.monotonic()
raw = bool(self.sensor.presence or self.sensor.motion)
print(raw)
if self.candidate_state is None:
self.candidate_state = raw
self.last_candidate_change = now
self.consecutive_false_count = 0 if raw else 1
if raw:
self.consecutive_false_count = 0
else:
self.consecutive_false_count += 1
if raw:
candidate = True
else:
if self.consecutive_false_count >= self.required_consecutive_false:
candidate = False
else:
candidate = self.candidate_state
if candidate != self.candidate_state:
self.candidate_state = candidate
self.last_candidate_change = now
return
if (now - self.last_candidate_change) < self.debounce_sec:
return
if candidate != self.committed_state:
self.committed_state = candidate
print("Committed presence:", self.committed_state)
if self.committed_state:
self.last_motion_time = now
if not self.motion_state:
self.motion_state = True
# Turn ON selected outlet or both if 'C'
if self.current_key == "C":
self.set_both_outlets(turn_on=True)
else:
self.send_govee_put("1_1")
else:
self.last_motion_time = now
# Do NOT turn off yet; wait for timeout before sending OFF command and updating label
return
if self.committed_state:
self.motion_state = True
if self.countdown_label:
self.countdown_label.text = ""
self.last_motion_time = now
return
if not self.committed_state and self.motion_state:
remaining = int(self.timeout_sec - (now - self.last_motion_time))
if remaining < 0:
remaining = 0
if self.countdown_label:
self.countdown_label.text = f"{remaining}s"
# Do NOT update status label to OFF here; only after timeout
else:
if self.countdown_label:
self.countdown_label.text = ""
if self.motion_state and (now - self.last_motion_time >= self.timeout_sec):
if self.current_key == "C":
print("Occupancy timeout reached -> sending BOTH OFF")
self.set_both_outlets(turn_on=False)
else:
print(f"Occupancy timeout reached -> sending {self.current_key} OFF")
self.send_govee_put("1_0")
self.motion_state = False
return
CIRCUITPY_WIFI_SSID = "SSID" CIRCUITPY_WIFI_PASSWORD = "Wi-Fi Password" CIRCUITPY_WEB_API_PASSWORD = "password" CIRCUITPY_WEB_API_PORT = 80 GOVEE_API_KEY = "Govee User API Key" DEVICE_1 = "Govee Mac address" MODEL_1 = "H5082" DST = "True" TZ_OFFSET = "-7"
This page (IR-Motion Sensor for Govee Smart Plug) was last updated on February 19, 2026.