Skip to content
You Start with one site
Amounts in Start with one site
IoT & AIoT · Course

Wire and read a real sensor

Lesson 4 of 9 Beginner 11 min read
Found this useful?

A dashboard full of wrong numbers is worse than no dashboard, because people believe it. A sensor taped next to the board's voltage regulator reads three degrees too warm. A loose wire returns nonsense that looks like a reading. One noisy sample crosses a limit and wakes someone at 3am. Before any reading leaves your device, it has to be a reading you would sign your name under. This lesson makes it one.

#Sensors #ESP32 #I2C

What you need

  • An ESP32 development board and a USB cable that carries data (some cables only charge).
  • A BME280 breakout board: temperature, humidity and pressure in one small chip. It is cheap and common, and the capstone uses it too.
  • Four jumper wires.
  • The Arduino IDE with the ESP32 board package, and the Adafruit BME280 library from the Library Manager (it installs the two small libraries it needs).

If you already have a different sensor, keep it. The ideas in this lesson (units, averaging, limits, a reference check) apply to every sensor; only the reading lines change.

Wire it

The BME280 talks over I2C, a two-wire bus: one wire carries data (SDA), one carries the clock (SCL). Add power and ground and you have four wires.

ESP32 BME280 3V3GNDGPIO 21GPIO 22 VCCGNDSDASCL 3.3 V powerdata (SDA) and clock (SCL)
Four wires. Power the BME280 from 3V3, never from 5 V, unless your breakout board says it has its own regulator.
  • BME280 VCC to ESP32 3V3
  • BME280 GND to ESP32 GND
  • BME280 SDA to ESP32 GPIO 21
  • BME280 SCL to ESP32 GPIO 22

GPIO 21 and 22 are the default I2C pins of a standard ESP32 board. Other ESP32 boards (S2, S3, C3) use different default pins; check your board's pin map.

BME280 or BMP280? The two look almost the same and are often sold under each other's name. The BMP280 has no humidity sensor. If the library says "not found" at both addresses and the wiring is right, read the chip marking or the seller's details: you may have a BMP280.

Know your units

Every number needs a unit, and the unit has to match what the dashboard expects. The Adafruit library returns:

FunctionUnitTypical indoor value
readTemperature()degrees Celsius18 to 30
readHumidity()percent relative humidity30 to 70
readPressure()pascals (Pa), not hectopascalsabout 101,325 at sea level

Pressure is the classic trap: weather reports use hectopascals (hPa), so divide by 100 before you send it. A chart that shows 101,325 when you expected 1,013 is a units bug, not a storm. When you define fields on the platform, give each one its unit, so every chart says what its numbers mean.

The sketch: many samples, one honest reading

This sketch takes a sample every 2 seconds, throws away any sample the sensor could not really give, and averages the rest into one reading every 30 seconds. It uses millis() as a timer instead of delay(), so later, when the same loop also handles the network, nothing waits.

#include <Adafruit_BME280.h>
Adafruit_BME280 bme;
bool sensorOk = false;
const unsigned long SAMPLE_MS = 2000; // one sample every 2 seconds
const int SAMPLES = 15; // 15 samples make one reading: one every 30 s
float sumT = 0, sumH = 0;
int taken = 0, good = 0;
unsigned long lastSample = 0;
// a value the sensor can really give, or a fault
bool sane(float t, float h) {
return !isnan(t) && !isnan(h) && t > -40.0 && t < 85.0 && h >= 0.0 && h <= 100.0;
}
void setup() {
Serial.begin(115200);
sensorOk = bme.begin(0x76) || bme.begin(0x77); // SDA = GPIO 21, SCL = GPIO 22
if (!sensorOk) {
Serial.println("BME280 not found: check the four wires and the address");
return;
}
// forced mode: the sensor measures only when asked, so it does not warm itself up
bme.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X1, // temperature
Adafruit_BME280::SAMPLING_X1, // pressure
Adafruit_BME280::SAMPLING_X1, // humidity
Adafruit_BME280::FILTER_OFF);
}
void loop() {
if (!sensorOk || millis() - lastSample < SAMPLE_MS) return;
lastSample = millis();
bme.takeForcedMeasurement();
float t = bme.readTemperature(); // degrees Celsius
float h = bme.readHumidity(); // percent relative humidity
taken++;
if (sane(t, h)) { sumT += t; sumH += h; good++; }
else Serial.printf("rejected sample: %.2f C, %.2f %%\n", t, h);
if (taken < SAMPLES) return;
if (good >= SAMPLES / 2) { // at least half of the samples were sane
Serial.printf("reading: %.1f C, %.1f %% (%d of %d samples)\n",
sumT / good, sumH / good, good, taken);
} else {
Serial.println("too few sane samples: no reading this time");
}
sumT = sumH = 0;
taken = good = 0;
}

