Bme280

Содержание

BME280 — датчик атмосферного давления, влажности и температуры

Сегодня расскажу о датчике BME280 с помощью которого можно получить показания влажности, температуры, атмосферного давления и высоту (расчетную). Данный датчик прост, предварительно откалиброван и для подключения не требуется дополнительных компонентов.

Общие сведения

Рассмотрим модуль поближе, в правой части расположен датчик BME280 фирмы Bosch (это приемник таких датчиков, как BMP180, BMP085). Данный датчик измеряет влажность, температуру и давление с помощью данных показаний осуществляется расчет высоты, но эти показания не точные, подробно о датчике можно посмотреть в документации. На обратной стороне установлен стабилизатор напряжения LM6206 на 3.3 В и преобразователь уровней I2C, поэтому можно подключить модуль к микроконтроллерам с 3.3 В или 5 В логикой, не боясь.

Назначение контактов:► VCC, GND — питание модуля 3.3 В или 5 В ► SCL — линия тактирования (Serial CLock)► SDA — линия данных (Serial Data)

Данный модуль работает по двухпроводному интерфейсу I2C, адрес по умолчанию 0x76, но есть возможность изменить на адрес 0x77. Если присмотреться на модуль, рядом с датчиком расположены контакты, по умолчанию левый и средний контакт замкнуты проводником. Необходимо острым предметом перерезать проводник и установить припоем перемычку между центральный и правым контактом,тем самым установив адрес 0x77. При необходимости можно вернуть адрес 0x76.

Подключение датчика давления BME280 к Arduino

Необходимые детали:► BME280 — датчик атмосферного давления, влажности и температуры x 1 шт.► Arduino UNO R3 (DCCduino, CH340G)x 1 шт.► Провод DuPont 10x, 2,54 мм, 20 см, F-F (Female — Female) x 1 шт.

Подключение:В данном примере используем датчик BME280 и плату Arduino UNO R3, все получение показание отправлять в «Мониторинг порта», принципе и все, осталось собрать схему по рисунку ниже. Для интерфейса I2C на плате arduino предусмотрено только два вывода A4 и A5, другие вывода не поддерживают I2C, так что учтите при проектирование.

Программа:Для датчика BME280 разработана библиотека «Adafruit BME280 Library» с помощью которой можно упростить работу с датчиком. Так же, для работы датчика необходима дополнительная библиотека «Adafruit Unified Sensor«. Скачать библиотеки можно в конце статьи или можно скачать через «Менеджер библиотек» в среде разработки IDE Arduino.

Источник

Скетч 1: метеостанция с OLED-дисплеем

Для компиляции и загрузки скетча нужно установить в Arduino дополнительные библиотеки:

  • ESP8266 OLED SSD1306
  • Adafruit Unified Sensor Driver
  • Adafruit BME280 Library

После установки в файле библиотеки BME280 нужно вручную поправить адрес с 0x77 на 0x76:

(Установленные библиотеки Arduino IDE хранит в папке \Documents\Arduino\libraries текущего пользователя Windows)

После чего остается только скомпилировать и загрузить в память ESP8266 следующий скетч:

#include "Wire.h"
#include "Adafruit_Sensor.h"
#include "Adafruit_BME280.h"
#include "SSD1306.h"

const float SEA_LEVEL_PRESSURE_HPA = 1013.25;
const int DELAY = 3000;
const int STARTUP_DELAY = 500;


Adafruit_BME280 bme;

SSD1306 display(0x3c, D6, D5);

void setup() 
{
 Serial.begin(115200);
 Wire.begin(D6, D5);
 Wire.setClock(100000); 
 if(!bme.begin())
 {
 Serial.println("Could not find a valid BME280 sensor, check wiring!");
 while (1)
 {
 yield();
 delay(DELAY);
 }
 }
 delay(STARTUP_DELAY);

display.init();
 display.flipScreenVertically();

}

