Problems with multiple Dallas DS18B20 sensors
1
2.2 Kilo ohms for Data line
2
Just about 10 meters away
3
MicroPython (RP2040)
1
Requires plug / unplug 5V power multiple times.
2
Did not fixed the issue
3
Did not fixed the issue
Changed the boot order, start wifi first and instantiate all sensors after Wifi connection.
import network, socket, time, machine, onewire, ds18x20, json
from secrets import secrets
# --- 1. POWER STABILIZATION ---
led = machine.Pin("LED", machine.Pin.OUT)
led.off()
time.sleep(5) # Give the 5V adapter 5 seconds to settle
# --- 2. WIFI FIRST (BEFORE SENSORS) ---
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(pm = 0xa11140)
def connect_wifi():
print("Connecting WiFi...")
wlan.connect(secrets['ssid'], secrets['password'])
attempt = 0
while not wlan.isconnected():
attempt += 1
led.toggle()
time.sleep(0.5)
if attempt > 20: # If it takes >10s, hard reset the radio
wlan.active(False)
time.sleep(1)
wlan.active(True)
wlan.connect(secrets['ssid'], secrets['password'])
attempt = 0
led.on()
print("WiFi Ready")
connect_wifi()
# --- 3. SENSOR SETUP (LATE INITIALIZATION) ---
# We define the sensors ONLY after WiFi is solid
ds_pin = machine.Pin(22)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
SENSOR_MAP = {
'bucatarie': '283f4cb400000080',
'baie' : '283997b40000001c',
'hol' : '284eb7ba000000ec',
'degivrare': '28969cb400000014',
'magazie' : '28f8adba00000098',
'exterior' : '2830c3ba00000015'
}
# --- 4. SERVER SETUP ---
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', 80))
s.listen(5)
s.settimeout(1.0)
while True:
if not wlan.isconnected():
connect_wifi()
try:
try:
conn, addr = s.accept()
except OSError:
continue
led.off()
request = str(conn.recv(1024))
if "/reboot" in request:
conn.send('HTTP/1.1 200 OK\r\n\r\nRebooting...')
conn.close()
time.sleep(1)
machine.reset()
# SENSOR READING WITH "QUIET" ERRORS
try:
ds_sensor.convert_temp()
time.sleep_ms(750)
roms = ds_sensor.scan()
found_roms = {''.join(['%02x' % b for b in rom]): rom for rom in roms}
results = {}
for name, hex_id in SENSOR_MAP.items():
if hex_id in found_roms:
t = ds_sensor.read_temp(found_roms[hex_id])
results[name] = int(t * 10) / 10.0
else:
results[name] = "OFFLINE"
except Exception as sensor_err:
results = {"error": "Sensor Bus Busy"}
response = json.dumps(results)
conn.send('HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n')
conn.send(response)
conn.close()
led.on()
except Exception as e:
if 'conn' in locals(): conn.close()
led.on()