Pi Pico, sensor, levelshifter, doosje, USB kabel. Scriptje in uPython.
Sensor: https://nl.aliexpress.com/item/4000142911469.html
Sonbest SM7901 (TTL versie)
Datasheet: http://www.sonbus.com/upload/pdf/SM7901B.pdf
Bonkje code:
from umodbus.serial import Serial as ModbusRTUMaster
from machine import Pin
import time
import network
from umqtt.simple import MQTTClient
# Fill in your WiFi network name (ssid) and password here:
wifi_ssid = "revspace-pub"
wifi_password = ""
rtu_pins = (Pin(0), Pin(1)) # (TX, RX)
uart_id = 0
host = ModbusRTUMaster(
pins=rtu_pins, # given as tuple (TX, RX)
# baudrate=9600, # optional, default 9600
# data_bits=8, # optional, default 8
# stop_bits=1, # optional, default 1
# parity=None, # optional, default None
# ctrl_pin=12, # optional, control DE/RE
uart_id=uart_id # optional, default 1, see port specific documentation
)
# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wifi_ssid, wifi_password)
while wlan.isconnected() == False:
print('Waiting for connection...')
time.sleep(1)
print("Connected to WiFi")
mqtt_host = "mosquitto"
mqtt_username = ""
mqtt_password = ""
mqtt_publish_topic = "topic"
# Enter a random ID for this MQTT Client
mqtt_client_id = "client_id"
mqtt_client = MQTTClient(
client_id=mqtt_client_id,
server=mqtt_host,
user=mqtt_username,
password=mqtt_password)
mqtt_client.connect()
mqtt_client.set_last_will(mqtt_publish_topic, "0 dB", retain=True, qos=0)
counter = 0
try:
while True:
datainvoer = host.read_holding_registers(1, 0x0000, 1)
stringetje = str(datainvoer[0]/10)+" dB"
print(f'Publish {stringetje}')
mqtt_client.publish(mqtt_publish_topic, stringetje)
time.sleep(3)
except Exception as e:
print(f'Failed to publish message: {e}')
finally:
mqtt_client.disconnect()