Lift a pressure sensor by a metre and the displayed number may change. Leave it on the same shelf and the number may also change. A useful beginner instrument must preserve that ambiguity: pressure is a measured quantity, while height is an interpretation that needs extra assumptions. Build a short-reference comparison lab before using a barometer as a floor detector.
The hardware is an Adafruit BMP390 breakout, product 4816, and an original Raspberry Pi Pico RP2040 running official MicroPython 1.26.0. A breakout is a small board that makes a tiny sensor easier to connect and adds support circuitry. This exact board matters: the bare Bosch chip and an arbitrary marketplace board do not have the same power-input protection or connector assumptions.
Absolute pressure and a relative comparison are different
Pressure is force per unit area. The unit Pa, pascal, is one newton per square metre; hPa, hectopascal, is 100 Pa. The BMP390 is an absolute-pressure sensor: its internal reference is effectively a sealed reference cavity, not the current room pressure. The program reports compensated pressure in Pa, not hPa. Dividing Pa by 100 is a unit conversion, not calibration.
Our relative pressure is a subtraction, ΔP=Pnow−Preference, using the same sensor at a recorded starting position. It is not a differential-pressure sensor with two physical ports. A stored reference helps remove a common initial offset over a short comparison; it does not remove later weather, heating, ventilation or sensor drift.
A published sea-level weather pressure is often a pressure reduced to a reference altitude, rather than the actual station pressure at your sensor. Subtracting it from an uncorrected local reading mixes different quantities. This lesson starts with a local same-device reference and leaves absolute sea-level height out of the automatic output.
Exact board, power and environmental limits
- Adafruit BMP390 product 4816, the STEMMA QT connector version, with Bosch BMP390. STEMMA QT is Adafruit’s compact four-wire connector family; this lab uses labelled header nets instead.
- Original non-wireless Pico RP2040 with official MicroPython 1.26.0 and a data-capable Universal Serial Bus (USB) cable.
- Four short wires and correctly soldered headers; a stable nonconductive support, a ruler for relative motion and a room thermometer for an optional air-model calculation.
- A voltmeter for the initial rail check. No pump, pressure hose, sealed vessel, fan or moving mechanism is required.
The module manufacturer specifies a 3–5 V VIN input and bus-level circuitry; with this Pico we use 3.3 V on VIN and 3.3 V bus levels. Its regulator, decoupling and pullups are already fitted. The published schematic shows 10 kΩ pullups, 10 µF supply capacitors and 100 nF sensor decoupling. Do not add a second supply to the module’s 3Vo regulator output.
The bare sensor’s operating supply is 1.65–3.6 V, with a separate 1.2–3.6 V interface supply. The datasheet’s pressure operating range is 300–1250 hPa; its full-accuracy temperature region is narrower than the −40 to +85°C operational temperature range. A 3.6 V absolute supply boundary and an overpressure-survival rating are not permissions to run this open-air experiment at those stresses.
Keep liquid, fingers, adhesive and dust away from the sensing port. Do not cover it with tape, press on the metal lid, blow into it or use a syringe to manufacture dramatic readings. A protective enclosure must allow pressure equalization; a sealed warm box measures that box’s internal conditions. Mechanical stress and contamination can change the result without an obvious electrical failure.
Four wires and a known address
SDA means serial data and SCL means serial clock. The module also labels the clock SCK and the shared data input SDI, serial data input, for its alternative interface. Match these named nets rather than connector colours.