void loop() 
{
 float tempC = bme.readTemperature();
 float humidity = bme.readHumidity();
 float pressurePascals = bme.readPressure();

// Print to serial monitor
 printToSerial(tempC, humidity, pressurePascals);

// Display data on screen in metric units
 drawWithMetricUnits(tempC, humidity, pressurePascals);
 yield();
 delay(DELAY);
}

void drawWithMetricUnits(float tempC, float humidity, float pressurePascals)
{
 float pressureHectoPascals = pressurePascals / 100.0;
 
 display.clear();
 
 display.drawRect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT);
 
 display.setFont(ArialMT_Plain_16);
 display.drawString(35, 3, "BME280");
 
 display.setFont(ArialMT_Plain_10);
 display.drawString(5, 22, "Temperature = " + String(tempC) + " *C");
 display.drawString(5, 35, "Humidity = " + String(humidity) + "%");
 display.drawString(5, 48, "Pressure = " + String(pressureHectoPascals) + " h,Pa");
 
 display.display();
}

void printToSerial(float tempC, float humidity, float pressurePascals)
{
 // Temperature
 float tempF = 9.0/5.0 * tempC + 32.0;

Serial.println("Temperature:");
 printValueAndUnits(tempC, "*C");
 printValueAndUnits(tempF, "*F");
 //printValueAndUnits(tempC, "°C");
 //printValueAndUnits(tempF, "°F");
 Serial.println("");

// Barometric pressure
 float pressureHectoPascals = pressurePascals / 100.0;
 float pressureInchesOfMercury = 0.000295299830714 * pressurePascals;

Serial.println("Pressure:");
 printValueAndUnits(pressurePascals, "Pa");
 printValueAndUnits(pressureHectoPascals, "hPa");
 printValueAndUnits(pressureInchesOfMercury, "inHg");
 Serial.println("");

// Humidity
 Serial.println("Humidity:");
 printValueAndUnits(humidity, "%");
 Serial.println("");

// Approximate altitude
 float altitudeMeters = bme.readAltitude(SEA_LEVEL_PRESSURE_HPA);
 float altitudeFeet = 3.28 * altitudeMeters;
 
 Serial.println("Approx. Altitude:");
 printValueAndUnits(altitudeMeters, "m");
 printValueAndUnits(altitudeFeet, "ft");
 Serial.println();
}

void printValueAndUnits(float value, String units)
{
 Serial.print(" ");
 Serial.print(value);
 Serial.print(" ");
 Serial.println(units);
}

Вот так будет выглядеть собранное устройство в работе:

Датчик меряет все доступные ему показатели (температура, влажность, давление) и они выводятся на экран. Показатели обновляются – обновляется информация на экране. Все.

К слову, на фотографии выше можно увидеть какой низкий уровень влажности стоит в помещении зимой в период работы центрального отопления. Низкая влажность негативно влияет на самочувствие людей и комнатных растений, а также ускоряет деградацию деревянной мебели и картин.

Регулярное отслеживание показателей микроклимата в помещении может стать первым шагом к его оздоровлению путем установки увлажнителей воздуха, термостатов и автоматических проветривателей.

I2C Interface

The module features a simple two-wire I2C interface which can be easily interfaced with any microcontroller of your choice.

The default I2C address of the BME280 module is 0x76HEX and can be changed to 0x77HEX easily with the solder jumper besides chip.

Procedure to Change I2C Address

  • Locate the solder jumper besides chip. By default the middle copper pad is connected to the left pad.
  • Scratch the connection between the middle and the left copper pad to disconnect those using a sharp knife.
  • Add a solder blob between the middle and the right copper pad to join them. It allows you to set the I2C address 0x77HEX.

Overview

The BME280 from Bosch Sensortec is a integrated environmental sensor designed for the mobile market. It a low power consumption design that combines high linearity and high
accuracy sensors for pressure, humidity and temperature.

The BME280 supports either SPI or I2C interface to communicate with the micro controller.

Because of the small size of the sensor, the best way to use this sensor is with a breakout board. The Adafruit breakout board is used here.

