CanSat Tutorials

Tutorial 7 of 9 · A real sensor

Connecting and programming the BMP280

Two wires, one library and a handful of lines gets you air temperature and air pressure, which is what the primary mission asks for.

Tutorials 1 2 3 4 5 6 7 8 9

The BMP280 is a chip about the size of a grain of rice. It measures air pressure and air temperature, and costs a couple of pounds on a small breakout board. Those two readings are the whole primary mission: measure them on the way down, and send them to your ground station once a second.

It measuresRangeRoughly how well
Air pressure300 to 1100 hPa±1 hPa absolute, and it can see changes much smaller than that
Air temperature-40 to +85 °C±1 °C
AltitudeCalculated, not measuredOnly as good as the sea level pressure you give it

Pressure falls as you go up, by roughly 12 pascals per metre near the ground. So a pressure sensor doubles as an altimeter. A CanSat released at 300 to 400 metres can work out its own height from the air around it.

Before you build

A BMP280 reads temperature to about one degree, and the air may only change a few degrees over a descent that lasts half a minute. Pressure, on the other hand, changes a lot and quickly. Ask yourself which of your two required readings will actually show a clear trend, and what that means for the graphs you have to produce.

Be careful with a BMP280 that is not BMP280. BMP180 is an older, less accurate chip. BME280 looks identical and adds humidity, needs a different library call, and is often sold in the same purple board shape. Check what you actually bought.

How it connects

Two wires, several sensors

The sensor and the board talk over a two wire bus called I2C, said as "eye squared see". One wire carries data, the other carries a clock that keeps both ends in step. Every device on the bus has an address, a number between 1 and 126, so the board can say who it is talking to.

Two wires carry the I2C bus from the board to every sensor on it Arduino Uno the controller SDA · PIN A4 · DATA SCL · PIN A5 · CLOCK BMP280 0x76 Another sensor 0x68
Every device shares the same two wires and is told apart by its address. Power and ground are not shown, but each device needs those too. Adding a second sensor costs you no extra pins, so I2C is the bus to learn first.

On an Uno the I2C pins are fixed: A4 is SDA and A5 is SCL. R3 boards also have a second pair of SDA and SCL pins next to AREF. Those are the same two pins brought out twice, so pick one pair and leave the other empty.

Wiring

Getting it connected without killing it

Check the voltage before you connect anything

Most cheap BMP280 breakouts, including the common small purple ones, are 3.3 volt parts with no regulator and no level shifting. Putting 5 volts on them will damage them, sometimes immediately and sometimes slowly enough that you blame your code. Some boards, such as Adafruit's, do have a regulator and are happy on 5 volts. Find out which one you have before it is wired in.

With a 3.3 volt module on an Uno, run VCC from the Uno's 3V3 pin. The SDA and SCL lines are then driven at 5 volts by the Uno. Most of these modules put up with that, although their data sheets do not promise it. Use this arrangement on the bench, then pick something better for the flight build: a level shifter, a module with one built in, or a 3.3 volt board such as a Pico, where the problem disappears.

BMP280 pinUno pinNotes
VCC or VIN3V3Unless your module is documented as 5 volt safe
GNDGNDAlways connect ground first and remove it last
SDA or SDIA4Data
SCL or SCKA5Clock
CSB, SDOLeave unconnectedThose are for SPI mode, and SDO selects the address on some boards

Setup

Installing the library and finding the sensor

You could read the sensor's registers yourself. Nobody does, because the calibration maths is fiddly and someone has already written it. That someone's code is called a library, and the IDE can install it for you.

  1. Open the Library Manager

    The books icon in the left sidebar, or Tools › Manage Libraries.

  2. Search for Adafruit BMP280

    Install Adafruit BMP280 Library. When it offers to install the libraries it depends on, say yes: it needs Adafruit Unified Sensor and Adafruit BusIO.

  3. Find the sensor before you try to read it

    Run the scanner sketch below. It should report a device at 0x76 or 0x77. If it reports nothing, stop and fix the wiring. If it reports a device at every address, SDA and SCL are probably swapped or shorted.

I2C scanner: what is on the bus?
// Ask every possible address on the bus whether anything is listening.
// Run this first. If it finds nothing, your wiring is wrong and no
// amount of sensor code will help.

#include <Wire.h>

void setup() {
  Wire.begin();
  Serial.begin(9600);
  delay(500);

  Serial.println("Scanning the I2C bus...");

  for (byte address = 1; address < 127; address++) {
    Wire.beginTransmission(address);
    byte error = Wire.endTransmission();

    if (error == 0) {
      Serial.print("Found a device at 0x");
      Serial.println(address, HEX);
    }
  }

  Serial.println("Scan finished");
}

void loop() {
}
Keep this sketch

The scanner is the most useful twenty lines in your sketchbook. Every time an I2C sensor misbehaves, the first question is whether the board can see it at all, and this answers that in five seconds. It also tells you the address to put in your code, and proves your wiring before you blame anything else.

The sketch

Reading the sensor, line by line

Reading temperature and pressure
#include <Wire.h>
#include <Adafruit_BMP280.h>

Adafruit_BMP280 bmp;              // our name for the sensor