Open the Serial Monitor at 115200 baud. Every 30 seconds you should see a line like the first two below. Breathe on the sensor and the humidity jumps, then settles over the next minute:

reading: 23.4 C, 51.2 % (15 of 15 samples)
reading: 23.4 C, 51.3 % (15 of 15 samples)
reading: 23.6 C, 63.8 % (15 of 15 samples) <- you breathed on it
reading: 23.5 C, 55.0 % (15 of 15 samples)

Why average?

Each sample has a little random noise in it. Averaging many samples cancels much of that noise, and the effect follows a simple rule: the noise of an average of n samples is the noise of one sample divided by √n.

Worked example

Single temperature samples wander by about ±0.3 °C around the true value. How much does an average of 15 samples wander, and what does it cost?

Show the worked solution, 3 steps
  1. Apply the rule

    √15 ≈ 3.9, so the average wanders by about 0.3 / 3.9 ≈ ±0.08 °C. The chart line becomes smooth. ✅

  2. The cost in time

    15 samples at one every 2 seconds take 30 seconds. A real change shows up in the reading within one 30 second window, and fully in the next. For a room, that delay does not matter. ✅

  3. The cost in messages

    None. You still send one reading every 30 seconds. Averaging on the device gives you a better number for the same data. ✅

Averaging removes random noise. It does not remove a steady error. If the sensor is three degrees warm because it sits on a warm board, the average is three degrees warm too, just very smooth. That needs placement and a reference check.

Limits that catch faults

The sane() function rejects any sample the BME280 cannot really produce: below -40 °C or above 85 °C (its working range), humidity outside 0 to 100%, or NaN ("not a number", which the library returns when a measurement failed). A rejected sample is printed and left out of the average.

The sketch also asks for at least half of the samples to be good. If 8 of 15 samples fail, something is wrong with the sensor or the wiring, and the honest answer is "no reading", not an average of the few that got through. A gap in the chart tells the truth; a wrong number hides it.

Place it and check it

  • Keep it away from heat. The ESP32 and its regulator warm the board by a few degrees when Wi-Fi is on. Put the sensor on wires a few centimetres away, out of direct sun, and not inside a sealed box: the air it measures must be the air you care about.
  • Use forced mode. The sketch asks the sensor to measure only when asked, then sleep. This is the setting the BME280 datasheet suggests for weather monitoring, and it keeps the chip from warming itself.
  • Check against a reference. Put a thermometer you trust next to the sensor for 30 minutes and compare the averages.
Your turn: the warm sensor

Over 30 minutes your BME280 averages 24.6 °C. A trusted thermometer beside it averages 23.8 °C. The difference stays the same when the room warms up. What do you do?

Show the answer, 3 steps
  1. Look for the cause first

    A steady +0.8 °C is often heat from the board. Move the sensor further away and compare again. If the gap shrinks, placement was the cause. ✅

  2. Then correct what is left

    If a steady gap remains, it is the sensor's own offset. The BME280's stated accuracy is about ±1 °C, so 0.8 °C is within its tolerance. Subtract it in firmware: t = bme.readTemperature() - 0.8; ✅

  3. Write it down

    Note the offset, the date and the reference you used beside the code. When someone asks why the device reads what it reads, you have the answer. ✅

When it does not work

  • "BME280 not found". Check the four wires, then the address. Most boards use 0x76; some use 0x77 (the sketch tries both). An I2C scanner sketch, included with the ESP32 board package under the Wire examples, lists every address it finds.
  • Humidity reads 0 or stays fixed. You probably have a BMP280, which has no humidity sensor.
  • The values jump wildly. Long or loose jumper wires on I2C pick up noise. Keep them under about 30 cm and push them fully home.
  • Temperature slowly climbs after power-on and settles a few degrees high. That is the board warming up. Move the sensor away from it.

Check yourself

Question 1

readPressure() returns 101325. What should you send to a weather chart?

Question 2

Single samples wander by ±0.4 °C. About how much does an average of 16 samples wander?

Question 3

Your sensor reads 3 °C too warm, all the time. Does averaging more samples fix it?

Question 4

In one 30 second window, 9 of 15 samples fail the sanity check. What should the device send?

Key points
  • Four wires: 3V3, GND, SDA to GPIO 21, SCL to GPIO 22. Power the BME280 from 3.3 V.
  • Know each unit: °C, % relative humidity, and pascals for pressure (divide by 100 for hPa).
  • Average many samples: noise falls with √n. Reject impossible samples, and send nothing when most fail.
  • Averaging does not fix a steady error. Keep the sensor away from heat and check it against a reference.

You now have a reading you can trust, printed on a serial port. Next, the same reading leaves the board: Wi-Fi, the right time, a checked certificate, and a publish over TLS.

Found this useful?

Discussion