A climate node becomes useful when it can explain both a measurement and the absence of one. This serial-console project returns temperature and relative humidity from one sensor and deliberately preserves an error state. It is a foundation for a room dashboard; adding a network connection later should not change the meaning of failed data.

Specify the whole module
The sensor is Sensirion SHT31-D on Adafruit breakout 2857, using its documented STEMMA QT revision. A breakout is a small board carrying the sensor and supporting components. STEMMA QT names its connector system; we use the labeled header pins. The processor board is Espressif ESP32-DevKitC V4 with ESP32-WROOM-32E. Other ESP32 families can have different pin assignments; do not translate connector position by appearance.
Relative humidity (RH) expresses how much water vapour is present relative to saturation at the current temperature. It is not the mass of water in the room. Heating the sensor locally can change RH even when no moisture has been removed. Keep it away from the processor’s regulator and warm air from a computer during comparisons.
Parts and equipment
- Espressif ESP32-DevKitC V4 fitted with ESP32-WROOM-32E; MicroPython 1.26.0 for ESP32; USB cable.
- Adafruit SHT31-D temperature/humidity breakout product 2857, documented STEMMA QT revision; breadboard and short four-wire connection.
Every connection
| Pin or part | Connection and purpose |
|---|---|
| Power | ESP32 3V3 → breakout VIN; ESP32 GND → breakout GND. Do not use 5V for VIN in this circuit. |
| Data | ESP32 GPIO21 → SDA; GPIO22 → SCL. These are GPIO numbers printed on the DevKitC, not connector positions. |
| Existing parts | Breakout already has 10 kΩ SDA/SCL pullups to VIN. No additional bus pullups for the single short connection. Onboard decoupling retained. |
| Unused controls | ADR left in its onboard pulled-low default, selecting 0x44. RST left at its onboard pulled-high default. ALR unconnected; no alert mode is configured. |
Why VIN is 3.3 V here
The breakout’s two 10 kΩ pullups connect SDA and SCL to VIN. Powering that board at 5 V would therefore pull this ESP32 bus toward 5 V. Use 3.3 V throughout. A low bus line then draws roughly 3.3/10000 = 0.33 mA through its pullup. Additional breakout boards can place resistors in parallel: two 10 kΩ pullups become 5 kΩ, so adding modules is an electrical change, not merely a software change.
I²C, Inter-Integrated Circuit, uses SDA for data and SCL for clock. The default seven-bit address is hexadecimal 0x44. The address-select pad can select 0x45, but the program below intentionally expects the default. Long wires, missing ground and a different address are distinct causes of communication failure.
Request, wait, validate, convert
The command bytes 0x24 and 0x00 request one high-repeatability measurement without clock stretching. Clock stretching means a peripheral holds the clock low while it needs more time; this example instead waits 20 ms before reading. The datasheet lists a maximum conversion time of 15.5 ms for this mode. “High repeatability” does not establish the accuracy of a finished installation.
The six received bytes contain two data bytes and one checksum for temperature, followed by the same arrangement for humidity. CRC means cyclic redundancy check, an error-detecting calculation. Both CRC-8 values use polynomial 0x31 and start at 0xFF. The datasheet test vector 0xBEEF produces 0x92 and is useful for checking the implementation. A checksum failure invalidates the complete sample; reporting one word from a damaged transaction would make the display misleading.
Convert unsigned raw temperature Traw using T = −45 + 175 × Traw/65535 degrees Celsius. Convert humidity Hraw using RH = 100 × Hraw/65535 percent. For example, Traw = 26214 gives 25 °C and Hraw = 32768 gives approximately 50.0008% RH. Showing two decimal places is formatting, not proof of hundredth-degree accuracy. Calibration, sensor tolerance, mounting and airflow still matter.
Complete program
"""ESP32-DevKitC V4 / MicroPython 1.26.0 / Adafruit 2857."""
def crc8(data):
c = 0xff
for value in data:
c ^= value
for _ in range(8):
c = ((c << 1) ^ 0x31) & 255 if c & 128 else (c << 1) & 255
return c
def decode(data):
if len(data) != 6:
raise ValueError('expected six bytes')
if crc8(data[:2]) != data[2] or crc8(data[3:5]) != data[5]:
raise ValueError('CRC mismatch')
t = (data[0] << 8) | data[1]; h = (data[3] << 8) | data[4]
return -45 + 175*t/65535, 100*h/65535
def measure(bus, delay):
if bus.writeto(0x44, b'\x24\x00') != 2:
raise OSError('command not acknowledged')
delay(20) # high repeatability, no clock stretching; max conversion 15.5 ms
return decode(bus.readfrom(0x44, 6))
def main():
from machine import Pin, SoftI2C
from time import sleep_ms, ticks_ms, ticks_diff
bus = SoftI2C(sda=Pin(21), scl=Pin(22), freq=100000, timeout=20000)
last_good = None; last_at = None; failures = 0
sleep_ms(20)
while True:
try:
last_good = measure(bus, sleep_ms); last_at = ticks_ms(); failures = 0
print('OK T=%.2f C RH=%.2f %%' % last_good)
except (OSError, ValueError) as exc:
failures += 1
age = None if last_at is None else ticks_diff(ticks_ms(), last_at)
print('INVALID now; last good:', last_good, 'age ms:', age,
'failures:', failures, 'reason:', exc)
sleep_ms(2000)
if __name__ == '__main__':
main()
Make an error visible
The main loop runs about once every two seconds. An accepted sample replaces last_good and resets the failure counter. A bus error, short frame or bad checksum prints INVALID now together with the last accepted values and their age. If nothing has succeeded, last_good is None. The node never substitutes zero for an error and never silently presents old values as current.
That distinction survives a future display or network upgrade: carry validity and age with the numbers. An application should decide its own maximum acceptable age. This console example reports the age rather than pretending all climate applications need the same threshold.
Bench procedure
- Disconnect power and check the four connections. Inspect the breakout revision and its labels. Install MicroPython 1.26.0 for the specified ESP32, save the complete listing as main.py and open the serial console.
- Record five minutes of readings with the board and sensor separated by short leads. Note room conditions and placement before comparing with another instrument. Two sensors disagreeing does not identify which one is correct.
- Move a warm hand near, without touching or breathing directly onto, the sensor. Observe that temperature and RH need not move in the same direction. Return it to the original position and allow settling.
- Stop power, disconnect SDA, then restart. Expect INVALID and no invented temperature. Restore wiring with power off. A separate host test injects a bad CRC; that is a software test, not a claim that a physical wire fault always produces a CRC error.
- Test the stale-data presentation by disconnecting a signal during a controlled low-voltage bench session only if your connectors permit it without shorts. Record the final good sample and subsequent age. Power down before general rewiring.
Limits worth understanding
This is an air-climate sensor, not a leak detector, waterproof probe or gas detector. Condensation and contamination can affect readings. No heater command is used; enabling a sensor heater would change the local conditions being measured. Failure recovery here is periodic new measurement attempts, not an unlimited sequence of bus resets.
The decoder and actual measurement helper are covered by host tests for valid endpoints, CRC errors, short data and failed commands. This circuit has not been physically tested. Save the sensor marking, board revision, interpreter version, placement and comparison observations when you perform the experiment.
Challenge: should you clamp a failed humidity reading to 0–100%?
No. A failure needs an invalid state. Clamping can conceal a protocol or program error; range handling belongs after a valid transfer and a justified physical interpretation.
Sources and related lessons
- Adafruit SHT31-D 2857 pinouts and pullups
- Sensirion SHT3x-DIS datasheet version 7, December 2022
- Espressif ESP32-DevKitC V4 board guide
- MicroPython 1.26.0 I2C reference
Continue with why a voltage divider drops under load, measuring current through a resistor with a voltmeter, and the interactive circuit lessons.