In this hookup we are only connecting one device to the Arduino using the I2C bus. We can use either address (0x77 or 0x76). It reads the barometric pressure, humidity and
temperature and displays it on the console.

Подключение BMP280 к Arduino по I2C/TWI

Так как датчик может работать по I2C и SPI, подключение можно реализовать двумя методами. При подключении по I2C нужно соединить контакты SDA и SCL.

Схема подключения BMP280 к Arduino

Для подключения понадобятся сам датчик BMP280, плата Ардуино, соединительные провода. Схема подключения показана на рисунке ниже.

Землю с Ардуино нужно соединить с землей на датчике, напряжение 3.3 В — на 3.3 В, SDA — к пину А4, SCL — к А5. Контакты А4 и А5 выбираются с учетом их поддержки интерфейса I2C.

Существуют несколько модулей с этим датчиком. Первый вариант — это модуль для работы в 3.3 В логике, данные модули будут подешевле; второй вариант — для работы в 5.0 В логике, на нём присутствуют: линейный стабилизатор напряжения на 3.3 В и преобразователи уровней 3.3/5.0 В на линиях SCK/SCL и SDI(MOSI)/SDA. Первый подойдёт для ардуин работающих от 3.3 В и Raspberry Pi / Orange Pi / Banana Pi и т.д., а второй — для обычных ардуин на 5.0 В.

Подключение BMP280 с встроенными стабилизатором напряжения на 3.3 В и преобразователями уровней 3.3/5.0 В на линиях SCK/SCL и SDI(MOSI)/SDA к Arduino.

Arduino Mega Arduino Uno/Nano/Pro Mini BMP280 модуль Цвет проводов на фото
GND GND GND Черный
5V 5V Vin Красный
20 (SDA) A4 SDA/SDI Зелёный
21 (SCL) A5 SCL/SCK Жёлтый

Подключение BMP280 без встроенного стабилизатора напряжения на 3.3 В к Arduino. В данном случае нужно использовать внешний преобразователь уровней на линиях SCK/SCL и SDI(MOSI)/SDA.

Arduino Mega Arduino Uno/Nano/Pro Mini BMP280 модуль Цвет проводов на фото
GND GND GND Черный
3.3V 3.3V VCC/3.3V Красный
20 (SDA) A4 SDA/SDI Зелёный
21 (SCL) A5 SCL/SCK Жёлтый

Примеры скетча

После запуска вы можете инициализировать датчик с помощью:

if (!bmp.begin()) {
Serial.println(«Could not find a valid BMP280 sensor, check wiring!»);
while (1);
}

1
2
3
4

if(!bmp.begin()){

Serial.println(«Could not find a valid BMP280 sensor, check wiring!»);

while(1);

}

вернет True, если датчик был найден, и False, если нет. В случае с False, проверьте соединение датчика с платой Arduino!

Считать температуру и давление легко, просто вызовите функции:

bmp.readTemperature(); // Температура в градусах Цельсия.
bmp.readPressure(); // Атмосферное давление в гПа

1
2

bmp.readTemperature();// Температура в градусах Цельсия.

bmp.readPressure();// Атмосферное давление в гПа

Копируйте и скомпилируйте нижеприведённый скетч в Arduino IDE.

#include <Adafruit_BMP280.h>

Adafruit_BMP280 bmp280;

void setup() {
Serial.begin(9600);
Serial.println(F(«BMP280»));

while (!bmp280.begin(BMP280_ADDRESS — 1)) {
Serial.println(F(«Could not find a valid BMP280 sensor, check wiring!»));
delay(2000);
}
}

void loop() {
float temperature = bmp280.readTemperature();
float pressure = bmp280.readPressure();
float altitude = bmp280.readAltitude(1013.25);

Serial.print(F(«Temperature = «));
Serial.print(temperature);
Serial.println(» *C»);

Serial.print(F(«Pressure = «));
Serial.print(pressure);
Serial.println(» Pa»);

Serial.print(F(«Altitude = «));
Serial.print(altitude);
Serial.println(» m»);

Serial.println();
delay(2000);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#include <Adafruit_BMP280.h>
 

Adafruit_BMP280bmp280;

voidsetup(){

Serial.begin(9600);

Serial.println(F(«BMP280»));

while(!bmp280.begin(BMP280_ADDRESS-1)){

Serial.println(F(«Could not find a valid BMP280 sensor, check wiring!»));

delay(2000);

}

}
 

voidloop(){

floattemperature=bmp280.readTemperature();

floatpressure=bmp280.readPressure();

floataltitude=bmp280.readAltitude(1013.25);

Serial.print(F(«Temperature = «));

Serial.print(temperature);

Serial.println(» *C»);

Serial.print(F(«Pressure = «));

Serial.print(pressure);

Serial.println(» Pa»);

Serial.print(F(«Altitude = «));

Serial.print(altitude);

Serial.println(» m»);

Serial.println();

delay(2000);

}

Результат

Температура рассчитывается в градусах Цельсия, вы можете преобразовать ее в градусы Фаренгейта, используя классическое уравнение F = C * 9/5 + 32.

Давление возвращается в единицах СИ Паскалей. 100 Паскалей = 1 гПа = 1 миллибар. Часто барометрическое давление сообщается в миллибарах или миллиметрах ртутного столба. Для дальнейшего использования 1 паскаль = 0,00750062 миллиметров ртутного столба или 1 миллиметр ртутного столба = 133,322 Паскаля. Таким образом, если вы возьмете значение паскаля, скажем, 100734 и разделите на 133,322, вы получите 755,57 миллиметров ртутного столба.

Также возможно превратить BMP280 в альтиметр. Если вы знаете давление на уровне моря, библиотека может рассчитать текущее атмосферное давление в высоту.

bme280.setup()¶

Initializes module. Initialization is mandatory before read values.

Parameters

  • (optional) — Controls oversampling of temperature data. Default oversampling is 16x.
  • (optional) — Controls oversampling of pressure data. Default oversampling is 16x.
  • (optional) — Controls oversampling of humidity data. Default oversampling is 16x
  • (optional) — Controls the sensor mode of the device. Default sensor more is normal.
  • (optional) — Controls inactive duration in normal mode. Default inactive duration is 20ms.
  • (optional) — Controls the time constant of the IIR filter. Default filter coefficient is 16.
  • (optional) — If 0 then the BME280 chip is not initialised. Useful in a battery operated setup when the ESP deep sleeps and on wakeup needs to initialise the driver (the module) but not the chip itself. The chip was kept powered (sleeping too) and is holding the latest reading that should be fetched quickly before another reading starts (). By default the chip is initialised.
, , Data oversampling
Skipped (output set to 0x80000)
1 oversampling ×1
2 oversampling ×2
3 oversampling ×4
4 oversampling ×8
5 oversampling ×16
Sensor mode
Sleep mode
1 and 2 Forced mode
3 Normal mode

Using forced mode is recommended for applications which require low sampling rate or hostbased synchronization. The sensor enters into sleep mode after a forced readout. Please refer to BME280 Final Datasheet for more details.

t standby (ms)
0.5
1 62.5
2 125
3 250
4 500
5 1000
6 10
7 20
Filter coefficient
Filter off
1 2
2 4
3 8
4 16

Example

Or simpler and more efficient

Use for «game mode» — Oversampling settings pressure ×4, temperature ×1, humidity ×0, sensor mode: normal mode, inactive duration = 0.5 ms, IIR filter settings filter coefficient 16.

Example of readout in forced mode (asynchronous)

Код Arduino, считывание показаний температуры, относительной влажности воздуха и атмосферного давления

Следующий скетч даст вам полное представление о том, как считывать показания температуры, относительной влажности и барометрического давления с модуля BME280, и может послужить основой для более практических экспериментов и проектов.

Вот как выглядит вывод в мониторе последовательного порта.

Рисунок 11 – Вывод показаний датчика BME280. Температура, относительная влажность, атмосферное давление и высота над уровнем моря

Объяснение кода

Скетч начинается с подключения четырех библиотек, а именно, Wire.h, SPI.h, Adafruit_Sensor.h и Adafruit_BME280.h.

Затем мы определяем переменную , необходимую для вычисления высоты, и создаем объект библиотеки , чтобы мы могли получить доступ к функциям, связанным с ней.

В функции мы инициализируем последовательную связь с компьютером и вызываем функцию .

Функция в качестве параметра принимает адрес модуля на шине I2C. Если ваш модуль имеет другой адрес I2C или вы изменили его, вам нужно указать его правильно. Эта функция инициализирует интерфейс I2C с заданным адресом и проверяет правильность идентификатора чипа. Затем она программно перезапускает микросхему и ждет окончания калибровки датчика после запуска.

В зацикленном фрагменте кода для считывания значений температуры, относительной влажности и атмосферного давления из модуля BME280 мы используем следующие функции:

  • функция возвращает от датчика температуру;
  • функция возвращает от датчика атмосферное давление;
  • функция вычисляет высоту (в метрах) исходя из текущего атмосферного давления (в гПа) и давления на уровне моря (в гПа);
  • функция возвращает от датчика относительную влажность воздуха.

Wrapping Up

This article was an in-depth guide on how to get pressure, temperature and humidity readings from a BME280 sensor with the ESP8266 using Arduino IDE and display the readings on a web server.

Now, you can take this project further and display your sensor readings in an OLED display; create a datalogger; save the readings in your own database or send the readings to your Home Automation platform using MQTT. Here’s some projects and tutorials that might help you implement these ideas:

  • ESP32 Publish Sensor Readings to Google Sheets
  • Low Power Weather Station Datalogger (MicroPython)
  • ESP32/ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE
  • ESP8266 and Node-RED with MQTT (Publish and Subscribe)
  • What is MQTT and How It Works

Learn more about the ESP8266 with our course: Home Automation using ESP8266

Thanks for reading.

Описание библиотеки для работы с датчиком. Пример скетча

Для работы с датчиком BMP180 существуют различные библиотеки, упрощающие работу. К ним относятся SFE_BMP180, Adafruit_BMP085. Эти же библиотеки подходят для работы с датчиком BMP080.  Для датчика bmp280 используется похожая библиотека Adafruit_BMP280.

Первый пробный скетч будет заставлять датчик считывать показания давления и температуры. Код подойдет как для датчика BMP180 , так и для BMP280, нужно только подключить правильную библиотеку и указать верные контакты, к которым подключен модуль. В первую очередь в коде нужно подключить все библиотеки и инициализировать работу датчика. Для определения давления нужно сначала узнать температуру. Для этого используется следующий элемент кода.

    status = pressure.startTemperature();// Считываются данные с датчика о температуре    if(status!=0){    delay(status); // Ожидание    status = pressure.getTemperature(T); // Сохранение полученных данных о температуре    if(status!=0){    Serial.print("Temperature: "); // Выведение на экран слова «Температура»    Serial.print(T,2); // Вывод на экран значения температуры.    Serial.println("deg C, "); //Печать символа градуса Цельсия.    

Затем нужно получить информацию об атмосферном давлении.

    status = pressure.startPressure(3); // происходит считывание давления    if(status!=0){    delay(status); // Ожидание    status = pressure.getPressure(P,T); // получение давления, сохранение    if(status!=0){    Serial.print("Absolute pressure: "); // Вывод на экран слов «Атмосферное давление»    Serial.print(P,2); // Вывод на экран значения переменной mBar    Serial.print(" mbar, "); // Вывод на экран текста "mBar"    Serial.print(P*0.7500637554192,2); // вывод на экран значения в mmHg (мм.рт.ст.)    Serial.println(" mmHg");} // вывод на экран единицы измерения давления "mmHg" (мм. Рт.ст.).    

После загрузки скетча в окне мониторинг порта появятся данные о температуре и атмосферном давлении.

Датчик BME280 также показывает давление и температуру, дополнительно он может считывать показания о влажности, который по умолчанию выключен. При необходимости можно произвести настройки датчика и начать считывать показания о влажности. Диапазон измерения от 0 до 100%. Библиотека, которая нужна для работы с датчиком, называется Adafruit_BME280.

Код похож на тот, что описан выше, только к нему еще добавляются строки для определения влажности.

    void printValues() {    Serial.print("Temperature = ");    Serial.print(bme.readTemperature());    Serial.println(" C"); //определение температуры, вывод ее на экран в градусах Цельсия.    Serial.print("Pressure = ");    Serial.print(bme.readPressure() / 100.0F);    Serial.println(" hPa"); //определение давления, вывод его на экран    Serial.print("Humidity = ");    Serial.print(bme.readHumidity());    Serial.println(" %"); //определение влажности в процентах, вывод измеренного значения на экран.    Serial.println();    }    

bme280.setup()¶

Initializes module. Initialization is mandatory before read values.

Parameters

  • (optional) — Controls oversampling of temperature data. Default oversampling is 16x.
  • (optional) — Controls oversampling of pressure data. Default oversampling is 16x.
  • (optional) — Controls oversampling of humidity data. Default oversampling is 16x
  • (optional) — Controls the sensor mode of the device. Default sensor more is normal.
  • (optional) — Controls inactive duration in normal mode. Default inactive duration is 20ms.
  • (optional) — Controls the time constant of the IIR filter. Default filter coefficient is 16.
  • (optional) — If 0 then the BME280 chip is not initialised. Useful in a battery operated setup when the ESP deep sleeps and on wakeup needs to initialise the driver (the module) but not the chip itself. The chip was kept powered (sleeping too) and is holding the latest reading that should be fetched quickly before another reading starts (). By default the chip is initialised.
, , Data oversampling
Skipped (output set to 0x80000)
1 oversampling ×1
2 oversampling ×2
3 oversampling ×4
4 oversampling ×8
5 oversampling ×16
Sensor mode
Sleep mode
1 and 2 Forced mode
3 Normal mode

Using forced mode is recommended for applications which require low sampling rate or hostbased synchronization. The sensor enters into sleep mode after a forced readout. Please refer to BME280 Final Datasheet for more details.

t standby (ms)
0.5
1 62.5
2 125
3 250
4 500
5 1000
6 10
7 20
Filter coefficient
Filter off
1 2
2 4
3 8
4 16

Example

Or simpler and more efficient

Use for «game mode» — Oversampling settings pressure ×4, temperature ×1, humidity ×0, sensor mode: normal mode, inactive duration = 0.5 ms, IIR filter settings filter coefficient 16.

Example of readout in forced mode (asynchronous)

Wiring BME280 Module to Arduino UNO

Let’s hook the BME280 module up to the Arduino.

Connections are fairly simple. Start by connecting VIN pin to the 5V output on the Arduino and connect GND to ground.

Now we are remaining with the pins that are used for I2C communication. Note that each Arduino Board has different I2C pins which should be connected accordingly. On the Arduino boards with the R3 layout, the SDA (data line) and SCL (clock line) are on the pin headers close to the AREF pin. They are also known as A5 (SCL) and A4 (SDA).

If you have a Mega, the pins are different! You’ll want to use digital 21 (SCL) and 20 (SDA). Refer below table for quick understanding.

SCL SDA
Arduino Uno A5 A4
Arduino Nano A5 A4
Arduino Mega 21 20
Leonardo/Micro 3 2

The following diagram shows you how to wire everything.


Wiring BME280 Module to Arduino

Software

The hookup and Arduino Sketch is for connecting a single Adafruit BME280 breakout board using either address 0x77 or 0x76.

You will need to download the cactus.io BME280_I2C library to work with this sample sketch. The library supports reading the barometric pressure,
humidity and temperature from the sensor.

To get the data from the sensor we need to call bme.readSensor(). We can then call the various functions to get the temperature, humidity and pressure.

The sensor returns the temperature in degrees celsius by design. We can call the method in the BME280 library called getTemperature_C to get the celsius
value or getTemperature_F for the value in fahrenheit.

The barometric pressure from the sensor is returned in Pascals. 100 Pascals = 1hPa = 1 millibar. The library method getPressure_P will return the
value in Pascals. The method getPressure_MB will return the value in millibars.

When we create the BME280 object in the sketch we can use the default which is BME280_I2C bme which will create an object using the default 0x77 address.
To create an object using the alternative address (0x76) we need to declare it as BME280_I2C bme(0x76).

We have found that when the BME280 is enclosed inside a case or nearby a circuit board the heat generated by voltage regulators can affect the temperature
reading from the BME280. We have included a function in the library that allows us to apply a temperature calibration offset to the value returned by getTemperature_C
or _F. Basically it justs adds the calibration offset. So if the temperature is reading 2 degrees high then we use this function:

bme.setTempCal(-2);   which will subtract 2 degrees from the temperture reading.

The default calibration offset is 0. So you only have to use this function if you want to apply a calibration value other than 0.

  • The sketch Supports only I2C bus connection.
  • The sketch Supports only one sensor connected.
  • Its blocking code.

Software

The hookup and Arduino Sketch is for connecting a single Adafruit BME280 breakout board.

You will need to download the cactus.io BME280_SPI library to work with this sample sketch. The library supports reading the barometric pressure,
humidity and temperature from the sensor.

We create the BME280 object in one of two ways. The first way is if we are using the hardware SPI pins as shown above. Uncomment line 10 in the code below
and comment out line 11.

To use software SPI which allows us to use alternate digital pins we need to comment out line 10 and uncomment line 11. We also need to define what pins we are using. This is
done in lines 4 to 7. We need to change the defines pin numbering to correspond to the SPI functions. For example if digital pin 7 is connected to CS on the
breakout board we would change line 7 to #define BME280_CS from 10 to 7.

To get the data from the sensor we need to call bme.readSensor(). We can then call the various functions to get the temperature, humidity and pressure.

The sensor returns the temperature in degrees celsius by design. We can call the method in the BME280 library called getTemperature_C to get the celsius
value or getTemperature_F for the value in fahrenheit.

The barometric pressure from the sensor is returned in Pascals. 100 Pascals = 1hPa = 1 millibar. The library method getPressure_MB will return the value in millibars.

When we create the BME280 object in the sketch we define the hardware pins that are used for chip select, data in and out and finally the serial clock.

We have found that when the BME280 is enclosed inside a case or nearby a circuit board the heat generated by voltage regulators can affect the temperature
reading from the BME280. We have included a function in the library that allows us to apply a temperature calibration offset to the value returned by getTemperature_C
or _F. Basically it justs adds the calibration offset. So if the temperature is reading 2 degrees high then we use this function:

bme.setTempCal(-2);    which will subtract 2 degrees from the temperture reading.

  • The sketch Supports only SPI bus connection.
  • The sketch Supports only one sensor connected.
  • Its blocking code.

Подключение модуля GY-BMP280-3.3 по шине SPI


Схема подключения к Arduino по шине SPI

  • VCC   —>  Arduino VCC (3.3 V)
  • GND  —>  Arduino GND
  • SCL   —>  Arduino D13  ( SPI / SCK )
  • SDO  —>  Arduino  D12 ( SPI / MISO )
  • SDA  —>   Arduino D11  ( SPI / MOSI )
  • CSB  —>   Arduino D10 ( SPI / CS,SS )

Скетч для работы с Arduino Uno по шине SPI:

Arduino

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

//Adafruit_BMP280 bme; // I2C
Adafruit_BMP280 bme(BMP_CS); // hardware SPI
//Adafruit_BMP280 bme(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);

void setup() {
Serial.begin(9600);
Serial.println(F(«BMP280 test»));

if (!bme.begin()) {
Serial.println(F(«Could not find a valid BMP280 sensor, check wiring!»));
while (1);
}
}

void loop() {
Serial.print(F(«Temperature = «));
Serial.print(bme.readTemperature());
Serial.println(» *C»);

Serial.print(F(«Pressure = «));
Serial.print(bme.readPressure());
Serial.println(» Pa»);

Serial.print(F(«Approx altitude = «));
Serial.print(bme.readAltitude(1013.25)); // this should be adjusted to your local forcase
Serial.println(» m»);

Serial.println();
delay(2000);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

//Adafruit_BMP280 bme; // I2C

Adafruit_BMP280bme(BMP_CS);// hardware SPI

//Adafruit_BMP280 bme(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

voidsetup(){

Serial.begin(9600);

Serial.println(F(«BMP280 test»));

if(!bme.begin()){

Serial.println(F(«Could not find a valid BMP280 sensor, check wiring!»));

while(1);

}

}

voidloop(){

Serial.print(F(«Temperature = «));

Serial.print(bme.readTemperature());

Serial.println(» *C»);

Serial.print(F(«Pressure = «));

Serial.print(bme.readPressure());

Serial.println(» Pa»);

Serial.print(F(«Approx altitude = «));

Serial.print(bme.readAltitude(1013.25));// this should be adjusted to your local forcase

Serial.println(» m»);

Serial.println();

delay(2000);

}

Скетч такой же, как и в первом примере, за исключением изменения нескольких строк:

Arduino

//Adafruit_BMP280 bme; // I2C — раскомментировать для шины I²C
Adafruit_BMP280 bme(BMP_CS); // hardware SPI — раскомментировать для шины SPI
//Adafruit_BMP280 bme(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);

1
2
3

//Adafruit_BMP280 bme; // I2C  —  раскомментировать для шины I²C

Adafruit_BMP280bme(BMP_CS);// hardware SPI  —  раскомментировать для шины SPI

//Adafruit_BMP280 bme(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

Две последнии строчки отличаются режимом работы SPI — аппаратным или программным. Под программным SPI понимается использование драйвера Arduino SPI для эмуляции аппаратного SPI с использованием «битовой синхронизации». Это позволяет подключить SPI-устройство к любым контактам Arduino.

Результат работы скетча выводится на Монитор порта (Serial Monitor, вызывается клавишами CTRL+SHIFT+M) среды программирования Arduino IDE.

Обзор модуля атмосферного давления BMP280

Модуль представляет из себя высокоточный цифровой измеритель атмосферного давления на базе микро-чипа BMP280 от фирмы BOSH. После изготовления каждый датчик проходит индивидуальную калибровку в заводских условиях. Его малые размеры, низкое энергопотребление и высокая измерительная способность позволили завоевать популярность среди множества разработчиков Arduino-проектов. Модуль BMP280 был разработан фирмой как более технологичная модель своего предшественника BMP180. Данная модификация, в отличие от своего младшего брата, предоставляет пользователю целых 2 последовательных интерфейса обмена данными (SPI и I2C), а также 3 режима работы:

NORMAL – в данном режиме модуль просыпается с определённой периодичностью, выполняет необходимые измерения и снова засыпает. Частота измерений задаётся программным путём, а результат считывается при необходимости.

SLEEP – режим максимально пониженного энергопотребления.

FORCED – этот режим позволяет будить модуль подачей внешнего управляющего сигнала. После выполнения измерений, модуль автоматически переходит в режим пониженного энергопотребления.

Помимо способности измерять показания атмосферного давления, разработчик наделил BMP280 возможностью определять температуру окружающей среды. Все производимые вычисления могут быть отфильтрованы настраиваемым программным фильтром. На рисунке №1 показан внешний вид модуля и его электрическая схема.

Рисунок №1 — внешний вид и схема модуля BMP280

Как видно из вышеприведенной схемы на модуле предусмотрены конденсаторы для фильтрации по питанию и подтягивающие резисторы интерфейсов ввода/вывода.