#------------------------------------------------------------------------------
"""
This is a Node-red flow, import it into the node-red for dashboard
[
{
"id": "311aa1e35fc95626",
"type": "mqtt in",
"z": "e05212636a9d133c",
"name": "",
"topic": "esp/dht22/temperature",
"qos": "1",
"datatype": "auto-detect",
"broker": "a2f40d2b.60af6",
"nl": false,
"rap": true,
"rh": 0,
"inputs": 0,
"x": 160,
"y": 120,
"wires": [
[
"82403aa5b2f504bc",
"5d6fd8922861eb93"
]
]
},
{
"id": "2f28f24805b0482a",
"type": "mqtt in",
"z": "e05212636a9d133c",
"name": "",
"topic": "esp/dht22/humidity",
"qos": "1",
"datatype": "auto-detect",
"broker": "a2f40d2b.60af6",
"nl": false,
"rap": true,
"rh": 0,
"inputs": 0,
"x": 150,
"y": 280,
"wires": [
[
"ea41e579c4918ff1",
"67bfd6e0ad196748"
]
]
},
{
"id": "82403aa5b2f504bc",
"type": "ui_gauge",
"z": "e05212636a9d133c",
"name": "",
"group": "3a5046b27ec6aa5c",
"order": 1,
"width": 0,
"height": 0,
"gtype": "gage",
"title": "Temperature",
"label": "°C",
"format": "{{value}}",
"min": 0,
"max": "80",
"colors": [
"#00b500",
"#e6e600",
"#ca3838"
],
"seg1": "",
"seg2": "",
"diff": false,
"className": "",
"x": 350,
"y": 120,
"wires": []
},
{
"id": "ea41e579c4918ff1",
"type": "ui_gauge",
"z": "e05212636a9d133c",
"name": "",
"group": "f2fd1ff9715ee71f",
"order": 1,
"width": 0,
"height": 0,
"gtype": "gage",
"title": "Humidity",
"label": "%",
"format": "{{value}}",
"min": "30",
"max": "100",
"colors": [
"#00b500",
"#e6e600",
"#ca3838"
],
"seg1": "",
"seg2": "",
"diff": false,
"className": "",
"x": 340,
"y": 280,
"wires": []
},
{
"id": "2e9bc30c1cd7e625",
"type": "mqtt in",
"z": "e05212636a9d133c",
"name": "",
"topic": "esp/hcsr04/distance",
"qos": "1",
"datatype": "auto-detect",
"broker": "a2f40d2b.60af6",
"nl": false,
"rap": true,
"rh": 0,
"inputs": 0,
"x": 150,
"y": 420,
"wires": [
[
"b08bb19cf8fe143c",
"d47a31222b66c5d0"
]
]
},
{
"id": "b08bb19cf8fe143c",
"type": "ui_gauge",
"z": "e05212636a9d133c",
"name": "",
"group": "3e29f55f1ad973ea",
"order": 1,
"width": 0,
"height": 0,
"gtype": "gage",
"title": "Distance",
"label": "CM",
"format": "{{value}}",
"min": 0,
"max": "400",
"colors": [
"#00b500",
"#e6e600",
"#ca3838"
],
"seg1": "",
"seg2": "",
"diff": false,
"className": "",
"x": 360,
"y": 420,
"wires": []
},
{
"id": "08a6a4a157d4ea9f",
"type": "ui_gauge",
"z": "e05212636a9d133c",
"name": "",
"group": "49a06489f27b883a",
"order": 1,
"width": 0,
"height": 0,
"gtype": "gage",
"title": "Temperature",
"label": "°C",
"format": "{{value}}",
"min": 0,
"max": "100",
"colors": [
"#00b500",
"#e6e600",
"#ca3838"
],
"seg1": "",
"seg2": "",
"diff": false,
"className": "",
"x": 450,
"y": 600,
"wires": []
},
{
"id": "a7b823e6.6a7f6",
"type": "mqtt in",
"z": "e05212636a9d133c",
"name": "",
"topic": "esp/ds18b20/temperature",
"qos": "1",
"datatype": "auto",
"broker": "a2f40d2b.60af6",
"nl": false,
"rap": false,
"inputs": 0,
"x": 170,
"y": 600,
"wires": [
[
"08a6a4a157d4ea9f",
"80a1d4725487feee"
]
]
},
{
"id": "d47a31222b66c5d0",
"type": "ui_chart",
"z": "e05212636a9d133c",
"name": "",
"group": "3e29f55f1ad973ea",
"order": 2,
"width": 0,
"height": 0,
"label": "Distance",
"chartType": "line",
"legend": "false",
"xformat": "HH:mm:ss",
"interpolate": "linear",
"nodata": "",
"dot": false,
"ymin": "",
"ymax": "",
"removeOlder": 1,
"removeOlderPoints": "",
"removeOlderUnit": "3600",
"cutout": 0,
"useOneColor": false,
"useUTC": false,
"colors": [
"#1f77b4",
"#aec7e8",
"#ff7f0e",
"#2ca02c",
"#98df8a",
"#d62728",
"#ff9896",
"#9467bd",
"#c5b0d5"
],
"outputs": 1,
"useDifferentColor": false,
"className": "",
"x": 360,
"y": 480,
"wires": [
[]
]
},
{
"id": "5d6fd8922861eb93",
"type": "ui_chart",
"z": "e05212636a9d133c",
"name": "",
"group": "3a5046b27ec6aa5c",
"order": 2,
"width": 0,
"height": 0,
"label": "Temperature",
"chartType": "line",
"legend": "false",
"xformat": "HH:mm:ss",
"interpolate": "linear",
"nodata": "",
"dot": false,
"ymin": "",
"ymax": "",
"removeOlder": 1,
"removeOlderPoints": "",
"removeOlderUnit": "3600",
"cutout": 0,
"useOneColor": false,
"useUTC": false,
"colors": [
"#1f77b4",
"#aec7e8",
"#ff7f0e",
"#2ca02c",
"#98df8a",
"#d62728",
"#ff9896",
"#9467bd",
"#c5b0d5"
],
"outputs": 1,
"useDifferentColor": false,
"className": "",
"x": 350,
"y": 180,
"wires": [
[]
]
},
{
"id": "67bfd6e0ad196748",
"type": "ui_chart",
"z": "e05212636a9d133c",
"name": "",
"group": "f2fd1ff9715ee71f",
"order": 2,
"width": 0,
"height": 0,
"label": "Humidity",
"chartType": "line",
"legend": "false",
"xformat": "HH:mm:ss",
"interpolate": "linear",
"nodata": "",
"dot": false,
"ymin": "",
"ymax": "",
"removeOlder": 1,
"removeOlderPoints": "",
"removeOlderUnit": "3600",
"cutout": 0,
"useOneColor": false,
"useUTC": false,
"colors": [
"#1f77b4",
"#aec7e8",
"#ff7f0e",
"#2ca02c",
"#98df8a",
"#d62728",
"#ff9896",
"#9467bd",
"#c5b0d5"
],
"outputs": 1,
"useDifferentColor": false,
"className": "",
"x": 340,
"y": 340,
"wires": [
[]
]
},
{
"id": "80a1d4725487feee",
"type": "ui_chart",
"z": "e05212636a9d133c",
"name": "",
"group": "49a06489f27b883a",
"order": 2,
"width": 0,
"height": 0,
"label": "Temperature",
"chartType": "line",
"legend": "false",
"xformat": "HH:mm:ss",
"interpolate": "linear",
"nodata": "",
"dot": false,
"ymin": "",
"ymax": "",
"removeOlder": 1,
"removeOlderPoints": "",
"removeOlderUnit": "3600",
"cutout": 0,
"useOneColor": false,
"useUTC": false,
"colors": [
"#1f77b4",
"#aec7e8",
"#ff7f0e",
"#2ca02c",
"#98df8a",
"#d62728",
"#ff9896",
"#9467bd",
"#c5b0d5"
],
"outputs": 1,
"useDifferentColor": false,
"className": "",
"x": 450,
"y": 660,
"wires": [
[]
]
},
{
"id": "bb74606805903752",
"type": "mqtt in",
"z": "e05212636a9d133c",
"name": "Servo 1 Control",
"topic": "esp/servo1",
"qos": "2",
"datatype": "auto-detect",
"broker": "a2f40d2b.60af6",
"nl": false,
"rap": false,
"inputs": 0,
"x": 820,
"y": 120,
"wires": [
[
"d162d31fd6cdc6c3"
]
]
},
{
"id": "b009e6191fc419b3",
"type": "mqtt in",
"z": "e05212636a9d133c",
"name": "Servo 2 Control",
"topic": "esp/servo2",
"qos": "2",
"datatype": "auto-detect",
"broker": "a2f40d2b.60af6",
"nl": false,
"rap": false,
"inputs": 0,
"x": 820,
"y": 220,
"wires": [
[
"907b4683b8bb355d"
]
]
},
{
"id": "d162d31fd6cdc6c3",
"type": "ui_text",
"z": "e05212636a9d133c",
"group": "5bd6e5630f5472e3",
"order": 1,
"width": 0,
"height": 0,
"name": "",
"label": "Servo 1 Angle",
"format": "{{msg.payload}}",
"layout": "col-center",
"className": "",
"style": false,
"font": "",
"fontSize": "",
"color": "#000000",
"x": 1040,
"y": 120,
"wires": []
},
{
"id": "907b4683b8bb355d",
"type": "ui_text",
"z": "e05212636a9d133c",
"group": "5bd6e5630f5472e3",
"order": 2,
"width": 0,
"height": 0,
"name": "",
"label": "Servo 2 Angle",
"format": "{{msg.payload}}",
"layout": "col-center",
"x": 1040,
"y": 220,
"wires": []
},
{
"id": "4fb398fe76974385",
"type": "ui_slider",
"z": "e05212636a9d133c",
"name": "Servo 1 Slider",
"label": "Servo 1",
"tooltip": "",
"group": "5bd6e5630f5472e3",
"order": 1,
"width": 0,
"height": 0,
"passthru": true,
"outs": "end",
"topic": "esp/servo1",
"topicType": "str",
"min": 0,
"max": 180,
"step": 1,
"className": "",
"x": 820,
"y": 320,
"wires": [
[
"b5678da9a2859bfd"
]
]
},
{
"id": "4ab589404f1eb98c",
"type": "ui_slider",
"z": "e05212636a9d133c",
"name": "Servo 2 Slider",
"label": "Servo 2",
"tooltip": "",
"group": "5bd6e5630f5472e3",
"order": 2,
"width": 0,
"height": 0,
"passthru": true,
"outs": "end",
"topic": "esp/servo2",
"topicType": "str",
"min": 0,
"max": 180,
"step": 1,
"className": "",
"x": 820,
"y": 420,
"wires": [
[
"9ead4011bc916c19"
]
]
},
{
"id": "b5678da9a2859bfd",
"type": "mqtt out",
"z": "e05212636a9d133c",
"name": "",
"topic": "esp/servo1",
"qos": "2",
"retain": "",
"respTopic": "",
"contentType": "",
"userProps": "",
"correl": "",
"expiry": "",
"broker": "a2f40d2b.60af6",
"x": 1040,
"y": 320,
"wires": []
},
{
"id": "9ead4011bc916c19",
"type": "mqtt out",
"z": "e05212636a9d133c",
"name": "",
"topic": "esp/servo2",
"qos": "2",
"retain": "",
"respTopic": "",
"contentType": "",
"userProps": "",
"correl": "",
"expiry": "",
"broker": "a2f40d2b.60af6",
"x": 1040,
"y": 420,
"wires": []
},
{
"id": "a2f40d2b.60af6",
"type": "mqtt-broker",
"name": "",
"broker": "test.mosquitto.org",
"port": "1883",
"clientid": "",
"usetls": false,
"compatmode": true,
"keepalive": "60",
"cleansession": true,
"birthTopic": "",
"birthQos": "0",
"birthRetain": "false",
"birthPayload": "",
"closeTopic": "",
"closePayload": "",
"willTopic": "",
"willQos": "0",
"willRetain": "false",
"willPayload": ""
},
{
"id": "3a5046b27ec6aa5c",
"type": "ui_group",
"name": "DHT22 Temperature",
"tab": "09b36765bf41261b",
"order": 1,
"disp": true,
"width": "6",
"collapse": false,
"className": ""
},
{
"id": "f2fd1ff9715ee71f",
"type": "ui_group",
"name": "DHT22 Humidity",
"tab": "09b36765bf41261b",
"order": 2,
"disp": true,
"width": "6",
"collapse": false,
"className": ""
},
{
"id": "3e29f55f1ad973ea",
"type": "ui_group",
"name": "HCSR04",
"tab": "09b36765bf41261b",
"order": 3,
"disp": true,
"width": "6",
"collapse": false,
"className": ""
},
{
"id": "49a06489f27b883a",
"type": "ui_group",
"name": "DS18B20",
"tab": "09b36765bf41261b",
"order": 4,
"disp": true,
"width": "6",
"collapse": false,
"className": ""
},
{
"id": "5bd6e5630f5472e3",
"type": "ui_group",
"name": "Control Panel",
"tab": "830414bcc79d9a1c",
"order": 1,
"disp": true,
"width": "6",
"collapse": false
},
{
"id": "09b36765bf41261b",
"type": "ui_tab",
"name": "Home",
"icon": "dashboard",
"disabled": false,
"hidden": false
},
{
"id": "830414bcc79d9a1c",
"type": "ui_tab",
"name": "Servo Control",
"icon": "dashboard",
"order": 1,
"disabled": false,
"hidden": false
}
]
"""
#------------------------------------------------------------------------------
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
from machine import Pin, ADC, PWM
import onewire, ds18x20
import dht
esp.osdebug(None)
import gc
gc.collect()
ssid = 'Wokwi-GUEST'
password = ''
mqtt_server = 'test.mosquitto.org'
client_id = ubinascii.hexlify(machine.unique_id())
topic_pub_ds18b20_temp = b'esp/ds18b20/temperature'
topic_pub_dht22_temp = b'esp/dht22/temperature'
topic_pub_dht22_hum = b'esp/dht22/humidity'
topic_pub_hcsr04_distance = b'esp/hcsr04/distance'
topic_sub_servo1 = b'esp/servo1'
topic_sub_servo2 = b'esp/servo2'
last_message = 0
message_interval = 5
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
# Initialize DS18B20 sensor
ds_pin = Pin(4) # Change the pin number to match your setup
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
if not roms:
print('No DS18B20 sensors found!')
else:
print('Found DS18B20 sensors: ', roms)
# Initialize DHT22 sensor
dht_pin = Pin(14) # Change the pin number to match your setup
dht_sensor = dht.DHT22(dht_pin)
# Initialize HC-SR04 sensor
trigger_pin = Pin(23, Pin.OUT)
echo_pin = Pin(19, Pin.IN)
# Initialize Servos
servo1 = PWM(Pin(33), freq=50) # Change the pin number to match your setup
servo2 = PWM(Pin(26), freq=50) # Change the pin number to match your setup
def set_servo_angle(servo, angle):
duty = (int(((angle)/180 *2 + 0.5) / 20 * 1023))
servo.duty(duty)
def connect_mqtt():
global client_id, mqtt_server, topic_sub_servo1, topic_sub_servo2
client = MQTTClient(client_id, mqtt_server)
client.set_callback(mqtt_callback)
client.connect()
print('Connected to %s MQTT broker' % (mqtt_server))
client.subscribe(topic_sub_servo1)
client.subscribe(topic_sub_servo2)
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
def mqtt_callback(topic, msg):
global servo1, servo2
print((topic, msg))
if topic == topic_sub_servo1:
angle = int(msg)
set_servo_angle(servo1, angle)
elif topic == topic_sub_servo2:
angle = int(msg)
set_servo_angle(servo2, angle)
def read_ds18b20():
try:
if roms:
ds_sensor.convert_temp()
time.sleep_ms(750)
ds18b20_temp = ds_sensor.read_temp(roms[0])
if isinstance(ds18b20_temp, float):
ds18b20_temp_b = b"{0:3.1f}".format(ds18b20_temp)
return ds18b20_temp_b
else:
return b'0.0'
else:
return b'0.0'
except Exception as e:
print("Error reading DS18B20 sensor:", str(e))
return b'Failed to read sensor.'
def read_dht22():
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
if isinstance(temp, float) and isinstance(hum, float):
temp_b = b"{0:3.1f}".format(temp)
hum_b = b"{0:3.1f}".format(hum)
return temp_b, hum_b
else:
return b'0.0', b'0.0'
except Exception as e:
print("Error reading DHT22 sensor:", str(e))
return b'Failed to read sensor.', b'Failed to read sensor.'
def read_hcsr04():
try:
trigger_pin.value(0)
time.sleep_us(2)
trigger_pin.value(1)
time.sleep_us(10)
trigger_pin.value(0)
pulse_start = time.ticks_us()
while echo_pin.value() == 0:
pulse_start = time.ticks_us()
pulse_end = time.ticks_us()
while echo_pin.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
distance = (pulse_duration * 0.0343) / 2
distance_b = b"{0:3.1f}".format(distance)
return distance_b
except Exception as e:
print("Error reading HC-SR04 sensor:", str(e))
return b'Failed to read sensor.'
try:
client = connect_mqtt()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg() # Check for new messages
if (time.time() - last_message) > message_interval:
ds18b20_temp = read_ds18b20()
dht22_temp, dht22_hum = read_dht22()
hcsr04_distance = read_hcsr04()
print("------------------------------------------")
print("Temperature (DS18B20):", ds18b20_temp.decode(), "°C")
print("Temperature (DHT22):", dht22_temp.decode(), "°C")
print("Humidity (DHT22):", dht22_hum.decode(), "%")
print("Distance (HC-SR04):", hcsr04_distance.decode(), "cm")
print("------------------------------------------")
client.publish(topic_pub_ds18b20_temp, ds18b20_temp)
client.publish(topic_pub_dht22_temp, dht22_temp)
client.publish(topic_pub_dht22_hum, dht22_hum)
client.publish(topic_pub_hcsr04_distance, hcsr04_distance)
# Servo 1 control based on distance
distance = float(hcsr04_distance)
if distance > 100:
set_servo_angle(servo1, 90) # Servo ON
elif distance < 40:
set_servo_angle(servo1, 0) # Servo OFF
# Servo 2 control based on temperature
dht22_temp_value = float(dht22_temp)
if dht22_temp_value > 38:
set_servo_angle(servo2, 0) # Servo ON
time.sleep(3)
set_servo_angle(servo2, 90) # Servo OFF
last_message = time.time()
except OSError as e:
restart_and_reconnect()
Loading
ds18b20
ds18b20