tricky-circuit-batch-006/images/pico-bmp390-relative-pressure.svg)| Pico net and physical pin | Exact module label | Job |
|---|---|---|
| 3V3 OUT, 36 | VIN | Common 3.3 V power/logic environment. |
| GND, 38 | GND | Shared zero-volt return. |
| GP0, 1 | SDA, also SDI on some documentation | Serial data. |
| GP1, 2 | SCK/SCL | Serial clock. |
I²C, Inter-Integrated Circuit, is the two-wire addressable serial bus. The default seven-bit address is 0x77; 0x introduces hexadecimal notation. Leave the ADDR address jumper open. A deliberately closed jumper selects 0x76 and requires the matching constructor argument. The driver does not silently scan and select a different device.
Leave CS, SDO and INT open for this I²C build, as the exact module guide instructs. CS is chip select for its alternative serial interface, SDO is serial data output/address selection, and INT is an optional interrupt notification. They are not extra Pico power connections. A pullup resistor lets an undriven serial line return high; the already-fitted resistors provide that function here.
With power disconnected, identify real board labels and rail breaks before wiring. Power through Pico USB only, then confirm the bus idles near 3.3 V before running software. Do not copy a 5 V Arduino wiring example to Pico pins. The drawing identifies functional nets and Pico physical pin numbers; it does not invent a module header’s left-to-right order.
Fresh raw data still needs per-device compensation
An analog-to-digital converter (ADC) turns the sensor element’s analog signals into raw numeric codes. The pressure and temperature codes are not directly Pa and degrees Celsius. The manufacturer stores per-device trim coefficients, correction constants programmed during production, in nonvolatile memory. Nonvolatile means that the values survive removal of power.
The complete driver reads the 21-byte trim block at 0x31 twice and checks that both copies agree. It decodes the signed and unsigned fields and applies the Bosch datasheet’s temperature and pressure polynomials. A polynomial combines powers of its inputs with these coefficients. Do not reuse another sensor’s coefficients or replace them with the synthetic constants in the host tests.
Two equal reads and an identity check cannot authenticate a sensor or detect every plausible corrupted calibration block. They reject specific faults such as a short transfer, changing data or an entirely blank block. The driver also refuses a compensated result outside the declared operational pressure/temperature range. An in-range result is still subject to sensor and setup error.
Every sample uses forced mode, one conversion request followed by automatic return to sleep. Pressure oversampling is 8× and temperature oversampling is 2×; oversampling combines internal conversions to trade time and power for noise behavior. The recursive internal filter is off so a long filter history is not mistaken for an instantaneous change.
Before requesting a new conversion, the code drains old data to clear its ready flags. It waits for both pressure and temperature readiness, reads all six data bytes together and checks error, identity, reset event and configuration. A stale ready flag cannot substitute for the new request. The 50-poll limit bounds attempts, not a strict wall-time deadline if the underlying bus itself stalls. This is a single-owner bus experiment; another program must not reconfigure the chip concurrently.
Give the reference an age and a location