void setup() {
  Serial.begin(9600);
  delay(500);

  if (!bmp.begin(0x76)) {         // 0x76 or 0x77: the scanner told you which
    Serial.println("No BMP280 found. Check wiring and address.");
    while (1) {                   // stop here rather than log nonsense
      delay(100);
    }
  }

  // How often and how carefully to measure. These settings are a
  // reasonable starting point for something that is moving.
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,
                  Adafruit_BMP280::SAMPLING_X2,      // temperature
                  Adafruit_BMP280::SAMPLING_X16,     // pressure
                  Adafruit_BMP280::FILTER_X16,
                  Adafruit_BMP280::STANDBY_MS_63);

  Serial.println("temp_C\tpressure_Pa\taltitude_m");
}

void loop() {
  float tempC = bmp.readTemperature();           // degrees Celsius
  float pressurePa = bmp.readPressure();         // pascals
  float altitudeM = bmp.readAltitude(1013.25);   // metres, see the warning

  Serial.print(tempC, 2);
  Serial.print("\t");
  Serial.print(pressurePa, 0);
  Serial.print("\t");
  Serial.println(altitudeM, 2);

  delay(1000);
}

Open the Serial Monitor. You should see three numbers a second. Breathe on the sensor and the temperature climbs. Lift it a metre off the desk and the pressure drops by about 12 pascals, which is small but visible.

Line by line

#include <Wire.h>
Pulls in the library that drives the I2C hardware. The angle brackets mean "look in the installed libraries". These lines go at the very top.
#include <Adafruit_BMP280.h>
Pulls in the sensor driver you just installed, which uses Wire underneath.
Adafruit_BMP280 bmp;
Creates an object and calls it bmp. From here on, bmp means your sensor. The name is yours to choose, like a variable name.
bmp.begin(0x76)
Wakes the sensor at that address, reads its factory calibration and checks it answers. It hands back true if all that worked.
if (!bmp.begin(0x76))
! means not, so this reads "if starting the sensor did not work". Checking is the difference between a log full of zeroes and knowing the sensor was missing.
while (1) { delay(100); }
A deliberate dead end. 1 counts as true, so this loops forever and the sketch stops. Better to stop loudly than to transmit made up data. Think about whether that is the right choice in flight, when nobody can reach the board.
bmp.setSampling(...)
How hard the sensor works: how many times it averages each reading, how much it smooths, how long it rests. More averaging gives quieter numbers but takes longer, and something falling at 15 metres per second has no time to spare. Try changing them.
bmp.readTemperature()
Hands back a float in degrees Celsius.
bmp.readPressure()
Hands back a float in pascals, not hectopascals. Normal sea level pressure is 101325 Pa, which is 1013.25 hPa. Divide by 100 if you want the units a weather forecast uses.
bmp.readAltitude(1013.25)
Works out a height from the pressure. The number you pass in is the pressure at sea level at that moment, which is not 1013.25 most days.
Why readAltitude can lie to you

There is no altitude sensor in a BMP280. It measures pressure and then a formula turns that into a height, using the sea level pressure you hand it. Use the standard 1013.25 when the real figure is 1025 and every altitude comes out tens of metres wrong, all in the same direction.

For a CanSat, two habits fix this. Always log raw pressure as well as any altitude, so the real data survives a bad assumption and you can recalculate afterwards. And on launch day, note the actual sea level pressure from a local weather station or a nearby airfield's METAR, and record it alongside your data. Height above the launch site is often more useful anyway, and you can get that by taking a reading on the ground before launch and subtracting.

Troubleshooting

If the sensor will not answer

What you seeWhat to check
Scanner finds nothingPower and ground first, then SDA and SCL, then whether they are swapped. A loose breadboard jumper is more likely than a dead sensor.
Scanner finds a device at a different addressFine. Put that address in bmp.begin(). Many modules select 0x76 or 0x77 from a solder bridge or the SDO pin.
No BMP280 found but the scanner sees itRight address, wrong chip. A BME280 or BMP180 answers on the same addresses and needs its own library.
All readings are the same number every timeThe sensor is in sleep mode or the sampling settings never got applied. Check setSampling ran after a successful begin.
Temperature reads two or three degrees highIt probably is. The chip warms itself slightly and sits next to other warm electronics. Note it, measure it against a thermometer, and say so in your report.
Readings jump around wildlyLong breadboard wires, no decoupling, or a shared supply with something noisy. Shorter wires are the first thing to try.
It worked, then stopped after you added a second sensorTwo devices on the same address, or no pull-up resistors. Most breakouts include them, and several boards in parallel can over-pull the bus.

Now change it

Change one thing at a time, upload, and watch what the board does.

  1. Run the scanner and write down your sensor's address. Put it in your project notes, because you will need it again later.
  2. Print pressure in hectopascals instead of pascals, to two decimal places. Compare it with the pressure on a weather site for your town. How close are you?
  3. Take a reading on the floor and another holding the sensor as high as you can reach. What is the difference in pascals, and does it match about 12 Pa per metre?
  4. Leave the sketch running for ten minutes without touching anything. Does the temperature drift? Plot it and you have your first real test result.
  5. Change SAMPLING_X16 to SAMPLING_X1 and look at how noisy the pressure becomes. Which setting would you fly, and why?
  6. Record the pressure on the ground, then work out your height above that point rather than above sea level. Which do you think the judges would rather see?
  7. Replace the delay(1000) with the millis() pattern from tutorial 4. You will need this for the next tutorial anyway.
  8. Decide what your sketch should do if begin() fails once the CanSat is sealed and on the launch pad. Stopping is one answer. Is it the right one?