Skip to content

Instantly share code, notes, and snippets.

@Nama
Created January 24, 2025 22:42
Show Gist options
  • Save Nama/225c13adae917a02418d15732f2a04fb to your computer and use it in GitHub Desktop.
Save Nama/225c13adae917a02418d15732f2a04fb to your computer and use it in GitHub Desktop.
doorbell sensor to send MQTT messages if it rings
import wifi
import network
import ubinascii
from time import sleep, sleep_ms, time
from machine import ADC, unique_id
from umqtt.simple import MQTTClient
from umqtt.simple import MQTTException
server = '192.168.2.4'
CLIENT_ID = ubinascii.hexlify(unique_id())
topic = b'cmnd/doors/doorbell/pressed'
db_signal = ADC(0)
def reconnect(hostname):
wifi.do_disconnect()
sleep(1)
wifi.do_connect(hostname)
main(hostname)
def main(hostname):
c = MQTTClient(CLIENT_ID, server, keepalive=1800)
try:
c.connect()
print('Connected to MQTT.')
c.publish(b'stat/doorbell/state', 'started')
c.disconnect()
except (OSError, MQTTException, IndexError):
reconnect(hostname)
last_msg = 0.0
# sta_if = network.WLAN(network.STA_IF)
while True:
#print(sta_if.isconnected())
if db_signal.read() > 820: # test and change that value
if time() - last_msg > 5:
try:
last_msg = time()
c.connect()
c.publish(topic, 'True')
c.disconnect()
except (OSError, MQTTException, IndexError):
reconnect(hostname)
print('Doorbell\'d')
#sleep_ms(10)
@Nama
Copy link
Author

Nama commented Jan 24, 2025

reading average of last minute and detecting changes to that might be better, for the voltage drop of the battery?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment