diff --git a/README.md b/README.md new file mode 100644 index 0000000..3f86b70 --- /dev/null +++ b/README.md @@ -0,0 +1,130 @@ +![License: MIT](https://img.shields.io/badge/License-MIT-green.svg) +![author](https://img.shields.io/badge/author-AlexGyver-informational.svg) +# GyverBME280 +Лёгкая библиотека для работы с BME280 по I2C для Arduino + +### Совместимость +Совместима со всеми Arduino платформами (используются Arduino-функции) + +## Содержание +- [Установка](#install) +- [Инициализация](#init) +- [Использование](#usage) +- [Пример](#example) +- [Версии](#versions) +- [Баги и обратная связь](#feedback) + + +## Установка +- Библиотеку можно найти по названию **GyverBME280** и установить через менеджер библиотек в: + - Arduino IDE + - Arduino IDE v2 + - PlatformIO +- [Скачать библиотеку](https://github.com/GyverLibs/GyverBME280/archive/refs/heads/main.zip) .zip архивом для ручной установки: + - Распаковать и положить в *C:\Program Files (x86)\Arduino\libraries* (Windows x64) + - Распаковать и положить в *C:\Program Files\Arduino\libraries* (Windows x32) + - Распаковать и положить в *Документы/Arduino/libraries/* + - (Arduino IDE) автоматическая установка из .zip: *Скетч/Подключить библиотеку/Добавить .ZIP библиотеку…* и указать скачанный архив +- Читай более подробную инструкцию по установке библиотек [здесь](https://alexgyver.ru/arduino-first/#%D0%A3%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0_%D0%B1%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA) + + +## Инициализация +```cpp +GyverBME280 bme; +``` + + +## Использование +```cpp +bool begin(void); // запустить со стандартным адресом (0x76) +bool begin(uint8_t address); // запустить с указанием адреса +bool isMeasuring(void); // возвращает true, пока идёт измерение +float readPressure(void); // прочитать давление в Па +float readHumidity(void); // Прочитать влажность в % +void oneMeasurement(void); // Сделать одно измерение и уйти в сон +float readTemperature(void); // Прочитать температуру в градусах С + +void setMode(uint8_t mode); // установить режим работы +// режимы: +NORMAL_MODE +FORCED_MODE + +void setFilter(uint8_t mode); // изменить коэффициент фильтрации. Вызывать перед begin +// коэффициенты: +FILTER_DISABLE +FILTER_COEF_2 +FILTER_COEF_4 +FILTER_COEF_8 +FILTER_COEF_16 + +void setStandbyTime(uint8_t mode); // Изменить время между измерениями. Вызывать перед begin +// режимы: +STANDBY_500US +STANDBY_10MS +STANDBY_20MS +STANDBY_6250US +STANDBY_125MS +STANDBY_250MS +STANDBY_500MS +STANDBY_1000MS + +void setHumOversampling(uint8_t mode); // Настроить оверсэмплинг или отключить влажность. Вызывать перед begin +void setTempOversampling(uint8_t mode); // Настроить оверсэмплинг или отключить температуру. Вызывать перед begin +void setPressOversampling(uint8_t mode); // Настроить оверсэмплинг или отключить давление. Вызывать перед begin +// режимы: +MODULE_DISABLE +OVERSAMPLING_1 +OVERSAMPLING_2 +OVERSAMPLING_4 +OVERSAMPLING_8 +OVERSAMPLING_16 +``` + + +## Пример +Остальные примеры смотри в **examples**! +```cpp +/* + Простой пример, демонстрирующий основные функции измерения температуры, давления и влажности +*/ + +#include // Подключение библиотеки +GyverBME280 bme; // Создание обьекта bme + +void setup() { + Serial.begin(9600); // Запуск последовательного порта + bme.begin(); // Если доп. настройки не нужны - инициализируем датчик +} + +void loop() { + Serial.print("Temperature: "); + Serial.print(bme.readTemperature()); // Выводим темперутуру в [*C] + Serial.println(" *C"); + + Serial.print("Humidity: "); + Serial.print(bme.readHumidity()); // Выводим влажность в [%] + Serial.println(" %"); + + float pressure = bme.readPressure(); // Читаем давление в [Па] + Serial.print("Pressure: "); + Serial.print(pressure / 100.0F); // Выводим давление в [гПа] + Serial.print(" hPa , "); + Serial.print(pressureToMmHg(pressure)); // Выводим давление в [мм рт. столба] + Serial.println(" mm Hg"); + Serial.print("Altitide: "); + Serial.print(pressureToAltitude(pressure)); // Выводим высоту в [м над ур. моря] + Serial.println(" m"); + Serial.println(""); + delay(1000); +} +``` + + +## Версии +- v1.3 - исправлена ошибка при отриц. температуре +- v1.4 - разбил на h и cpp + + +## Баги и обратная связь +При нахождении багов создавайте **Issue**, а лучше сразу пишите на почту [alex@alexgyver.ru](mailto:alex@alexgyver.ru) +Библиотека открыта для доработки и ваших **Pull Request**'ов! \ No newline at end of file diff --git a/examples/custom_setup/custom_setup.ino b/examples/custom_setup/custom_setup.ino new file mode 100644 index 0000000..103793e --- /dev/null +++ b/examples/custom_setup/custom_setup.ino @@ -0,0 +1,33 @@ +/* + Пример индивидуальных настроек датчика под ваше применение + См. константы в GyverBME280.h , стандартные настройки можно изменить там же в классе GyverMBE280 + Настройки вступают в силу только ПОСЛЕ .begin(); +*/ + +#include // Подключение библиотеки +GyverBME280 bme; // Создание обьекта bme + +void setup() { + Serial.begin(9600); // Запуск последовательного порта + bme.setFilter(FILTER_COEF_8); // Настраиваем коофициент фильтрации + bme.setTempOversampling(OVERSAMPLING_8); // Настраиваем передискретизацию для датчика температуры + bme.setPressOversampling(OVERSAMPLING_16); // Настраиваем передискретизацию для датчика давления + bme.setStandbyTime(STANDBY_500MS); // Устанавливаем время сна между измерениями (у нас обычный циклический режим) + bme.begin(); // Если на этом настройки окончены - инициализируем датчик +} + +void loop() { + Serial.print("Temperature: "); + Serial.print(bme.readTemperature()); // Выводим темперутуру в [*C] + Serial.println(" *C"); + + Serial.print("Humidity: "); + Serial.print(bme.readHumidity()); // Выводим влажность в [%] + Serial.println(" %"); + + Serial.print("Pressure: "); + Serial.print(pressureToMmHg(bme.readPressure())); // Выводим давление в мм рт. столба + Serial.println(" mm Hg"); + Serial.println(""); + delay(1000); +} diff --git a/examples/low_power/low_power.ino b/examples/low_power/low_power.ino new file mode 100644 index 0000000..f077e71 --- /dev/null +++ b/examples/low_power/low_power.ino @@ -0,0 +1,31 @@ +/* + Пример работы датчика с пониженным энергопотреблением + По умолчанию - NORMAL_MODE - Время сна между преобразованиями - 250мс + См. константы в GyverBME280.h , стандартные настройки можно изменить там же в классе GyverMBE280 + Настройки вступают в силу только ПОСЛЕ .begin(); +*/ + +#include // Подключение библиотеки +GyverBME280 bme; // Создание обьекта bme + +void setup() { + Serial.begin(9600); // Запуск последовательного порта + bme.setHumOversampling(MODULE_DISABLE); // Отключаем неиспользуемый модуль измерения влажности - экономим энергию + // bme.setMode(FORCED_MODE); // По возможности используем принудительный режим с редким опросом + bme.setStandbyTime(STANDBY_1000MS); // Если используем обычный режим - увеличиваем время сна между измерениями насколько это возможно в нашем случае + bme.begin(); // Если на этом настройки окончены - инициализируем датчик +} + +void loop() { + // bme.oneMeasurement(); // Если используем принудительный мод - необходимо будить датчик для проведения измерения + // while (bme.isMeasuring()); // И дождаться окончания текущего измерения , чтобы не взять устаревшие данные + Serial.print("Temperature: "); + Serial.print(bme.readTemperature()); // Выводим темперутуру в [*C] + Serial.println(" *C"); + + Serial.print("Pressure: "); + Serial.print(pressureToMmHg(bme.readPressure())); // Выводим давление в мм рт. столба + Serial.println(" mm Hg"); + Serial.println(""); + delay(1000); +} diff --git a/examples/modes/modes.ino b/examples/modes/modes.ino new file mode 100644 index 0000000..2809eb5 --- /dev/null +++ b/examples/modes/modes.ino @@ -0,0 +1,57 @@ +/* + Пример работы датчика в двух режимах - обычном и принудительном , а так же перезапись настроек во время работы + О режимах: + NORMAL_MODE - Обычный - датчик делает измерения циклически , между измерениями спит , время сна настраивается с помощью .setStandbyTime(); , см пример low_power + FORCED_MODE - Принудительный - датчик спит , после вызова .oneMeasurement(); просыпается и делает ОДНО преобразование , после чего уходит в сон + По умолчанию - NORMAL_MODE - Время сна между преобразованиями - 250мс + См. константы в GyverBME280.h , стандартные настройки можно изменить там же в классе GyverMBE280 +*/ + +#include // Подключение библиотеки +GyverBME280 bme; // Создание обьекта bme + +void setup() { + Serial.begin(9600); // Запуск последовательного порта + bme.setMode(FORCED_MODE); // Перед инициализацией говорим датчику работать в принудительном режиме + bme.begin(); // Больше настройки не нужны - инициализируем датчик + + while (millis() < 10000) { // Работа с датчиком в принудительном режиме в течении первых 10 секунд + bme.oneMeasurement(); // Просим датчик проснуться и сделать одно преобразование + while (bme.isMeasuring()); // Ждем окончания преобразования + + Serial.print("Temperature: "); + Serial.print(bme.readTemperature()); // Читаем и выводим температуру + Serial.println(" *C"); + + Serial.print("Humidity: "); + Serial.print(bme.readHumidity()); // Читаем и выводим влажность + Serial.println(" %"); + + Serial.print("Pressure: "); + Serial.print(pressureToMmHg(bme.readPressure())); // Читаем и выводим давление + Serial.println(" mm Hg"); + Serial.println(""); + delay(1000); + } + + bme.setMode(NORMAL_MODE); // Спустя 10 секунд переключаем датчик в обычный режим + bme.begin(); // Переинициализируем датчик после изменения настроек - обязательная процедура + +} + +void loop() { // Работа с датчиком в обычном режиме , преобразования идут в цикличном режиме + + Serial.print("Temperature: "); + Serial.print(bme.readTemperature()); // Читаем и выводим температуру + Serial.println(" *C"); + + Serial.print("Humidity: "); + Serial.print(bme.readHumidity()); // Читаем и выводим влажность + Serial.println(" %"); + + Serial.print("Pressure: "); + Serial.print(pressureToMmHg(bme.readPressure())); // Читаем и выводим давление + Serial.println(" mm Hg"); + Serial.println(""); + delay(1000); +} diff --git a/examples/simple/simple.ino b/examples/simple/simple.ino new file mode 100644 index 0000000..2a89f79 --- /dev/null +++ b/examples/simple/simple.ino @@ -0,0 +1,33 @@ +/* + Простой пример, демонстрирующий основные функции измерения температуры, давления и влажности +*/ + +#include // Подключение библиотеки +GyverBME280 bme; // Создание обьекта bme + +void setup() { + Serial.begin(9600); // Запуск последовательного порта + bme.begin(); // Если доп. настройки не нужны - инициализируем датчик +} + +void loop() { + Serial.print("Temperature: "); + Serial.print(bme.readTemperature()); // Выводим темперутуру в [*C] + Serial.println(" *C"); + + Serial.print("Humidity: "); + Serial.print(bme.readHumidity()); // Выводим влажность в [%] + Serial.println(" %"); + + float pressure = bme.readPressure(); // Читаем давление в [Па] + Serial.print("Pressure: "); + Serial.print(pressure / 100.0F); // Выводим давление в [гПа] + Serial.print(" hPa , "); + Serial.print(pressureToMmHg(pressure)); // Выводим давление в [мм рт. столба] + Serial.println(" mm Hg"); + Serial.print("Altitide: "); + Serial.print(pressureToAltitude(pressure)); // Выводим высоту в [м над ур. моря] + Serial.println(" m"); + Serial.println(""); + delay(1000); +} diff --git a/keywords.txt b/keywords.txt new file mode 100644 index 0000000..956c5a2 --- /dev/null +++ b/keywords.txt @@ -0,0 +1,52 @@ + +####################################### +# Syntax Coloring Map For GyverBME280 +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### +GyverBME280 KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +begin KEYWORD2 +isMeasuring KEYWORD2 +setFilter KEYWORD2 +setMode KEYWORD2 +setStandbyTime KEYWORD2 +setHumOversampling KEYWORD2 +setTempOversampling KEYWORD2 +setPressOversampling KEYWORD2 +oneMeasurement KEYWORD2 +readTemperature KEYWORD2 +readPressure KEYWORD2 +readHumidity KEYWORD2 +pressureToAltitude KEYWORD2 +pressureToMmHg KEYWORD2 +####################################### +# Constants (LITERAL1) +####################################### + +NORMAL_MODE LITERAL1 +FORCED_MODE LITERAL1 +STANDBY_500US LITERAL1 +STANDBY_10MS LITERAL1 +STANDBY_20MS LITERAL1 +STANDBY_6250US LITERAL1 +STANDBY_125MS LITERAL1 +STANDBY_250MS LITERAL1 +STANDBY_500MS LITERAL1 +STANDBY_1000MS LITERAL1 +MODULE_DISABLE LITERAL1 +OVERSAMPLING_1 LITERAL1 +OVERSAMPLING_2 LITERAL1 +OVERSAMPLING_4 LITERAL1 +OVERSAMPLING_8 LITERAL1 +OVERSAMPLING_16 LITERAL1 +FILTER_DISABLE LITERAL1 +FILTER_COEF_2 LITERAL1 +FILTER_COEF_4 LITERAL1 +FILTER_COEF_8 LITERAL1 +FILTER_COEF_16 LITERAL1 \ No newline at end of file diff --git a/library.properties b/library.properties new file mode 100644 index 0000000..19200e0 --- /dev/null +++ b/library.properties @@ -0,0 +1,9 @@ +name=GyverBME280 +version=1.4 +author=AlexGyver +maintainer=AlexGyver +sentence=Light library for BME280 sensor +paragraph=Light library for BME280 sensor +category=Sensors +url=https://github.com/GyverLibs/GyverBME280 +architectures=* \ No newline at end of file diff --git a/src/GyverBME280.cpp b/src/GyverBME280.cpp new file mode 100644 index 0000000..ad6801d --- /dev/null +++ b/src/GyverBME280.cpp @@ -0,0 +1,217 @@ +#include "GyverBME280.h" + +/* ============ Utilities ============ */ + +float pressureToAltitude(float pressure) { + if(!pressure) return 0; // If the pressure module has been disabled return '0' + pressure /= 100.0F; // Convert [Pa] to [hPa] + return 44330.0 * (1.0 - pow(pressure / 1013.25, 0.1903)); // Сalculate altitude +} + +float pressureToMmHg(float pressure) { + return (float)(pressure * 0.00750061683f); // Convert [Pa] to [mm Hg] +} + +/* ============ Setup & begin ============ */ + +bool GyverBME280::begin(void) { + return GyverBME280::begin(0x76); +} + +bool GyverBME280::begin(uint8_t address) { + _i2c_address = address; + /* === Start I2C bus & check BME280 === */ + Wire.begin(); // Start I2C bus + if(!GyverBME280::reset()) return false; // BME280 software reset & ack check + if(GyverBME280::readRegister(0xD0) != 0x60) return false; // Check chip ID + GyverBME280::readCalibrationData(); // Read all calibration values + + /* === Load settings to BME280 === */ + GyverBME280::writeRegister(0xF2 , _hum_oversampl); // write hum oversampling value + GyverBME280::writeRegister(0xF2 , GyverBME280::readRegister(0xF2)); // rewrite hum oversampling register + GyverBME280::writeRegister(0xF4 , ((_temp_oversampl << 5) | (_press_oversampl << 2) | _operating_mode)); // write temp & press oversampling value , normal mode + GyverBME280::writeRegister(0xF5 , ((_standby_time << 5) | (_filter_coef << 2))); // write standby time & filter coef + return true; +} + +void GyverBME280::setMode(uint8_t mode) { + _operating_mode = mode; +} + + +void GyverBME280::setFilter(uint8_t mode) { + _filter_coef = mode; +} + +void GyverBME280::setStandbyTime(uint8_t mode) { + _standby_time = mode; +} + +void GyverBME280::setHumOversampling(uint8_t mode) { + _hum_oversampl = mode; +} + +void GyverBME280::setTempOversampling(uint8_t mode) { + _temp_oversampl = mode; +} + +void GyverBME280::setPressOversampling(uint8_t mode) { + _press_oversampl = mode; +} + +/* ============ Reading ============ */ + +int32_t GyverBME280::readTempInt(void) { + int32_t temp_raw = GyverBME280::readRegister24(0xFA); // Read 24-bit value + if (temp_raw == 0x800000) return 0; // If the temperature module has been disabled return '0' + + temp_raw >>= 4; // Start temperature reading in integers + int32_t value_1 = ((((temp_raw >> 3) - ((int32_t)CalibrationData._T1 << 1))) * + ((int32_t)CalibrationData._T2)) >> 11; + int32_t value_2 = (((((temp_raw >> 4) - ((int32_t)CalibrationData._T1)) * + ((temp_raw >> 4) - ((int32_t)CalibrationData._T1))) >> 12) * ((int32_t)CalibrationData._T3)) >> 14; + + return ((int32_t)value_1 + value_2); // Return temperature in integers +} + + +float GyverBME280::readTemperature(void) { + int32_t temp_raw = GyverBME280::readTempInt(); + float T = (temp_raw * 5 + 128) >> 8; + return T / 100; // Return temperature in float +} + + +float GyverBME280::readPressure(void) { + uint32_t press_raw = GyverBME280::readRegister24(0xF7); // Read 24-bit value + if (press_raw == 0x800000) return 0; // If the pressure module has been disabled return '0' + + press_raw >>= 4; // Start pressure converting + int64_t value_1 = ((int64_t)GyverBME280::readTempInt()) - 128000; + int64_t value_2 = value_1 * value_1 * (int64_t)CalibrationData._P6; + value_2 = value_2 + ((value_1 * (int64_t)CalibrationData._P5) << 17); + value_2 = value_2 + (((int64_t)CalibrationData._P4) << 35); + value_1 = ((value_1 * value_1 * (int64_t)CalibrationData._P3) >> 8) + ((value_1 * (int64_t)CalibrationData._P2) << 12); + value_1 = (((((int64_t)1) << 47) + value_1)) * ((int64_t)CalibrationData._P1) >> 33; + + if (!value_1) return 0; // Avoid division by zero + + int64_t p = 1048576 - press_raw; + p = (((p << 31) - value_2) * 3125) / value_1; + value_1 = (((int64_t)CalibrationData._P9) * (p >> 13) * (p >> 13)) >> 25; + value_2 = (((int64_t)CalibrationData._P8) * p) >> 19; + p = ((p + value_1 + value_2) >> 8) + (((int64_t)CalibrationData._P7) << 4); + + return (float)p / 256; // Return pressure in float +} + + +float GyverBME280::readHumidity(void) { + Wire.beginTransmission(_i2c_address); // Start I2C transmission + Wire.write(0xFD); // Request humidity data register + if(Wire.endTransmission() != 0) return 0; + Wire.requestFrom(_i2c_address, 2); // Request humidity data + int32_t hum_raw = ((uint16_t)Wire.read() << 8) | (uint16_t)Wire.read(); // Read humidity data + if (hum_raw == 0x8000) return 0; // If the humidity module has been disabled return '0' + + int32_t value = (GyverBME280::readTempInt() - ((int32_t)76800)); // Start humidity converting + value = (((((hum_raw << 14) - (((int32_t)CalibrationData._H4) << 20) - + (((int32_t)CalibrationData._H5) * value)) +((int32_t)16384)) >> 15) * + (((((((value * ((int32_t)CalibrationData._H6)) >> 10) *(((value * + ((int32_t)CalibrationData._H3)) >> 11) + ((int32_t)32768))) >> 10) + + ((int32_t)2097152)) * ((int32_t)CalibrationData._H2) + 8192) >> 14)); + value = (value - (((((value >> 15) * (value >> 15)) >> 7) * ((int32_t)CalibrationData._H1)) >> 4)); + value = (value < 0) ? 0 : value; + value = (value > 419430400) ? 419430400 : value; + float h = (value >> 12); + + return h / 1024.0; // Return humidity in float +} + +/* ============ Misc ============ */ + +bool GyverBME280::isMeasuring(void) { + return (bool)((GyverBME280::readRegister(0xF3) & 0x08) >> 3); // Read status register & mask bit "measuring" +} + +void GyverBME280::oneMeasurement(void) { + GyverBME280::writeRegister(0xF4 , ((GyverBME280::readRegister(0xF4) & 0xFC) | 0x02)); // Set the operating mode to FORCED_MODE +} + +GyverBME280::GyverBME280() {} + +/* ============ Private ============ */ + +/* = BME280 software reset = */ +bool GyverBME280::reset(void) { + if(!GyverBME280::writeRegister(0x0E , 0xB6)) return false; + delay(10); + return true; +} + + +/* = Read and combine three BME280 registers = */ +uint32_t GyverBME280::readRegister24(uint8_t address) { + Wire.beginTransmission(_i2c_address); + Wire.write(address); + if(Wire.endTransmission() != 0) return 0x800000; + Wire.requestFrom(_i2c_address, 3); + return (((uint32_t)Wire.read() << 16) | ((uint32_t)Wire.read() << 8) | (uint32_t)Wire.read()); +} + + +/* = Write one 8-bit BME280 register = */ +bool GyverBME280::writeRegister(uint8_t address , uint8_t data) { + Wire.beginTransmission(_i2c_address); + Wire.write(address); + Wire.write(data); + if(Wire.endTransmission() != 0) return false; + return true; +} + + +/* = Read one 8-bit BME280 register = */ +uint8_t GyverBME280::readRegister(uint8_t address) { + Wire.beginTransmission(_i2c_address); + Wire.write(address); + if(Wire.endTransmission() != 0) return 0; + Wire.requestFrom(_i2c_address , 1); + return Wire.read(); +} + +/* = Structure to store all calibration values = */ +void GyverBME280::readCalibrationData(void) { + /* first part request*/ + Wire.beginTransmission(_i2c_address); + Wire.write(0x88); + if(Wire.endTransmission() != 0) return; + Wire.requestFrom(_i2c_address , 25); + /* reading */ + CalibrationData._T1 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._T2 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._T3 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P1 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P2 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P3 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P4 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P5 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P6 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P7 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P8 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._P9 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._H1 = Wire.read(); + + /* second part request*/ + Wire.beginTransmission(_i2c_address); + Wire.write(0xE1); + Wire.endTransmission(); + Wire.requestFrom(_i2c_address , 8); + /* reading */ + CalibrationData._H2 = (Wire.read() | (Wire.read() << 8)); + CalibrationData._H3 = Wire.read(); + CalibrationData._H4 = (Wire.read() << 4); + uint8_t interVal = Wire.read(); + CalibrationData._H4 |= (interVal & 0xF); + CalibrationData._H5 = (((interVal & 0xF0) >> 4) | (Wire.read() << 4)); + CalibrationData._H6 = Wire.read(); +} \ No newline at end of file diff --git a/src/GyverBME280.h b/src/GyverBME280.h new file mode 100644 index 0000000..2517188 --- /dev/null +++ b/src/GyverBME280.h @@ -0,0 +1,111 @@ +/* + Лёгкая библиотека для работы с BME280 по I2C для Arduino + Документация: + GitHub: https://github.com/GyverLibs/GyverBME280 + + Egor 'Nich1con' Zaharov for AlexGyver, alex@alexgyver.ru + https://alexgyver.ru/ + MIT License + + Версии: + v1.3 - исправлена ошибка при отриц. температуре + v1.4 - разбил на h и cpp +*/ + +#ifndef GyverBME280_h +#define GyverBME280_h + +#include +#include + +#define NORMAL_MODE 0x03 +#define FORCED_MODE 0x02 + +#define STANDBY_500US 0x00 +#define STANDBY_10MS 0x06 +#define STANDBY_20MS 0x07 +#define STANDBY_6250US 0x01 +#define STANDBY_125MS 0x02 +#define STANDBY_250MS 0x03 +#define STANDBY_500MS 0x04 +#define STANDBY_1000MS 0x05 + +#define MODULE_DISABLE 0x00 +#define OVERSAMPLING_1 0x01 +#define OVERSAMPLING_2 0x02 +#define OVERSAMPLING_4 0x03 +#define OVERSAMPLING_8 0x04 +#define OVERSAMPLING_16 0x05 + +#define FILTER_DISABLE 0x00 +#define FILTER_COEF_2 0x01 +#define FILTER_COEF_4 0x02 +#define FILTER_COEF_8 0x03 +#define FILTER_COEF_16 0x04 + + +// ================================= CLASS =================================== + +class GyverBME280 { + +public: + GyverBME280(); // Create an object of class BME280 + bool begin(void); // Initialize sensor with standart 0x76 address + bool begin(uint8_t address); // Initialize sensor with not standart 0x76 address + bool isMeasuring(void); // Returns 'true' while the measurement is in progress + float readPressure(void); // Read and calculate atmospheric pressure [float , Pa] + float readHumidity(void); // Read and calculate air humidity [float , %] + void oneMeasurement(void); // Make one measurement and go back to sleep [FORCED_MODE only] + void setMode(uint8_t mode); + float readTemperature(void); // Read and calculate air temperature [float , *C] + void setFilter(uint8_t mode); // Adjust the filter ratio other than the standard one [before begin()] + void setStandbyTime(uint8_t mode); // Adjust the sleep time between measurements [NORMAL_MODE only][before begin()] + void setHumOversampling(uint8_t mode); // Set oversampling or disable humidity module [before begin()] + void setTempOversampling(uint8_t mode); // Set oversampling or disable temperature module [before begin()] + void setPressOversampling(uint8_t mode); // Set oversampling or disable pressure module [before begin()] + +private: + + //============================== DEFAULT SETTINGS ========================================| + int _i2c_address = 0x76; // BME280 address on I2C bus | + uint8_t _operating_mode = NORMAL_MODE; // Sensor operation mode | + uint8_t _standby_time = STANDBY_250MS; // Time between measurements in NORMAL_MODE | + uint8_t _filter_coef = FILTER_COEF_16; // Filter ratio IIR | + uint8_t _temp_oversampl = OVERSAMPLING_4; // Temperature module oversampling parameter | + uint8_t _hum_oversampl = OVERSAMPLING_1; // Humidity module oversampling parameter | + uint8_t _press_oversampl = OVERSAMPLING_2; // Pressure module oversampling parameter | + //========================================================================================| + + bool reset(void); // BME280 software reset + int32_t readTempInt(); // Temperature reading in integers for the function of reading + void readCalibrationData(void); // Read all cells containing calibration values + uint8_t readRegister(uint8_t address); // Read one 8-bit BME280 register + uint32_t readRegister24(uint8_t address); // Read and combine three BME280 registers + bool writeRegister(uint8_t address , uint8_t data); // Write one 8-bit BME280 register + + struct { // Structure to store all calibration values + uint16_t _T1; + int16_t _T2; + int16_t _T3; + uint16_t _P1; + int16_t _P2; + int16_t _P3; + int16_t _P4; + int16_t _P5; + int16_t _P6; + int16_t _P7; + int16_t _P8; + int16_t _P9; + uint8_t _H1; + int16_t _H2; + uint8_t _H3; + int16_t _H4; + int16_t _H5; + int8_t _H6; + } CalibrationData; + +}; + +float pressureToMmHg(float pressure); // Convert [Pa] to [mm Hg] +float pressureToAltitude(float pressure); // Convert pressure to altitude +#endif \ No newline at end of file