Start the program with the sensor held still at a recorded reference point. After 16 fresh pairs, it accepts the average only if the observed pressure span is no more than 10 Pa and temperature span no more than 0.2°C. A span is maximum minus minimum, not an uncertainty estimate. These thresholds are our experiment’s screening policy; they are not Bosch accuracy specifications.
The reference is valid for at most 120 seconds and only while the current sensor temperature remains within 2°C of its reference average. Expiration clears the reference, prints REFERENCE_EXPIRED and stops. It does not quietly zero the instrument at a new height. Return to the recorded position and deliberately restart before collecting a replacement reference.
COLLECTING_REFERENCE and REFERENCE_UNSTABLE rows have no relative value; a missing value is printed as None rather than zero. An electrical, readiness or parsing fault clears the reference and stops with FAULT_STOP. Startup failures similarly produce INITIALIZATION_FAULT. This makes uncertainty visible instead of retaining the last successful number as though it were current.
Complete MicroPython program
Save the complete file on the Pico and run it from your editor’s serial console. MicroPython’s application programming interface (API), its callable software interface, supplies I²C and timing functions. No external driver package is required. The read–evaluate–print loop (REPL) remains available after Ctrl+C. The program prints dictionaries containing explicit units and state; it does not silently convert a pressure number into height.
Download complete driver and comparison program (ZIP; file: tricky-circuit-batch-006/code/pico-bmp390-relative-pressure.py). This listing contains the same file, including initialization, faults and entry point.
Complete MicroPython program
"""Original Pico RP2040, MicroPython 1.26.0, Adafruit BMP390 PID4816.
Compensation implements the Bosch BMP390 datasheet polynomial, independently
arranged here; raw values and per-device trim are never interchangeable.
"""
import math
import struct
def valid_number(x):
return not isinstance(x, bool) and math.isfinite(float(x))
def coefficients(raw):
if len(raw) != 21 or raw == bytes(21) or raw == b"\xff"*21:
raise ValueError("invalid trim block")
q = struct.unpack("<HHbhhbbHHbbhbb", raw)
return (q[0]*256.0, q[1]/2.0**30, q[2]/2.0**48,
(q[3]-16384)/2.0**20, (q[4]-16384)/2.0**29,
q[5]/2.0**32, q[6]/2.0**37, q[7]*8.0, q[8]/64.0,
q[9]/256.0, q[10]/32768.0, q[11]/2.0**48,
q[12]/2.0**48, q[13]/2.0**65)
def compensate(trim, data):
if len(data) != 6:
raise ValueError("short pressure/temperature burst")
raw_p = data[0] | data[1]<<8 | data[2]<<16
raw_t = data[3] | data[4]<<8 | data[5]<<16
if raw_p in (0,0xffffff) or raw_t in (0,0xffffff):
raise ValueError("raw rail/default-like data")
t1,t2,t3,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11 = trim
delta = raw_t-t1
temperature = delta*t2 + delta*delta*t3
t = temperature
pressure = (p5 + t*(p6+t*(p7+t*p8))
+ raw_p*(p1+t*(p2+t*(p3+t*p4)))
+ raw_p*raw_p*(p9+t*p10+raw_p*p11))
if not valid_number(pressure) or not valid_number(t):
raise ValueError("nonfinite compensation")
if not 30000 <= pressure <= 125000 or not -40 <= t <= 85:
raise ValueError("compensated value outside operating range")
return pressure,t
def height_model_m(reference_Pa, pressure_Pa, mean_air_C):
if not all(valid_number(x) for x in (reference_Pa,pressure_Pa,mean_air_C)):
raise ValueError("invalid model input")
if reference_Pa <= 0 or pressure_Pa <= 0 or not -40 <= mean_air_C <= 60:
raise ValueError("invalid model range")
return 287.05*(mean_air_C+273.15)/9.80665*math.log(reference_Pa/pressure_Pa)
class BMP390:
def __init__(self,bus,sleep_ms,address=0x77):
self.bus,self.sleep_ms,self.address=bus,sleep_ms,address
if address not in (0x76,0x77):
raise ValueError("wrong configured I2C address")
self.sleep_ms(10)
self.identity()
self.wait(0x10) # Command decoder ready before soft reset.
self.write(0x7e,0xb6)
self.sleep_ms(10)
self.identity();self.wait(0x10)
self.read(0x10,1) # Acknowledge reset event belonging to this initialization.
a,b=self.read(0x31,21),self.read(0x31,21)
if a != b:
raise ValueError("trim changed between reads")
self.trim_raw=a;self.trim=coefficients(a)
self.write(0x1b,0x03) # Sleep, pressure and temperature enabled.
self.write(0x1c,0x0b) # Pressure8x, temperature2x oversampling.
self.write(0x1f,0x00) # No recursive IIR filter.
self.guard()
def read(self,register,length):
data=self.bus.readfrom_mem(self.address,register,length)
if len(data) != length:
raise OSError("short I2C read")
return data
def write(self,register,value):
self.bus.writeto_mem(self.address,register,bytes((value,)))
def identity(self):
if self.read(0x00,1)[0] != 0x60:
raise ValueError("BMP390 CHIP_ID must be 0x60")
def error(self):
error=self.read(0x02,1)[0]
if error & 0x07:
raise OSError("BMP390 ERR_REG="+hex(error))
def wait(self,mask):
# Bounded polling count, not a strict wall-time deadline for I2C faults.
for _ in range(50):
self.error()
if self.read(0x03,1)[0]&mask == mask:
return
self.sleep_ms(5)
raise OSError("BMP390 readiness timeout")
def guard(self):
self.identity();self.error()
if self.read(0x10,1)[0]&1:
raise OSError("BMP390 reset detected; restart and recollect reference")
if (self.read(0x1b,1)[0]&0x33 != 0x03
or self.read(0x1c,1)[0] != 0x0b or self.read(0x1f,1)[0] != 0):
raise OSError("BMP390 configuration changed")
def sample(self):
self.guard()
self.read(0x04,6) # Drain old values so their ready flags cannot satisfy a new request.
self.write(0x1b,0x13) # One forced conversion, both channels.
self.wait(0x60)
raw=self.read(0x04,6)
self.guard()
return compensate(self.trim,raw)
class RelativePressure:
def __init__(self):self.clear()
def clear(self):
self.window=[];self.reference=None;self.reference_t=None;self.stamp=None
def update(self,pressure,temperature,now_ms,ticks_diff):
if (not valid_number(pressure) or not valid_number(temperature)
or not 30000 <= pressure <= 125000 or not -40 <= temperature <= 85):
self.clear();raise ValueError("invalid sample")
if self.reference is None:
self.window.append((pressure,temperature))
self.window=self.window[-16:]
if len(self.window)<16:
return dict(state="COLLECTING_REFERENCE",collected=len(self.window),pressure_Pa=pressure,temperature_C=temperature,delta_Pa=None)
ps=[x[0]for x in self.window];ts=[x[1]for x in self.window]
if max(ps)-min(ps)>10 or max(ts)-min(ts)>.2:
return dict(state="REFERENCE_UNSTABLE",pressure_Pa=pressure,temperature_C=temperature,delta_Pa=None)
self.reference=sum(ps)/16;self.reference_t=sum(ts)/16;self.stamp=now_ms
age=ticks_diff(now_ms,self.stamp)
if age<0 or age>120000 or abs(temperature-self.reference_t)>2:
self.clear()
return dict(state="REFERENCE_EXPIRED",delta_Pa=None)
return dict(state="RELATIVE_PRESSURE_ONLY",pressure_Pa=pressure,
temperature_C=temperature,reference_Pa=self.reference,
reference_temperature_C=self.reference_t,reference_age_ms=age,
delta_Pa=pressure-self.reference)
def run(sensor,relative,ticks_ms,ticks_diff,sleep_ms,emit=print,limit=None):
count=0
while limit is None or count<limit:
try:
p,t=sensor.sample()
row=relative.update(p,t,ticks_ms(),ticks_diff)
except (OSError,ValueError) as exc:
relative.clear()
emit(dict(state="FAULT_STOP",delta_Pa=None,error=str(exc)))
return
emit(row)
if row["state"] == "REFERENCE_EXPIRED":
return # Recollect only after the operator restores the reference position.
count+=1;sleep_ms(500)
if __name__ == "__main__":
from machine import Pin,I2C
from time import sleep_ms,ticks_ms,ticks_diff
try:
bus=I2C(0,sda=Pin(0),scl=Pin(1),freq=100000)
sensor=BMP390(bus,sleep_ms)
relative=RelativePressure()
run(sensor,relative,ticks_ms,ticks_diff,sleep_ms)
except (OSError,ValueError) as exc:
print(dict(state="INITIALIZATION_FAULT",delta_Pa=None,error=str(exc)))
The console waits 500 ms after each successful cycle, so actual sampling includes conversion and bus time; this is not a precision 2 Hz clock. The modular millisecond counter is safe for the short reference interval under normal frequent calls. An arbitrary pause concealing complete counter wraps cannot be reconstructed. After a long debugger stop, system sleep or uncertain history, restart from the physical reference point.
Host Python normally uses wider floating-point arithmetic than the official RP2 MicroPython build’s single-precision setting. The formula is the same, but host tests do not establish bit-for-bit Pico rounding or a sub-pascal target resolution. In particular, the number of printed digits must not be presented as an accuracy result.
A height model is an explicitly conditional calculation
For a small vertical comparison in approximately stationary air, hydrostatic balance gives dP/dz=−ρg. The ideal-gas approximation gives air density ρ=P/(RdT). Treating mean air temperature T as constant and integrating gives Δz=(RdT/g) ln(Pref/Pnow). Here Rd=287.05 J/(kg·K) is the dry-air gas constant, g=9.80665 m/s² is standard gravitational acceleration, ln is the natural logarithm, and kelvin temperature is degrees Celsius plus 273.15.
The separate height_model_m() helper evaluates that formula only when you supply a mean air temperature. It is not called by the automatic logger. The sensor’s internal temperature follows its die, board and self-heating; it is not automatically the mean temperature of an air column between two heights. Humidity, weather, dynamic pressure, pressure-port geometry and a changing reference can invalidate a naive interpretation.
For a synthetic reference of 100000 Pa, current pressure 99988 Pa and assumed mean air temperature 20°C, ΔP=−12 Pa and the model gives about +1.03 m. The same −12 Pa change caused by weather while the sensor stays still gives the same calculation. This counterexample is why a relative subtraction and a fresh timestamp alone cannot identify actual vertical movement.
Reproduce the ambiguity in a controlled sequence
- Record exact board, firmware, wiring, rail voltage and reference location. Let the powered assembly settle away from warm hands and the computer’s exhaust. Wait for a stable trend; a fixed arbitrary wait does not guarantee thermal equilibrium.
- Hold the module at the reference point and start the program. Record its 16-pair collection and whether the stability checks accept it. If not, keep the raw pressure/temperature rows and investigate the setup rather than loosening thresholds to force success.
- Within the short reference lifetime, move it gently to a measured higher support, keep the port clear and stop moving before comparing. Record absolute Pa, ΔPa, reference age and sensor temperature. Do not infer speed or acceleration from the transit.
- Return to the reference point before expiry and compare the return offset. Repeat without changing the mount, then repeat with a separately collected fresh reference. Use the blank worksheet to record unsuccessful returns as well as appealing ones.
- Hold the device still and observe ordinary room-pressure disturbances, such as a normal door opening at a distance. Do not blow on the port. The point is to discover that an unchanged physical height can still have a pressure response; whether your room shows a visible change is an observation, not a promised outcome.
- Let the reference expire. Confirm that the program stops rather than re-zeroing where it happens to be. Reproduce bus failures, short data and configuration changes with the host’s injected bus tests; do not force an electrical short to simulate them.
Blank observation sheet (ZIP; file: tricky-circuit-batch-006/code/pico-bmp390-relative-pressure-observations-blank.csv) keeps actual readings separate from a conditional height calculation. There are no invented measured traces. If the purpose becomes long-term altitude tracking, add an independently justified changing-pressure reference and an environmental error budget rather than extending this 120-second policy by assumption.
Challenge: average more samples until the height is exact?
No. Averaging can reduce some uncorrelated noise. It cannot identify a slow weather change, remove a common calibration bias, correct the wrong air temperature or discover a sealed enclosure. A very stable wrong model can produce many consistent decimal places. Preserve ΔPa and the assumptions, and compare with an independent height reference if height is the real quantity of interest.
Sources and verification boundaries
Actual supplied-code host checks cover signed trim decoding, polynomial terms, fresh readiness, reset/configuration faults, short reads, reference expiration and the actual console loop. The tests use synthetic trim values; they are not factory characterization data. Physical bus margins, pressure response and MicroPython execution remain untested. Review the electronics lessons before extending the circuit.
- Bosch BMP390 datasheet, DS002-07 revision 1.7, March 2021: current served revision at review, including calibration, forced mode and register semantics.
- Bosch product documentation; no separate applicable errata sheet was identified in the current listing and targeted primary-source check. Absence is not guaranteed.
- Exact Adafruit product 4816, module pinouts and manufacturer board schematic.
- Bosch handling and mounting guidance for pressure-port contamination and mechanical constraints.
- Original Pico pinout; MicroPython 1.26 I²C API; official RP2 numeric configuration.



