Digital sensors like the DHT or DS18B20 are devices that deliver the measurement already converted into digital data.
When we need to measure the physical world with some reliability, analog sensors fall short. Electrical noise, cable length, and ADC resolution can falsify the data.
The solution is digital sensors. These small devices integrate their own converter and send us the “cooked” data through a sequence of ones and zeros.
Today we’ll look at the two most popular ones: the DHT family (for air) and the robust DS18B20 (for everything else).
DHT Family: Temperature and Humidity
The DHT11 (blue) and DHT22 (white, also called AM2302) are very common sensors that measure both temperature and relative humidity.
- DHT11: The cheap brother. Short range (0-50°C), lower precision, and only returns integers.
- DHT22: The smart brother. Wider range (-40 to 80°C), better precision, and returns decimals.
Protocol and Connection
Although they have 3 or 4 pins, communication is done over a single data wire. Be careful, it is NOT standard OneWire, it is a proprietary protocol very sensitive to timing.
The connection is simple:
- VCC: 3.3V or 5V.
- GND: Ground.
- DATA: To any GPIO pin.
The Pull-Up resistor is mandatory For a clean signal, we need a 4.7kΩ or 10kΩ resistor between VCC and DATA. If you use a loose sensor (the plastic square), you have to add it. If you use a module mounted on a PCB, it is usually already soldered on.
Code in MicroPython
MicroPython includes the official dht driver in the firmware, so it’s very easy to use.
import dht
from machine import Pin
import time
# Initialize the sensor.
# Change dht.DHT11 to dht.DHT22 according to your model
# We use GPIO 15 for data
sensor = dht.DHT22(Pin(15))
while True:
try:
# 1. Measure (This can take up to 2 seconds)
sensor.measure()
# 2. Read the calculated values
temp = sensor.temperature()
hum = sensor.humidity()
print(f"Temperature: {temp}°C | Humidity: {hum}%")
except OSError as e:
print("Error reading sensor. Retrying...")
# IMPORTANT: DHT sensors are slow.
# The DHT11 needs a minimum of 1s between readings.
# The DHT22 needs a minimum of 2s.
time.sleep(2)
If you try to read the sensor too fast (without time.sleep), you will get an ETIMEDOUT error or failed readings. Give it time to breathe!
DS18B20 and the OneWire Protocol
If the DHT is for air, the DS18B20 is the all-terrain vehicle. It is a high-precision temperature sensor often encapsulated in a waterproof metal probe, ideal for liquids, refrigerators, or outdoors.
What makes the DS18B20 special is that it uses the Dallas OneWire protocol.
What is OneWire?
It is a communication bus that allows connecting multiple sensors to the same data wire.
Each DS18B20 sensor has a unique 64-bit code (its ROM address) burned into its silicon. Thanks to this, we can have 10 sensors connected to the same GPIO pin and read them individually by asking for their address.
Electrical Connection
Same as the DHT, it needs a 4.7kΩ Pull-Up resistor between VCC and DATA. Without it, the bus will not work and will not detect any sensors.
Scanning and Reading
The process has two parts: first we look for who is on the bus (Scanning) and then we read. MicroPython separates this into two libraries: onewire (for the bus) and ds18x20 (for the specific sensor).
import machine, onewire, ds18x20, time
# 1. OneWire Bus Configuration on GPIO 4
dat = machine.Pin(4)
ds = ds18x20.DS18X20(onewire.OneWire(dat))
# 2. Bus scan: Look for connected sensors
print("Scanning OneWire bus...")
roms = ds.scan()
if not roms:
print("No sensors found! Did you add the 4.7k resistor?")
else:
print(f"Found {len(roms)} sensors.")
# Main reading loop
while True:
# A. Start conversion: Shout "Everyone measure!"
ds.convert_temp()
# B. Wait: The conversion takes about 750ms max.
time.sleep_ms(750)
# C. Read the results one by one
for rom in roms:
temperatura = ds.read_temp(rom)
# Format the ROM address to be readable
rom_id = ''.join(f'{b:02x}' for b in rom)
print(f"Sensor {rom_id}: {temperatura:.2f}°C")
print("-" * 20)
time.sleep(2)
Why convert_temp and then wait?
The DS18B20 is a passive device. It needs time to capture the temperature and convert it to digital. If you try to read (read_temp) immediately after requesting the conversion, you will read the old value (usually 85.0°C, which is the reset value).
DHT or DS18B20
| Feature | DHT11 | DHT22 | DS18B20 |
|---|---|---|---|
| Measures | Temp + Humidity | Temp + Humidity | Temperature Only |
| Temp Range | 0 to 50°C | -40 to 80°C | -55 to 125°C |
| Precision | Low (±2°C) | Good (±0.5°C) | Excellent (±0.5°C) |
| Protocol | Proprietary (1 wire) | Proprietary (1 wire) | OneWire (Real Bus) |
| Multiple on 1 pin | No | No | Yes (Multiple) |
| Speed | 1 Hz | 0.5 Hz | ~750ms conversion |
- Use DHT22 if you need to know the ambient humidity (weather stations, greenhouses). Avoid DHT11 except for school prototypes.
- Use DS18B20 for everything else: temperature control of liquids, aquariums, underfloor heating, or machinery. Its robustness and the ability to put several on a single cable make it unbeatable.
With this, we now have digital eyes and skin for our system. We can now sense the environment!