Full Code of kriswiner/ESP32 for AI

master a7973d4dca78 cached
76 files
602.6 KB
194.5k tokens
89 symbols
1 requests
Download .txt
Showing preview only (632K chars total). Download the full file or copy to clipboard to get everything.
Repository: kriswiner/ESP32
Branch: master
Commit: a7973d4dca78
Files: 76
Total size: 602.6 KB

Directory structure:
gitextract_wmdjks10/

├── Bosch/
│   ├── BME280_VEML6040_LTSleep.ino
│   ├── BNO055_MS5637.ino
│   └── readme.md
├── CCS811_BME280_ESP32C3Mini_WebServer/
│   ├── BME280.cpp
│   ├── BME280.h
│   ├── CCS811.cpp
│   ├── CCS811.h
│   ├── CCS811_BME280_ESP32C3Mini_WebServer.ino
│   ├── I2CDev.cpp
│   ├── I2CDev.h
│   └── Readme.md
├── CCS811_BME280_ESP32C3Mini_deepSleep/
│   ├── BME280.cpp
│   ├── BME280.h
│   ├── CCS811.cpp
│   ├── CCS811.h
│   ├── CCS811_BME280_ESP32C3Mini_deepSleep.ino
│   ├── I2CDev.cpp
│   ├── I2CDev.h
│   └── Readme.md
├── EM7180/
│   ├── EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/
│   │   ├── EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32.ino
│   │   ├── I2Cdev.cpp
│   │   ├── I2Cdev.h
│   │   ├── LIS2MDL.cpp
│   │   ├── LIS2MDL.h
│   │   ├── LPS22HB.cpp
│   │   ├── LPS22HB.h
│   │   ├── LSM6DSM.cpp
│   │   ├── LSM6DSM.h
│   │   ├── USFS.cpp
│   │   └── USFS.h
│   └── Readme.md
├── ESP32C3MiniEnvSensor/
│   ├── ESP32C3Mini_EnvSensor.v02b/
│   │   ├── APDS9253.cpp
│   │   ├── APDS9253.h
│   │   ├── ESP32C3Mini_EnvSensor.v02b.ino
│   │   ├── HDC2010.cpp
│   │   ├── HDC2010.h
│   │   ├── I2Cdev.cpp
│   │   ├── I2Cdev.h
│   │   ├── LPS22HB.cpp
│   │   ├── LPS22HB.h
│   │   ├── SPIFlash.cpp
│   │   └── SPIFlash.h
│   ├── Readme.md
│   ├── SPIFlash_ESP32C3Mini/
│   │   └── SPIFlash_ESP32C3Mini.ino
│   └── readSPIFlash_ESP32C3Mini_EnvSensor.v02b/
│       ├── SPIFlash.cpp
│       ├── SPIFlash.h
│       └── readSPIFlash_ESP32C3Mini_EnvSensor.v02b.ino
├── MPU9250_MS5637/
│   ├── MPU9250_MS5637_AHRS.ino
│   ├── MS5637.ino
│   ├── quaternionFilters.ino
│   └── readme.md
├── MPU9250_MS5637_AHRS_UDP/
│   ├── MPU9250_MS5637_AHRS_UDP.ino
│   ├── quaternionFilters.ino
│   └── readme.md
├── PWM/
│   ├── ledcWrite_demo_ESP32.ino
│   └── readme.md
├── README.md
├── SPI/
│   ├── Readme.md
│   └── SPIFlash_ESP32.ino
├── VISHAY/
│   ├── VEML6040.ino
│   └── readme.md
├── VL53L0x/
│   ├── VL53L0X_ESP32.ino
│   └── readme.md
└── extras/
    └── FreeIMU_cube_UDP_ES32/
        ├── AverageCompassVals.pde
        ├── FreeIMU_cube_UDP_ES32.pde
        ├── Kalman.pde
        ├── MathUtils.java
        ├── MotionDetect.pde
        ├── ODO.pde
        ├── Quaternion.java
        ├── SMA.pde
        ├── StopWatch.pde
        ├── Unused.pde
        ├── code/
        │   └── RXTXcomm.jar
        └── data/
            ├── ArialMT-10.vlw
            └── CourierNew36.vlw

================================================
FILE CONTENTS
================================================

================================================
FILE: Bosch/BME280_VEML6040_LTSleep.ino
================================================
/* BME280 and VEML6040 Basic Example Code using ESP32
 by: Kris Winer
 date: December 14, 2016
 license: Beerware - Use this code however you'd like. If you 
 find it useful you can buy me a beer some time.
 
 This sketch uses SDA/SCL on pins 0/2, respectively, and it uses the ESP32.
 
 The BME280 is a simple but high resolution pressure/humidity/temperature sensor, which can be used in its high resolution
 mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 only 1 microAmp. The choice will depend on the application.

 VEML6040 color sensor senses red, green, blue, and white light and incorporates photodiodes, amplifiers, 
 and analog / digital circuits into a single chip using CMOS process. With the   color   sensor   applied,   
 the   brightness,   and   color temperature of backlight can be adjusted base on ambient light  source  
 that  makes  panel  looks  more  comfortable  for  end   user’s   eyes.   VEML6040’s   adoption   of   FiltronTM
 technology  achieves  the  closest  ambient  light  spectral  sensitivity to real human eye responses.

 VEML6040  provides  excellent  temperature  compensation  capability  for  keeping  the  output  stable  
 under  changing  temperature.   VEML6040’s   function   are   easily   operated   via the simple command format 
 of I2C (SMBus compatible) interface  protocol.  VEML6040’s  operating  voltage  ranges  from   2.5   V   to   
 3.6   V.   VEML6040   is   packaged   in   a   lead  (Pb)-free  4  pin  OPLGA  package  which  offers  the  best market-proven reliability.

 
 SDA and SCL should have 4K7 pull-up resistors (to 3.3V).
 
 Hardware setup:
 SDA ----------------------- 21
 SCL ----------------------- 22
 
  */
#include "Wire.h"   
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>
//#include <WebServer.h>
//#include <ESP32mDNS.h>
//#include <ArduinoOTA.h>

/*#include "gpio.h"
extern "C" {
#include "user_interface.h"
  bool wifi_set_sleep_type(sleep_type_t);
  sleep_type_t wifi_get_sleep_type(void);
}
*/
// Must immediately declare functions to avoid "Not declared in this scope" errors
void      I2Cscan();
void      writeByte(uint8_t address, uint8_t subAddress, uint8_t data);
uint8_t   readByte(uint8_t address, uint8_t subAddress);
void      readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest);
int32_t  readBME280Temperature();
int32_t  readBME280Pressure();
int32_t  readBME280Humidity();
void      BME280Init();
uint32_t  BME280_compensate_P(int32_t adc_P);
int32_t   BME280_compensate_T(int32_t adc_T);
uint32_t  BME280_compensate_H(int32_t adc_H);
uint16_t  getRGBWdata(uint16_t * destination);
void      enableVEML6040();
//void      initWifi();

//ADC_MODE(ADC_VCC); // to use getVcc, don't use if using battery voltage monotor

// BME280 registers
#define BME280_HUM_LSB    0xFE
#define BME280_HUM_MSB    0xFD
#define BME280_TEMP_XLSB  0xFC
#define BME280_TEMP_LSB   0xFB
#define BME280_TEMP_MSB   0xFA
#define BME280_PRESS_XLSB 0xF9
#define BME280_PRESS_LSB  0xF8
#define BME280_PRESS_MSB  0xF7
#define BME280_CONFIG     0xF5
#define BME280_CTRL_MEAS  0xF4
#define BME280_STATUS     0xF3
#define BME280_CTRL_HUM   0xF2
#define BME280_RESET      0xE0
#define BME280_ID         0xD0  // should be 0x60
#define BME280_CALIB00    0x88
#define BME280_CALIB26    0xE1

////////////////////////////
// VEML6040 Command Codes //
////////////////////////////
#define  VEML6040_CONF            0x00 // command codes
#define  VEML6040_R_DATA          0x08  
#define  VEML6040_G_DATA          0x09 
#define  VEML6040_B_DATA          0x0A
#define  VEML6040_W_DATA          0x0B

#define VEML6040_ADDRESS         0x10
#define BME280_ADDRESS           0x76   // Address of BMP280 altimeter when ADO = 0

#define SerialDebug true  // set to true to get Serial output for debugging
#define myLed 5

enum Posr {
  P_OSR_00 = 0,  // no op
  P_OSR_01,
  P_OSR_02,
  P_OSR_04,
  P_OSR_08,
  P_OSR_16
};

enum Hosr {
  H_OSR_00 = 0,  // no op
  H_OSR_01,
  H_OSR_02,
  H_OSR_04,
  H_OSR_08,
  H_OSR_16
};

enum Tosr {
  T_OSR_00 = 0,  // no op
  T_OSR_01,
  T_OSR_02,
  T_OSR_04,
  T_OSR_08,
  T_OSR_16
};

enum IIRFilter {
  full = 0,  // bandwidth at full sample rate
  BW0_223ODR,
  BW0_092ODR,
  BW0_042ODR,
  BW0_021ODR // bandwidth at 0.021 x sample rate
};

enum Mode {
  BME280Sleep = 0,
  forced,
  forced2,
  normal
};

enum SBy {
  t_00_5ms = 0,
  t_62_5ms,
  t_125ms,
  t_250ms,
  t_500ms,
  t_1000ms,
  t_10ms,
  t_20ms,
};

enum IT {
  IT_40 = 0, //   40 ms
  IT_80,     //   80 ms
  IT_160,    //  160 ms
  IT_320,    //  320 ms
  IT_640,    //  640 ms
  IT_1280   // 1280 ms
};

// Specify BME280 configuration
uint8_t Posr = P_OSR_16, Hosr = H_OSR_16, Tosr = T_OSR_02, Mode = normal, IIRFilter = BW0_042ODR, SBy = t_62_5ms;     // set pressure amd temperature output data rate
// t_fine carries fine temperature as global value for BME280
int32_t t_fine;

// Specify VEML6070 Integration time
uint8_t IT = IT_160;
uint8_t ITime = 160;  // milliseconds
uint16_t RGBWData[4] = {0, 0, 0, 0};
float GSensitivity = 0.25168/((float) (IT + 1)); // ambient light sensitivity increases with integration time
float redLight, greenLight, blueLight, ambientLight;

float Temperature, Pressure, Humidity; // stores BME280 pressures sensor pressure and temperature
float VBAT;  // battery voltage from ESP8285 ADC read
int32_t rawPress, rawTemp, rawHumidity;   // pressure and temperature raw count output for BME280

// BME280 compensation parameters
uint8_t  dig_H1, dig_H3, dig_H6;
uint16_t dig_T1, dig_P1, dig_H4, dig_H5;
int16_t  dig_T2, dig_T3, dig_P2, dig_P3, dig_P4, dig_P5, dig_P6, dig_P7, dig_P8, dig_P9, dig_H2;

float   temperature_C, temperature_F, pressure, humidity, altitude; // Scaled output of the BME280

uint32_t delt_t = 0, count = 0, sumCount = 0;  // used to control display output rate

/*ESP8266WebServer server(80);
 
String webString="";     // String to display
 
void handle_root() {
  server.send(200, "text/plain", "Hello from the environmental monitoring station ESP8285!");
  delay(100);
}

  String createHTML(float var1, float var2, float var3, float var4, float var5, float var6, float var7, float var8, float var9, float var10) {
   webString = "<html><head><meta http-equiv=\"Refresh\" content=\"10\"></head><body><UL>"

  +String("<LI>Temperature = ")+String(var1)+String(" C</LI>") 
  +String("<LI>Temperature = ")+String(var2)+String(" F</LI>") 
  +String("<LI>Pressure = ")+String(var3)+String(" milliBar</LI>") 
  +String("<LI>Altitude = ")+String(var4)+String(" feet</LI>") 
  +String("<LI>Humidity = ")+String(var5)+String(" %RH</LI>") 
  +String("<LI>Red Light = ")+String(var6)+String(" microWatts/sq. cm</LI>") 
  +String("<LI>Green Light = ")+String(var7)+String(" microWatts/sq. cm</LI>") 
  +String("<LI>Blue Light = ")+String(var8)+String(" microWatts/sq. cm</LI>") 
  +String("<LI>Ambient Light = ")+String(var9)+String(" lux</LI>") 
  +String("<LI>Battery Voltage = ")+String(var10)+String(" V</LI>") 
     
  +"</UL></body></html>" ;
   return webString;
  }
*/

void setup()
{

  Serial.begin(115200);
  delay(4000);

  pinMode(myLed, OUTPUT);
  digitalWrite(myLed, HIGH);
  
  Wire.begin(21, 22, 400000); // SDA (21), SCL (22) on ESP32, 400 kHz rate

  I2Cscan(); // should detect BME280 at 0x76
  
  // Read the WHO_AM_I register of the BME280 this is a good test of communication
  byte f = readByte(BME280_ADDRESS, BME280_ID);  // Read WHO_AM_I register for BME280
  Serial.print("BME280 "); 
  Serial.print("I AM "); 
  Serial.print(f, HEX); 
  Serial.print(" I should be "); 
  Serial.println(0x60, HEX);
  Serial.println(" ");
  
 // delay(1000); 

  if(f == 0x60) {
   
  writeByte(BME280_ADDRESS, BME280_RESET, 0xB6); // reset BME280 before initilization
  delay(100);

  BME280Init(); // Initialize BME280 altimeter
  Serial.println("Calibration coeficients:");
  Serial.print("dig_T1 ="); 
  Serial.println(dig_T1);
  Serial.print("dig_T2 ="); 
  Serial.println(dig_T2);
  Serial.print("dig_T3 ="); 
  Serial.println(dig_T3);
  Serial.print("dig_P1 ="); 
  Serial.println(dig_P1);
  Serial.print("dig_P2 ="); 
  Serial.println(dig_P2);
  Serial.print("dig_P3 ="); 
  Serial.println(dig_P3);
  Serial.print("dig_P4 ="); 
  Serial.println(dig_P4);
  Serial.print("dig_P5 ="); 
  Serial.println(dig_P5);
  Serial.print("dig_P6 ="); 
  Serial.println(dig_P6);
  Serial.print("dig_P7 ="); 
  Serial.println(dig_P7);
  Serial.print("dig_P8 ="); 
  Serial.println(dig_P8);
  Serial.print("dig_P9 ="); 
  Serial.println(dig_P9);
  Serial.print("dig_H1 ="); 
  Serial.println(dig_H1);
  Serial.print("dig_H2 ="); 
  Serial.println(dig_H2);
  Serial.print("dig_H3 ="); 
  Serial.println(dig_H3);
  Serial.print("dig_H4 ="); 
  Serial.println(dig_H4);
  Serial.print("dig_H5 ="); 
  Serial.println(dig_H5);
  Serial.print("dig_H6 ="); 
  Serial.println(dig_H6);
 }
  else Serial.println(" BME280 not functioning!");

  enableVEML6040(); // initalize sensor
  delay(150);  

  // Get some information abut the ESP8285

  uint32_t freeheap = ESP.getFreeHeap();
  Serial.print("Free Heap Size = "); Serial.println(freeheap);
 // uint32_t chipID = ESP.getChipId();
 // Serial.print("ESP32 chip ID = "); Serial.println(chipID);
//  uint32_t flashChipID = ESP.getFlashChipId();
// Serial.print("ESP8285 flash chip ID = "); Serial.println(flashChipID);
  uint32_t flashChipSize = ESP.getFlashChipSize();
  Serial.print("ESP32 flash chip size = "); Serial.print(flashChipSize); Serial.println(" bytes");
  uint32_t flashChipSpeed = ESP.getFlashChipSpeed();
  Serial.print("ESP32 flash chip speed = "); Serial.print(flashChipSpeed); Serial.println(" Hz");
//  uint32_t getVcc = ESP.getVcc();
//  Serial.print("ESP8285 supply voltage = "); Serial.print(getVcc); Serial.println(" volts");

 /*    initWifi();

     Serial.println("Light sleep enabled");
     wifi_set_sleep_type(LIGHT_SLEEP_T); // Enable light sleep mode to save power
  
     server.on("/ESP8285Data", [](){

    // BME280 Data
    rawTemp =   readBME280Temperature();
    temperature_C = (float) BME280_compensate_T(rawTemp)/100.0; // temperature in Centigrade
    temperature_F = 9.*temperature_C/5. + 32.;
    rawPress =  readBME280Pressure();
    pressure = (float) BME280_compensate_P(rawPress)/25600.0; // Pressure in millibar
    altitude = 145366.45f*(1.0f - powf((pressure/1013.25f), 0.190284f));
    rawHumidity =  readBME280Humidity();
    humidity = (float) BME280_compensate_H(rawHumidity)/1024.0; // Humidity in %rH

    // VEML6040 Data
    getRGBWdata(RGBWData);
    redLight = (float)RGBWData[0]/96.0f;
    greenLight = (float)RGBWData[1]/74.0f;
    blueLight = (float)RGBWData[2]/56.0f;
    ambientLight = (float)RGBWData[1]*GSensitivity;

    // Battery Voltage
    VBAT = (1300.0/300.0) * (float)(analogRead(A0)) / 1024.0; // LiPo battery voltage in volts
 //   VBAT = (1100.0/100.0) * (float)(analogRead(A0)) / 1024.0; // 9V battery voltage in volts
    
    createHTML(temperature_C, temperature_F, pressure, altitude, humidity, redLight, greenLight, blueLight, ambientLight, VBAT);
    server.send(200, "text/html", webString);               // send to someone's browser when asked
    });
  
  server.begin();
  Serial.println("HTTP server started");

  Serial.println("LABEL,Timestamp,Pressure(mbar),Temperature(F),Humidity(rH%)");
  */
}
 

void loop()
{  
    rawTemp =   readBME280Temperature();
    temperature_C = (float) BME280_compensate_T(rawTemp)/100.0f;
    rawPress =  readBME280Pressure();
    pressure = (float) BME280_compensate_P(rawPress)/25600.0f; // Pressure in mbar
    rawHumidity =   readBME280Humidity();
    humidity = (float) BME280_compensate_H(rawHumidity)/1024.0f;
 
      Serial.println("BME280:");
      Serial.print("Altimeter temperature = "); 
      Serial.print( temperature_C, 2); 
      Serial.println(" C"); // temperature in degrees Celsius
      Serial.print("Altimeter temperature = "); 
      Serial.print(9.0f*temperature_C/5.0f + 32.0f, 2); 
      Serial.println(" F"); // temperature in degrees Fahrenheit
      Serial.print("Altimeter pressure = "); 
      Serial.print(pressure, 2); Serial.println(" mbar");// pressure in millibar

      Serial.print("DATA,");Serial.print("TIMER,"); 
      Serial.print(pressure); Serial.print(",");
      Serial.print(9.0f*temperature_C/5.0f + 32.0f, 2); Serial.print(",");
      Serial.print(humidity); Serial.println();

      altitude = 145366.45f*(1.0f - pow((pressure/1013.25f), 0.190284f));
      Serial.print("Altitude = "); 
      Serial.print(altitude, 2); 
      Serial.println(" feet");
      Serial.print("Altimeter humidity = "); 
      Serial.print(humidity, 1);  
      Serial.println(" %RH");// pressure in millibar
      Serial.println(" ");

      getRGBWdata(RGBWData);
      Serial.print("Red raw counts = ");   Serial.println(RGBWData[0]);
      Serial.print("Green raw counts = "); Serial.println(RGBWData[1]);
      Serial.print("Blue raw counts = ");  Serial.println(RGBWData[2]);
      Serial.print("White raw counts = "); Serial.println(RGBWData[3]);
      Serial.print("Inferred IR raw counts = "); Serial.println(RGBWData[3] - RGBWData[0] - RGBWData[1] - RGBWData[2]);
      Serial.println("  ");
 
      Serial.print("Red   light power density = "); Serial.print((float)RGBWData[0]/96.0f, 2); Serial.println(" microWatt/cm^2");
      Serial.print("Green light power density = "); Serial.print((float)RGBWData[1]/74.0f, 2); Serial.println(" microWatt/cm^2");
      Serial.print("Blue  light power density = "); Serial.print((float)RGBWData[2]/56.0f, 2); Serial.println(" microWatt/cm^2");
      Serial.println("  ");

      Serial.print("Ambient light intensity = "); Serial.print((float)RGBWData[1]*GSensitivity, 2); Serial.println(" lux");
      Serial.println("  ");

  // Empirical estimation of the correlated color temperature CCT:
  // see https://www.vishay.com/docs/84331/designingveml6040.pdf
      float temp = ( (float) (RGBWData[0] - RGBWData[2])/(float) RGBWData[1] );
      float CCT = 4278.6f*pow(temp, -1.2455f) + 0.5f;

      Serial.print("Correlated Color Temperature = "); Serial.print(CCT, 2); Serial.println(" Kelvin");
      Serial.println("  ");

      float VBAT = (100.0f/120.0f) * float(analogRead(34)) / 1024.0f;  // LiPo battery
      Serial.print("Battery Voltage = "); Serial.print(VBAT, 2); Serial.println(" V");    
  
      digitalWrite(myLed, HIGH); // blink blue led
      delay(100);
      digitalWrite(myLed, LOW);   

//      server.handleClient(); // serve data to web server site 
 
      delay(1000); // wait 1 seconds before refreshing data
}

//===================================================================================================================
//====== Set of useful function to access acceleration, gyroscope, magnetometer, and temperature data
//===================================================================================================================
/*void initWifi() {
  const char* ssid     = "NETGEAR16";
  const char* password = "braveroad553";
 // Connect to WiFi network
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("\n\r \n\rWorking to connect");

 // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("ESP8285 Environmental Data Server");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  }
*/
int32_t readBME280Temperature()
{
  uint8_t rawData[3];  // 20-bit pressure register data stored here
  readBytes(BME280_ADDRESS, BME280_TEMP_MSB, 3, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 16 | (uint32_t) rawData[1] << 8 | rawData[2]) >> 4);
}

int32_t readBME280Pressure()
{
  uint8_t rawData[3];  // 20-bit pressure register data stored here
  readBytes(BME280_ADDRESS, BME280_PRESS_MSB, 3, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 16 | (uint32_t) rawData[1] << 8 | rawData[2]) >> 4);
}

int32_t readBME280Humidity()
{
  uint8_t rawData[2];  // 16-bit humidity register data stored here
  readBytes(BME280_ADDRESS, BME280_HUM_MSB, 2, &rawData[0]);  
   return (uint32_t) (((uint32_t) rawData[0] << 24 | (uint32_t) rawData[1] << 16) ) >> 16;
}


void BME280Init()
{
  // Configure the BME280
  // Set H oversampling rate
  writeByte(BME280_ADDRESS, BME280_CTRL_HUM, 0x07 & Hosr);
  // Set T and P oversampling rates and sensor mode
  writeByte(BME280_ADDRESS, BME280_CTRL_MEAS, Tosr << 5 | Posr << 2 | Mode);
  // Set standby time interval in normal mode and bandwidth
  writeByte(BME280_ADDRESS, BME280_CONFIG, SBy << 5 | IIRFilter << 2);
  // Read and store calibration data
  uint8_t calib[26];
  readBytes(BME280_ADDRESS, BME280_CALIB00, 26, &calib[0]);
  dig_T1 = (uint16_t)(((uint16_t) calib[1] << 8) | calib[0]);
  dig_T2 = ( int16_t)((( int16_t) calib[3] << 8) | calib[2]);
  dig_T3 = ( int16_t)((( int16_t) calib[5] << 8) | calib[4]);
  dig_P1 = (uint16_t)(((uint16_t) calib[7] << 8) | calib[6]);
  dig_P2 = ( int16_t)((( int16_t) calib[9] << 8) | calib[8]);
  dig_P3 = ( int16_t)((( int16_t) calib[11] << 8) | calib[10]);
  dig_P4 = ( int16_t)((( int16_t) calib[13] << 8) | calib[12]);
  dig_P5 = ( int16_t)((( int16_t) calib[15] << 8) | calib[14]);
  dig_P6 = ( int16_t)((( int16_t) calib[17] << 8) | calib[16]);
  dig_P7 = ( int16_t)((( int16_t) calib[19] << 8) | calib[18]);
  dig_P8 = ( int16_t)((( int16_t) calib[21] << 8) | calib[20]);
  dig_P9 = ( int16_t)((( int16_t) calib[23] << 8) | calib[22]);
  dig_H1 = calib[25];
  readBytes(BME280_ADDRESS, BME280_CALIB26, 7, &calib[0]);
  dig_H2 = ( int16_t)((( int16_t) calib[1] << 8) | calib[0]);
  dig_H3 = calib[2];
  dig_H4 = ( int16_t)(((( int16_t) calib[3] << 8) | (0x0F & calib[4]) << 4) >> 4);
  dig_H5 = ( int16_t)(((( int16_t) calib[5] << 8) | (0xF0 & calib[4]) ) >> 4 );
  dig_H6 = calib[6];
}

// Returns temperature in DegC, resolution is 0.01 DegC. Output value of
// “5123” equals 51.23 DegC.
int32_t BME280_compensate_T(int32_t adc_T)
{
  int32_t var1, var2, T;
  var1 = ((((adc_T >> 3) - ((int32_t)dig_T1 << 1))) * ((int32_t)dig_T2)) >> 11;
  var2 = (((((adc_T >> 4) - ((int32_t)dig_T1)) * ((adc_T >> 4) - ((int32_t)dig_T1))) >> 12) * ((int32_t)dig_T3)) >> 14;
  t_fine = var1 + var2;
  T = (t_fine * 5 + 128) >> 8;
  return T;
}

// Returns pressure in Pa as unsigned 32 bit integer in Q24.8 format (24 integer bits and 8
//fractional bits).
//Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa
uint32_t BME280_compensate_P(int32_t adc_P)
{
  long long var1, var2, p;
  var1 = ((long long)t_fine) - 128000;
  var2 = var1 * var1 * (long long)dig_P6;
  var2 = var2 + ((var1*(long long)dig_P5)<<17);
  var2 = var2 + (((long long)dig_P4)<<35);
  var1 = ((var1 * var1 * (long long)dig_P3)>>8) + ((var1 * (long long)dig_P2)<<12);
  var1 = (((((long long)1)<<47)+var1))*((long long)dig_P1)>>33;
  if(var1 == 0)
  {
    return 0;
    // avoid exception caused by division by zero
  }
  p = 1048576 - adc_P;
  p = (((p<<31) - var2)*3125)/var1;
  var1 = (((long long)dig_P9) * (p>>13) * (p>>13)) >> 25;
  var2 = (((long long)dig_P8) * p)>> 19;
  p = ((p + var1 + var2) >> 8) + (((long long)dig_P7)<<4);
  return (uint32_t)p;
}

// Returns humidity in %RH as unsigned 32 bit integer in Q22.10 format (22integer and 10fractional bits).
// Output value of “47445”represents 47445/1024= 46.333%RH
uint32_t BME280_compensate_H(int32_t adc_H)
{
int32_t var;

var = (t_fine - ((int32_t)76800));
var = (((((adc_H << 14) - (((int32_t)dig_H4) << 20) - (((int32_t)dig_H5) * var)) +
((int32_t)16384)) >> 15) * (((((((var * ((int32_t)dig_H6)) >> 10) * (((var *
((int32_t)dig_H3)) >> 11) + ((int32_t)32768))) >> 10) + ((int32_t)2097152)) * ((int32_t)dig_H2) + 8192) >> 14));
var = (var - (((((var >> 15) * (var >> 15)) >> 7) * ((int32_t)dig_H1)) >> 4));
var = (var < 0 ? 0 : var); 
var = (var > 419430400 ? 419430400 : var);
return(uint32_t)(var >> 12);
}

uint16_t getRGBWdata(uint16_t * destination)
{
    for (int j = 0; j < 4; j++)
    {
    uint8_t rawData[2] = {0, 0};
    Wire.beginTransmission(VEML6040_ADDRESS);
    Wire.write(VEML6040_R_DATA + j);        // Command code for reading rgbw data channels in sequence
    Wire.endTransmission(false);  // Send the Tx buffer, but send a restart to keep connection alive

    Wire.requestFrom(VEML6040_ADDRESS, 2);  // Read two bytes from slave register address 
    uint8_t i = 0;
    while (Wire.available()) 
    {
        rawData[i++] = Wire.read();       // Put read results in the Rx buffer
    }     
    Wire.endTransmission();
    destination[j] = ((uint16_t) rawData[1] << 8) | rawData[0];
    }
 
}

void enableVEML6040()
{
  Wire.beginTransmission(VEML6040_ADDRESS);
  Wire.write(VEML6040_CONF); // Command code for configuration register
  Wire.write(IT << 4); // Bit 3 must be 0, bit 0 is 0 for run and 1 for shutdown, LS Byte
  Wire.write(0x00); // MS Byte
  Wire.endTransmission();
}
 
// simple function to scan for I2C devices on the bus
void I2Cscan() 
{
    // scan for i2c devices
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4) 
    {
      Serial.print("Unknown error at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.println(address,HEX);
    }    
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");
}


// I2C read/write functions for the BMP280 sensors

  void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
	Wire.beginTransmission(address);  // Initialize the Tx buffer
	Wire.write(subAddress);           // Put slave register address in Tx buffer
	Wire.write(data);                 // Put data in Tx buffer
	Wire.endTransmission();           // Send the Tx buffer
}

  uint8_t readByte(uint8_t address, uint8_t subAddress)
{
	uint8_t data; // `data` will store the register data	 
	Wire.beginTransmission(address);         // Initialize the Tx buffer
	Wire.write(subAddress);	                 // Put slave register address in Tx buffer
	Wire.endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
	Wire.requestFrom(address, 1);  // Read one byte from slave register address 
	data = Wire.read();                      // Fill Rx buffer with result
	return data;                             // Return data read from slave register
}

  void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
{  
	Wire.beginTransmission(address);   // Initialize the Tx buffer
	Wire.write(subAddress);            // Put slave register address in Tx buffer
	Wire.endTransmission(false);       // Send the Tx buffer, but send a restart to keep connection alive
	uint8_t i = 0;
  Wire.requestFrom(address, count);  // Read bytes from slave register address 
	while (Wire.available()) {
        dest[i++] = Wire.read(); }         // Put read results in the Rx buffer
}


================================================
FILE: Bosch/BNO055_MS5637.ino
================================================
/* BNO055_MS5637_ESP32 Basic Example Code
 by: Kris Winer
 date: December 14, 2016
 license: Beerware - Use this code however you'd like. If you 
 find it useful you can buy me a beer some time.
 
 Demonstrates basic BNO055 functionality including parameterizing the register addresses, 
 initializing the sensor, communicating with pressure sensor MS5637, 
 getting properly scaled accelerometer, gyroscope, and magnetometer data out. 
 
 Addition of 9 DoF sensor fusion using open source Madgwick and Mahony filter algorithms. 
 Can compare results to hardware 9 DoF sensor fusion carried out on the BNO055.
 Sketch runs on the 3.3 V ESP32.
 
 This sketch is intended specifically for the BNO055+MS5637 Add-On Shield.
 It uses SDA/SCL on pins 21/22, respectively, and it uses the Wire library.
 
 The Add-on shield can also be used as a stand-alone breakout board for any Arduino, Teensy, or 
 other microcontroller by closing the solder jumpers on the back of the board.
  
 The MS5637 is a simple but high resolution (24-bit) pressure sensor, which can be used in its high resolution
 mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 only 1 microAmp. The choice will depend on the application.
 
 All sensors communicate via I2C at 400 kHz or higher.
 SDA and SCL should have external pull-up resistors (to 3.3V).
 4K7 resistors are on the BNO055_MS5637 breakout board.
 
 Hardware setup:
 Breakout Board --------- ESP32
 3V3 ---------------------- 3.3V
 SDA -----------------------21
 SCL -----------------------22
 GND ---------------------- GND
 
 */
#include <Wire.h>   

// See MS5637-02BA03 Low Voltage Barometric Pressure Sensor Data Sheet
// http://www.meas-spec.com/product/pressure/MS5637-02BA03.aspx
//
#define MS5637_RESET      0x1E
#define MS5637_CONVERT_D1 0x40
#define MS5637_CONVERT_D2 0x50
#define MS5637_ADC_READ   0x00

// BNO055 Register Map
// http://ae-bst.resource.bosch.com/media/products/dokumente/bno055/BST_BNO055_DS000_10_Release.pdf
//
// BNO055 Page 0
#define BNO055_CHIP_ID          0x00    // should be 0xA0              
#define BNO055_ACC_ID           0x01    // should be 0xFB              
#define BNO055_MAG_ID           0x02    // should be 0x32              
#define BNO055_GYRO_ID          0x03    // should be 0x0F              
#define BNO055_SW_REV_ID_LSB    0x04                                                                          
#define BNO055_SW_REV_ID_MSB    0x05
#define BNO055_BL_REV_ID        0x06
#define BNO055_PAGE_ID          0x07
#define BNO055_ACC_DATA_X_LSB   0x08
#define BNO055_ACC_DATA_X_MSB   0x09
#define BNO055_ACC_DATA_Y_LSB   0x0A
#define BNO055_ACC_DATA_Y_MSB   0x0B
#define BNO055_ACC_DATA_Z_LSB   0x0C
#define BNO055_ACC_DATA_Z_MSB   0x0D
#define BNO055_MAG_DATA_X_LSB   0x0E
#define BNO055_MAG_DATA_X_MSB   0x0F
#define BNO055_MAG_DATA_Y_LSB   0x10
#define BNO055_MAG_DATA_Y_MSB   0x11
#define BNO055_MAG_DATA_Z_LSB   0x12
#define BNO055_MAG_DATA_Z_MSB   0x13
#define BNO055_GYR_DATA_X_LSB   0x14
#define BNO055_GYR_DATA_X_MSB   0x15
#define BNO055_GYR_DATA_Y_LSB   0x16
#define BNO055_GYR_DATA_Y_MSB   0x17
#define BNO055_GYR_DATA_Z_LSB   0x18
#define BNO055_GYR_DATA_Z_MSB   0x19
#define BNO055_EUL_HEADING_LSB  0x1A
#define BNO055_EUL_HEADING_MSB  0x1B
#define BNO055_EUL_ROLL_LSB     0x1C
#define BNO055_EUL_ROLL_MSB     0x1D
#define BNO055_EUL_PITCH_LSB    0x1E
#define BNO055_EUL_PITCH_MSB    0x1F
#define BNO055_QUA_DATA_W_LSB   0x20
#define BNO055_QUA_DATA_W_MSB   0x21
#define BNO055_QUA_DATA_X_LSB   0x22
#define BNO055_QUA_DATA_X_MSB   0x23
#define BNO055_QUA_DATA_Y_LSB   0x24
#define BNO055_QUA_DATA_Y_MSB   0x25
#define BNO055_QUA_DATA_Z_LSB   0x26
#define BNO055_QUA_DATA_Z_MSB   0x27
#define BNO055_LIA_DATA_X_LSB   0x28
#define BNO055_LIA_DATA_X_MSB   0x29
#define BNO055_LIA_DATA_Y_LSB   0x2A
#define BNO055_LIA_DATA_Y_MSB   0x2B
#define BNO055_LIA_DATA_Z_LSB   0x2C
#define BNO055_LIA_DATA_Z_MSB   0x2D
#define BNO055_GRV_DATA_X_LSB   0x2E
#define BNO055_GRV_DATA_X_MSB   0x2F
#define BNO055_GRV_DATA_Y_LSB   0x30
#define BNO055_GRV_DATA_Y_MSB   0x31
#define BNO055_GRV_DATA_Z_LSB   0x32
#define BNO055_GRV_DATA_Z_MSB   0x33
#define BNO055_TEMP             0x34
#define BNO055_CALIB_STAT       0x35
#define BNO055_ST_RESULT        0x36
#define BNO055_INT_STATUS       0x37
#define BNO055_SYS_CLK_STATUS   0x38
#define BNO055_SYS_STATUS       0x39
#define BNO055_SYS_ERR          0x3A
#define BNO055_UNIT_SEL         0x3B
#define BNO055_OPR_MODE         0x3D
#define BNO055_PWR_MODE         0x3E
#define BNO055_SYS_TRIGGER      0x3F
#define BNO055_TEMP_SOURCE      0x40
#define BNO055_AXIS_MAP_CONFIG  0x41
#define BNO055_AXIS_MAP_SIGN    0x42
#define BNO055_ACC_OFFSET_X_LSB 0x55
#define BNO055_ACC_OFFSET_X_MSB 0x56
#define BNO055_ACC_OFFSET_Y_LSB 0x57
#define BNO055_ACC_OFFSET_Y_MSB 0x58
#define BNO055_ACC_OFFSET_Z_LSB 0x59
#define BNO055_ACC_OFFSET_Z_MSB 0x5A
#define BNO055_MAG_OFFSET_X_LSB 0x5B
#define BNO055_MAG_OFFSET_X_MSB 0x5C
#define BNO055_MAG_OFFSET_Y_LSB 0x5D
#define BNO055_MAG_OFFSET_Y_MSB 0x5E
#define BNO055_MAG_OFFSET_Z_LSB 0x5F
#define BNO055_MAG_OFFSET_Z_MSB 0x60
#define BNO055_GYR_OFFSET_X_LSB 0x61
#define BNO055_GYR_OFFSET_X_MSB 0x62
#define BNO055_GYR_OFFSET_Y_LSB 0x63
#define BNO055_GYR_OFFSET_Y_MSB 0x64
#define BNO055_GYR_OFFSET_Z_LSB 0x65
#define BNO055_GYR_OFFSET_Z_MSB 0x66
#define BNO055_ACC_RADIUS_LSB   0x67
#define BNO055_ACC_RADIUS_MSB   0x68
#define BNO055_MAG_RADIUS_LSB   0x69
#define BNO055_MAG_RADIUS_MSB   0x6A
//
// BNO055 Page 1
#define BNO055_PAGE_ID          0x07
#define BNO055_ACC_CONFIG       0x08
#define BNO055_MAG_CONFIG       0x09
#define BNO055_GYRO_CONFIG_0    0x0A
#define BNO055_GYRO_CONFIG_1    0x0B
#define BNO055_ACC_SLEEP_CONFIG 0x0C
#define BNO055_GYR_SLEEP_CONFIG 0x0D
#define BNO055_INT_MSK          0x0F
#define BNO055_INT_EN           0x10
#define BNO055_ACC_AM_THRES     0x11
#define BNO055_ACC_INT_SETTINGS 0x12
#define BNO055_ACC_HG_DURATION  0x13
#define BNO055_ACC_HG_THRESH    0x14
#define BNO055_ACC_NM_THRESH    0x15
#define BNO055_ACC_NM_SET       0x16
#define BNO055_GYR_INT_SETTINGS 0x17
#define BNO055_GYR_HR_X_SET     0x18
#define BNO055_GYR_DUR_X        0x19
#define BNO055_GYR_HR_Y_SET     0x1A
#define BNO055_GYR_DUR_Y        0x1B
#define BNO055_GYR_HR_Z_SET     0x1C
#define BNO055_GYR_DUR_Z        0x1D
#define BNO055_GYR_AM_THRESH    0x1E
#define BNO055_GYR_AM_SET       0x1F

// Using the BNO055_MS5637 breakout board/Teensy 3.1 Add-On Shield, ADO is set to 1 by default 
#define ADO 1
#if ADO
#define BNO055_ADDRESS 0x29   //  Device address of BNO055 when ADO = 1
#define MS5637_ADDRESS 0x76   //  Address of MS5637 altimeter
#else
#define BNO055_ADDRESS 0x28   //  Device address of BNO055 when ADO = 0
#define MS5637_ADDRESS 0x76   //  Address of MS5637 altimeter
#endif  

#define SerialDebug true      // set to true to get Serial output for debugging

// Set initial input parameters
enum Ascale {  // ACC Full Scale
  AFS_2G = 0,
  AFS_4G,
  AFS_8G,
  AFS_18G
};

enum Abw { // ACC Bandwidth
  ABW_7_81Hz = 0,
  ABW_15_63Hz,
  ABW_31_25Hz,
  ABW_62_5Hz,
  ABW_125Hz,    
  ABW_250Hz,
  ABW_500Hz,     
  ABW_1000Hz,    //0x07
};

enum APwrMode { // ACC Pwr Mode
  NormalA = 0,  
  SuspendA,
  LowPower1A,
  StandbyA,        
  LowPower2A,
  DeepSuspendA
};

enum Gscale {  // gyro full scale
  GFS_2000DPS = 0,
  GFS_1000DPS,
  GFS_500DPS,
  GFS_250DPS,
  GFS_125DPS    // 0x04
};

enum GPwrMode { // GYR Pwr Mode
  NormalG = 0,
  FastPowerUpG,
  DeepSuspendedG,
  SuspendG,
  AdvancedPowerSaveG
};

enum Gbw { // gyro bandwidth
  GBW_523Hz = 0,
  GBW_230Hz,
  GBW_116Hz,
  GBW_47Hz,
  GBW_23Hz,
  GBW_12Hz,
  GBW_64Hz,
  GBW_32Hz
};

enum OPRMode {  // BNO-55 operation modes
  CONFIGMODE = 0x00,
// Sensor Mode
  ACCONLY,
  MAGONLY,
  GYROONLY,
  ACCMAG,
  ACCGYRO,
  MAGGYRO,
  AMG,            // 0x07
// Fusion Mode
  IMU,
  COMPASS,
  M4G,
  NDOF_FMC_OFF,
  NDOF            // 0x0C
};

enum PWRMode {
  Normalpwr = 0,   
  Lowpower,       
  Suspendpwr       
};

enum Modr {         // magnetometer output data rate  
  MODR_2Hz = 0,     
  MODR_6Hz,
  MODR_8Hz,
  MODR_10Hz,  
  MODR_15Hz,
  MODR_20Hz,
  MODR_25Hz, 
  MODR_30Hz 
};

enum MOpMode { // MAG Op Mode
  LowPower = 0,
  Regular,
  EnhancedRegular,
  HighAccuracy
};

enum MPwrMode { // MAG power mode
  Normal = 0,   
  Sleep,     
  Suspend,
  ForceMode  
};

#define ADC_256  0x00 // define pressure and temperature conversion rates
#define ADC_512  0x02
#define ADC_1024 0x04
#define ADC_2048 0x06
#define ADC_4096 0x08
#define ADC_8192 0x0A
#define ADC_D1   0x40
#define ADC_D2   0x50

// Specify sensor configuration
uint8_t OSR = ADC_8192;       // set pressure amd temperature oversample rate
//
uint8_t GPwrMode = NormalG;    // Gyro power mode
uint8_t Gscale = GFS_250DPS;  // Gyro full scale
//uint8_t Godr = GODR_250Hz;    // Gyro sample rate
uint8_t Gbw = GBW_23Hz;       // Gyro bandwidth
//
uint8_t Ascale = AFS_2G;      // Accel full scale
//uint8_t Aodr = AODR_250Hz;    // Accel sample rate
uint8_t APwrMode = NormalA;    // Accel power mode
uint8_t Abw = ABW_31_25Hz;    // Accel bandwidth, accel sample rate divided by ABW_divx
//
//uint8_t Mscale = MFS_4Gauss;  // Select magnetometer full-scale resolution
uint8_t MOpMode = Regular;    // Select magnetometer perfomance mode
uint8_t MPwrMode = Normal;    // Select magnetometer power mode
uint8_t Modr = MODR_10Hz;     // Select magnetometer ODR when in BNO055 bypass mode

uint8_t PWRMode = Normalpwr;    // Select BNO055 power mode
uint8_t OPRMode = NDOF;       // specify operation mode for sensors
uint8_t status;               // BNO055 data status register
float aRes, gRes, mRes;       // scale resolutions per LSB for the sensors
  
// Pin definitions
int intPin = 14;  // These can be changed, 2 and 3 are the Arduinos ext int pins
int myLed = 5;

uint16_t Pcal[8];         // calibration constants from MS5637 PROM registers
unsigned char nCRC;       // calculated check sum to ensure PROM integrity
uint32_t D1 = 0, D2 = 0;  // raw MS5637 pressure and temperature data
double dT, OFFSET, SENS, TT2, OFFSET2, SENS2;  // First order and second order corrections for raw S5637 temperature and pressure data
int16_t accelCount[3];  // Stores the 16-bit signed accelerometer sensor output
int16_t gyroCount[3];   // Stores the 16-bit signed gyro sensor output
int16_t magCount[3];    // Stores the 16-bit signed magnetometer sensor output
int16_t quatCount[4];   // Stores the 16-bit signed quaternion output
int16_t EulCount[3];    // Stores the 16-bit signed Euler angle output
int16_t LIACount[3];    // Stores the 16-bit signed linear acceleration output
int16_t GRVCount[3];    // Stores the 16-bit signed gravity vector output
float gyroBias[3] = {0, 0, 0}, accelBias[3] = {0, 0, 0}, magBias[3] = {0, 0, 0};  // Bias corrections for gyro, accelerometer, and magnetometer
int16_t tempGCount, tempMCount;      // temperature raw count output of mag and gyro
float   Gtemperature, Mtemperature;  // Stores the BNO055 gyro and LIS3MDL mag internal chip temperatures in degrees Celsius
double Temperature, Pressure;        // stores MS5637 pressures sensor pressure and temperature

// global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System)
float GyroMeasError = PI * (40.0f / 180.0f);   // gyroscope measurement error in rads/s (start at 40 deg/s)
float GyroMeasDrift = PI * (0.0f  / 180.0f);   // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)
// There is a tradeoff in the beta parameter between accuracy and response speed.
// In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy.
// However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion.
// Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car!
// By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec
// I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense; 
// the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy. 
// In any case, this is the free parameter in the Madgwick filtering and fusion scheme.
float beta = sqrt(3.0f / 4.0f) * GyroMeasError;   // compute beta
float zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift;   // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value
#define Kp 2.0f * 5.0f // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral
#define Ki 0.0f

uint32_t delt_t = 0, count = 0, sumCount = 0;  // used to control display output rate
float pitch, yaw, roll;
float Pitch, Yaw, Roll;
float LIAx, LIAy, LIAz, GRVx, GRVy, GRVz;
float deltat = 0.0f, sum = 0.0f;          // integration interval for both filter schemes
uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval
uint32_t Now = 0;                         // used to calculate integration interval

float ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values 
float q[4] = {1.0f, 0.0f, 0.0f, 0.0f};    // vector to hold quaternion
float quat[4] = {1.0f, 0.0f, 0.0f, 0.0f};    // vector to hold quaternion
float eInt[3] = {0.0f, 0.0f, 0.0f};       // vector to hold integral error for Mahony method


void setup()
{
  Wire.begin(21, 22, 400000); // (SDA, SCL) (21, 22) are default on ESP32, 400 kHz I2C bus speed
  delay(5000);
  Serial.begin(115200);
  
  // Set up the interrupt pin, its set as active high, push-pull
  pinMode(intPin, INPUT);
  pinMode(myLed, OUTPUT);
  digitalWrite(myLed, HIGH);

  I2Cscan(); // check for I2C devices on the bus8
  
  // Read the WHO_AM_I register, this is a good test of communication
  Serial.println("BNO055 9-axis motion sensor...");
  byte c = readByte(BNO055_ADDRESS, BNO055_CHIP_ID);  // Read WHO_AM_I register for BNO055
  Serial.print("BNO055 Address = 0x"); Serial.println(BNO055_ADDRESS, HEX);
  Serial.print("BNO055 WHO_AM_I = 0x"); Serial.println(BNO055_CHIP_ID, HEX);
  Serial.print("BNO055 "); Serial.print("I AM "); Serial.print(c, HEX); Serial.println(" I should be 0xA0");  

  delay(1000); 
   
    // Read the WHO_AM_I register of the accelerometer, this is a good test of communication
  byte d = readByte(BNO055_ADDRESS, BNO055_ACC_ID);  // Read WHO_AM_I register for accelerometer
  Serial.print("BNO055 ACC "); Serial.print("I AM "); Serial.print(d, HEX); Serial.println(" I should be 0xFB");  

  delay(1000); 
  
  // Read the WHO_AM_I register of the magnetometer, this is a good test of communication
  byte e = readByte(BNO055_ADDRESS, BNO055_MAG_ID);  // Read WHO_AM_I register for magnetometer
  Serial.print("BNO055 MAG "); Serial.print("I AM "); Serial.print(e, HEX); Serial.println(" I should be 0x32");

  delay(1000);   
  
  // Read the WHO_AM_I register of the gyroscope, this is a good test of communication
  byte f = readByte(BNO055_ADDRESS, BNO055_GYRO_ID);  // Read WHO_AM_I register for LIS3MDL
  Serial.print("BNO055 GYRO "); Serial.print("I AM "); Serial.print(f, HEX); Serial.println(" I should be 0x0F");

  delay(1000); 

  if (c == 0xA0) // BNO055 WHO_AM_I should always be 0xA0
  {  
    Serial.println("BNO055 is online...");
    
    // Check software revision ID
    byte swlsb = readByte(BNO055_ADDRESS, BNO055_SW_REV_ID_LSB);
    byte swmsb = readByte(BNO055_ADDRESS, BNO055_SW_REV_ID_MSB);
    Serial.print("BNO055 SW Revision ID: "); Serial.print(swmsb, HEX); Serial.print("."); Serial.println(swlsb, HEX); 
    Serial.println("Should be 03.04");
    
    // Check bootloader version
    byte blid = readByte(BNO055_ADDRESS, BNO055_BL_REV_ID);
    Serial.print("BNO055 bootloader Version: "); Serial.println(blid); 
    
    // Check self-test results
    byte selftest = readByte(BNO055_ADDRESS, BNO055_ST_RESULT);
    
    if(selftest & 0x01) {
      Serial.println("accelerometer passed selftest"); 
    } else {
      Serial.println("accelerometer failed selftest"); 
    }
    if(selftest & 0x02) {
      Serial.println("magnetometer passed selftest"); 
    } else {
      Serial.println("magnetometer failed selftest"); 
    }  
    if(selftest & 0x04) {
      Serial.println("gyroscope passed selftest"); 
    } else {
      Serial.println("gyroscope failed selftest"); 
    }      
    if(selftest & 0x08) {
      Serial.println("MCU passed selftest"); 
    } else {
      Serial.println("MCU failed selftest"); 
    }
      
    delay(1000);
  
  // Reset the MS5637 pressure sensor
  MS5637Reset();
  delay(100);
  Serial.println("MS5637 pressure sensor reset...");
  // Read PROM data from MS5637 pressure sensor
  MS5637PromRead(Pcal);
  Serial.println("PROM data read:");
  Serial.print("C0 = "); Serial.println(Pcal[0]);
  unsigned char refCRC = Pcal[0] >> 12;
  Serial.print("C1 = "); Serial.println(Pcal[1]);
  Serial.print("C2 = "); Serial.println(Pcal[2]);
  Serial.print("C3 = "); Serial.println(Pcal[3]);
  Serial.print("C4 = "); Serial.println(Pcal[4]);
  Serial.print("C5 = "); Serial.println(Pcal[5]);
  Serial.print("C6 = "); Serial.println(Pcal[6]);
  
  nCRC = MS5637checkCRC(Pcal);  //calculate checksum to ensure integrity of MS5637 calibration data
  Serial.print("Checksum = "); Serial.print(nCRC); Serial.print(" , should be "); Serial.println(refCRC);  
  
  delay(1000);  
 
  accelgyroCalBNO055(accelBias, gyroBias);
  
  Serial.println("Average accelerometer bias (mg) = "); Serial.println(accelBias[0]); Serial.println(accelBias[1]); Serial.println(accelBias[2]);
  Serial.println("Average gyro bias (dps) = "); Serial.println(gyroBias[0]); Serial.println(gyroBias[1]); Serial.println(gyroBias[2]);
  
  delay(1000); 
  
  magCalBNO055(magBias);
  
  Serial.println("Average magnetometer bias (mG) = "); Serial.println(magBias[0]); Serial.println(magBias[1]); Serial.println(magBias[2]);
 
  delay(1000); 
  
  // Check calibration status of the sensors
  uint8_t calstat = readByte(BNO055_ADDRESS, BNO055_CALIB_STAT);
  Serial.println("Not calibrated = 0, fully calibrated = 3");
  Serial.print("System calibration status "); Serial.println( (0xC0 & calstat) >> 6);
  Serial.print("Gyro   calibration status "); Serial.println( (0x30 & calstat) >> 4);
  Serial.print("Accel  calibration status "); Serial.println( (0x0C & calstat) >> 2);
  Serial.print("Mag    calibration status "); Serial.println( (0x03 & calstat) >> 0);
  
  initBNO055(); // Initialize the BNO055
  Serial.println("BNO055 initialized for sensor mode...."); // Initialize BNO055 for sensor read 
 
  }
  else
  {
    Serial.print("Could not connect to BNO055: 0x");
    Serial.println(c, HEX);
    while(1) ; // Loop forever if communication doesn't happen
  }
}

void loop()
{  
    readAccelData(accelCount);  // Read the x/y/z adc values
    // Now we'll calculate the accleration value into actual mg's
    ax = (float)accelCount[0]; // - accelBias[0];  // subtract off calculated accel bias
    ay = (float)accelCount[1]; // - accelBias[1];
    az = (float)accelCount[2]; // - accelBias[2]; 

    readGyroData(gyroCount);  // Read the x/y/z adc values
    // Calculate the gyro value into actual degrees per second
    gx = (float)gyroCount[0]/16.; // - gyroBias[0];  // subtract off calculated gyro bias
    gy = (float)gyroCount[1]/16.; // - gyroBias[1];  
    gz = (float)gyroCount[2]/16.; // - gyroBias[2];   

    readMagData(magCount);  // Read the x/y/z adc values   
    // Calculate the magnetometer values in milliGauss
    mx = (float)magCount[0]/1.6; // - magBias[0];  // get actual magnetometer value in mGauss 
    my = (float)magCount[1]/1.6; // - magBias[1];  
    mz = (float)magCount[2]/1.6; // - magBias[2];   
    
    readQuatData(quatCount);  // Read the x/y/z adc values   
    // Calculate the quaternion values  
    quat[0] = (float)(quatCount[0])/16384.;    
    quat[1] = (float)(quatCount[1])/16384.;  
    quat[2] = (float)(quatCount[2])/16384.;   
    quat[3] = (float)(quatCount[3])/16384.;   
    
    readEulData(EulCount);  // Read the x/y/z adc values   
    // Calculate the Euler angles values in degrees
    Yaw = (float)EulCount[0]/16.;  
    Roll = (float)EulCount[1]/16.;  
    Pitch = (float)EulCount[2]/16.;   
 
    readLIAData(LIACount);  // Read the x/y/z adc values   
    // Calculate the linear acceleration (sans gravity) values in mg
    LIAx = (float)LIACount[0];  
    LIAy = (float)LIACount[1];  
    LIAz = (float)LIACount[2];   

    readGRVData(GRVCount);  // Read the x/y/z adc values   
    // Calculate the linear acceleration (sans gravity) values in mg
    GRVx = (float)GRVCount[0];  
    GRVy = (float)GRVCount[1];  
    GRVz = (float)GRVCount[2];   
    
  
  Now = micros();
  deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
  lastUpdate = Now;
  
  sum += deltat; // sum for averaging filter update rate
  sumCount++;
  
  // Sensors x, y, and z-axes  for the three sensor: accel, gyro, and magnetometer are all aligned, so
  // no allowance for any orientation mismatch in feeding the output to the quaternion filter is required.
  // For the BNO055, the sensor forward is along the x-axis just like
  // in the LSM9DS0 and MPU9250 sensors. This rotation can be modified to allow any convenient orientation convention.
  // This is ok by aircraft orientation standards!  
  // Pass gyro rate as rad/s
  MadgwickQuaternionUpdate(ax, -ay, -az, gx*PI/180.0f, -gy*PI/180.0f, -gz*PI/180.0f,  -my,  -mx, -mz);
//  MahonyQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, mx, my, mz);
    
    // Serial print and/or display at 0.5 s rate independent of data rates
    delt_t = millis() - count;
    if (delt_t > 1000) { // update LCD once per half-second independent of read rate
    
  if (SerialDebug) {
  // check BNO-055 error status at 2 Hz rate
    uint8_t sysstat = readByte(BNO055_ADDRESS, BNO055_SYS_STATUS); // check system status
    Serial.print("System Status = 0x"); Serial.println(sysstat, HEX);
    if(sysstat == 0x05) Serial.println("Sensor fusion algorithm running");
    if(sysstat == 0x06) Serial.println("Sensor fusion not algorithm running");
    
    if(sysstat == 0x01) {
      uint8_t syserr = readByte(BNO055_ADDRESS, BNO055_SYS_ERR);
      if(syserr == 0x01) Serial.println("Peripheral initialization error");
      if(syserr == 0x02) Serial.println("System initialization error");
      if(syserr == 0x03) Serial.println("Self test result failed");
      if(syserr == 0x04) Serial.println("Register map value out of range");
      if(syserr == 0x05) Serial.println("Register map address out of range");
      if(syserr == 0x06) Serial.println("Register map write error");
      if(syserr == 0x07) Serial.println("BNO low power mode no available for selected operation mode");
      if(syserr == 0x08) Serial.println("Accelerometer power mode not available");
      if(syserr == 0x09) Serial.println("Fusion algorithm configuration error");
      if(syserr == 0x0A) Serial.println("Sensor configuration error");    
    }  
  }

    if(SerialDebug) {
    Serial.print("ax = "); Serial.print((int)ax);  
    Serial.print(" ay = "); Serial.print((int)ay); 
    Serial.print(" az = "); Serial.print((int)az); Serial.println(" mg");
    Serial.print("gx = "); Serial.print( gx, 2); 
    Serial.print(" gy = "); Serial.print( gy, 2); 
    Serial.print(" gz = "); Serial.print( gz, 2); Serial.println(" deg/s");
    Serial.print("mx = "); Serial.print( (int)mx ); 
    Serial.print(" my = "); Serial.print( (int)my ); 
    Serial.print(" mz = "); Serial.print( (int)mz ); Serial.println(" mG");
    
    Serial.print("qx = "); Serial.print(q[0]);
    Serial.print(" qy = "); Serial.print(q[1]); 
    Serial.print(" qz = "); Serial.print(q[2]); 
    Serial.print(" qw = "); Serial.println(q[3]); 
    Serial.print("quatw = "); Serial.print(quat[0]);
    Serial.print(" quatx = "); Serial.print(quat[1]); 
    Serial.print(" quaty = "); Serial.print(quat[2]); 
    Serial.print(" quatz = "); Serial.println(quat[3]); 
    } 
    
    if(SerialDebug) {
      tempGCount = readGyroTempData();  // Read the gyro adc values
    Gtemperature = (float) tempGCount; // Gyro chip temperature in degrees Centigrade
   // Print gyro die temperature in degrees Centigrade      
    Serial.print("Gyro temperature is ");  Serial.print(Gtemperature, 1);  Serial.println(" degrees C"); // Print T values to tenths of a degree C
    }
    
    D1 = MS5637Read(ADC_D1, OSR);  // get raw pressure value
    D2 = MS5637Read(ADC_D2, OSR);  // get raw temperature value
    
    dT = D2 - Pcal[5]*pow(2,8);    // calculate temperature difference from reference
    OFFSET = Pcal[2]*pow(2, 17) + dT*Pcal[4]/pow(2,6);
    SENS = Pcal[1]*pow(2,16) + dT*Pcal[3]/pow(2,7);
 
    Temperature = (2000 + (dT*Pcal[6])/pow(2, 23))/100;           // First-order Temperature in degrees Centigrade
//
// Second order corrections
    if(Temperature > 20) 
    {
      TT2 = 5*dT*dT/pow(2, 38); // correction for high temperatures
      OFFSET2 = 0;
      SENS2 = 0;
    }
    if(Temperature < 20)                   // correction for low temperature
    {
      TT2      = 3*dT*dT/pow(2, 33); 
      OFFSET2 = 61*(100*Temperature - 2000)*(100*Temperature - 2000)/16;
      SENS2   = 29*(100*Temperature - 2000)*(100*Temperature - 2000)/16;
    } 
    if(Temperature < -15)                      // correction for very low temperature
    {
      OFFSET2 = OFFSET2 + 17*(100*Temperature + 1500)*(100*Temperature + 1500);
      SENS2 = SENS2 + 9*(100*Temperature + 1500)*(100*Temperature + 1500);
    }
 // End of second order corrections
 //
     Temperature = Temperature - TT2/100;
     OFFSET = OFFSET - OFFSET2;
     SENS = SENS - SENS2;
 
     Pressure = (((D1*SENS)/pow(2, 21) - OFFSET)/pow(2, 15))/100;  // Pressure in mbar or Pa/100
  
    float altitude = 145366.45*(1. - pow((Pressure/1013.25), 0.190284));
   
    if(SerialDebug) {
    Serial.print("Digital temperature value = "); Serial.print( (float)Temperature, 2); Serial.println(" C"); // temperature in degrees Celsius
    Serial.print("Digital temperature value = "); Serial.print(9.*(float) Temperature/5. + 32., 2); Serial.println(" F"); // temperature in degrees Fahrenheit
    Serial.print("Digital pressure value = "); Serial.print((float) Pressure, 2);  Serial.println(" mbar");// pressure in millibar
    Serial.print("Altitude = "); Serial.print(altitude, 2); Serial.println(" feet");
    }
    
  // Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation.
  // In this coordinate system, the positive z-axis is down toward Earth. 
  // Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise.
  // Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative.
  // Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll.
  // These arise from the definition of the homogeneous rotation matrix constructed from quaternions.
  // Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be
  // applied in the correct order which for this configuration is yaw, pitch, and then roll.
  // For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links.
    yaw   = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]);   
    pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));
    roll  = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]);
    pitch *= 180.0f / PI;
    yaw   *= 180.0f / PI; 
 //   yaw   -= 13.8f; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04
    roll  *= 180.0f / PI;
     
    if(SerialDebug) {
    Serial.print("Software Yaw, Pitch, Roll: ");
    Serial.print(yaw, 2);
    Serial.print(", ");
    Serial.print(pitch, 2);
    Serial.print(", ");
    Serial.println(roll, 2);
    
    Serial.print("Hardware Yaw, Pitch, Roll: ");
    Serial.print(Yaw, 2);
    Serial.print(", ");
    Serial.print(Pitch, 2);
    Serial.print(", ");
    Serial.println(Roll, 2);
 
    Serial.print("Hardware x, y, z linear acceleration: ");
    Serial.print(LIAx, 2);
    Serial.print(", ");
    Serial.print(LIAy, 2);
    Serial.print(", ");
    Serial.println(LIAz, 2);

    Serial.print("Hardware x, y, z gravity vector: ");
    Serial.print(GRVx, 2);
    Serial.print(", ");
    Serial.print(GRVy, 2);
    Serial.print(", ");
    Serial.println(GRVz, 2);
 
    
    Serial.print("rate = "); Serial.print((float)sumCount/sum, 2); Serial.println(" Hz");
    }

     Serial.print(millis()/1000);Serial.print(",");
     Serial.print(yaw, 2); Serial.print(",");Serial.print(pitch, 2); Serial.print(",");Serial.print(roll, 2); Serial.print(",");
     Serial.print(Yaw, 2); Serial.print(",");Serial.print(Pitch, 2); Serial.print(",");Serial.print(Roll, 2); Serial.println(",");
  
    digitalWrite(myLed, !digitalRead(myLed));
    count = millis(); 
    sumCount = 0;
    sum = 0;    
    }

}

//===================================================================================================================
//====== Set of useful function to access acceleration. gyroscope, magnetometer, and temperature data
//===================================================================================================================

void readAccelData(int16_t * destination)
{
  uint8_t rawData[6];  // x/y/z accel register data stored here
  readBytes(BNO055_ADDRESS, BNO055_ACC_DATA_X_LSB, 6, &rawData[0]);  // Read the six raw data registers into data array
  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;      // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; 
}


void readGyroData(int16_t * destination)
{
  uint8_t rawData[6];  // x/y/z gyro register data stored here
  readBytes(BNO055_ADDRESS, BNO055_GYR_DATA_X_LSB, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array
  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; 
}

int8_t readGyroTempData()
{
  return readByte(BNO055_ADDRESS, BNO055_TEMP);  // Read the two raw data registers sequentially into data array 
}

void readMagData(int16_t * destination)
{
  uint8_t rawData[6];  // x/y/z gyro register data stored here
  readBytes(BNO055_ADDRESS, BNO055_MAG_DATA_X_LSB, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array
  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
}

void readQuatData(int16_t * destination)
{
  uint8_t rawData[8];  // x/y/z gyro register data stored here
  readBytes(BNO055_ADDRESS, BNO055_QUA_DATA_W_LSB, 8, &rawData[0]);  // Read the six raw data registers sequentially into data array
  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
  destination[3] = ((int16_t)rawData[7] << 8) | rawData[6] ;
}

void readEulData(int16_t * destination)
{
  uint8_t rawData[6];  // x/y/z gyro register data stored here
  readBytes(BNO055_ADDRESS, BNO055_EUL_HEADING_LSB, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array
  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
}

void readLIAData(int16_t * destination)
{
  uint8_t rawData[6];  // x/y/z gyro register data stored here
  readBytes(BNO055_ADDRESS, BNO055_LIA_DATA_X_LSB, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array
  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
}

void readGRVData(int16_t * destination)
{
  uint8_t rawData[6];  // x/y/z gyro register data stored here
  readBytes(BNO055_ADDRESS, BNO055_GRV_DATA_X_LSB, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array
  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
}

void initBNO055() {
   // Select BNO055 config mode
   writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, CONFIGMODE );
   delay(25);
   // Select page 1 to configure sensors
   writeByte(BNO055_ADDRESS, BNO055_PAGE_ID, 0x01);
   // Configure ACC
   writeByte(BNO055_ADDRESS, BNO055_ACC_CONFIG, APwrMode << 5 | Abw << 2 | Ascale );
   // Configure GYR
   writeByte(BNO055_ADDRESS, BNO055_GYRO_CONFIG_0, Gbw << 3 | Gscale );
   writeByte(BNO055_ADDRESS, BNO055_GYRO_CONFIG_1, GPwrMode);
   // Configure MAG
   writeByte(BNO055_ADDRESS, BNO055_MAG_CONFIG, MPwrMode << 5 | MOpMode << 3 | Modr );
   
   // Select page 0 to read sensors
   writeByte(BNO055_ADDRESS, BNO055_PAGE_ID, 0x00);

   // Select BNO055 gyro temperature source 
   writeByte(BNO055_ADDRESS, BNO055_TEMP_SOURCE, 0x01 );

   // Select BNO055 sensor units (temperature in degrees C, rate in dps, accel in mg)
   writeByte(BNO055_ADDRESS, BNO055_UNIT_SEL, 0x01 );
   
   // Select BNO055 system power mode
   writeByte(BNO055_ADDRESS, BNO055_PWR_MODE, PWRMode );
 
   // Select BNO055 system operation mode
   writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, OPRMode );
   delay(25);
   
}

void accelgyroCalBNO055(float * dest1, float * dest2) 
{
  uint8_t data[6]; // data array to hold accelerometer and gyro x, y, z, data
  uint16_t ii = 0, sample_count = 0;
  int32_t gyro_bias[3]  = {0, 0, 0}, accel_bias[3] = {0, 0, 0};
 
  Serial.println("Accel/Gyro Calibration: Put device on a level surface and keep motionless! Wait......");
  delay(4000);
  
  // Select page 0 to read sensors
   writeByte(BNO055_ADDRESS, BNO055_PAGE_ID, 0x00);
   // Select BNO055 system operation mode as AMG for calibration
   writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, CONFIGMODE );
   delay(25);
   writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, AMG);
   
 // In NDF fusion mode, accel full scale is at +/- 4g, ODR is 62.5 Hz, set it the same here
   writeByte(BNO055_ADDRESS, BNO055_ACC_CONFIG, APwrMode << 5 | Abw << 2 | AFS_4G );
   sample_count = 256;
   for(ii = 0; ii < sample_count; ii++) {
    int16_t accel_temp[3] = {0, 0, 0};
    readBytes(BNO055_ADDRESS, BNO055_ACC_DATA_X_LSB, 6, &data[0]);  // Read the six raw data registers into data array
    accel_temp[0] = (int16_t) (((int16_t)data[1] << 8) | data[0]) ; // Form signed 16-bit integer for each sample in FIFO
    accel_temp[1] = (int16_t) (((int16_t)data[3] << 8) | data[2]) ;
    accel_temp[2] = (int16_t) (((int16_t)data[5] << 8) | data[4]) ;
    accel_bias[0]  += (int32_t) accel_temp[0];
    accel_bias[1]  += (int32_t) accel_temp[1];
    accel_bias[2]  += (int32_t) accel_temp[2];
    delay(20);  // at 62.5 Hz ODR, new accel data is available every 16 ms
   }
    accel_bias[0]  /= (int32_t) sample_count;  // get average accel bias in mg
    accel_bias[1]  /= (int32_t) sample_count;
    accel_bias[2]  /= (int32_t) sample_count;
    
  if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) 1000;}  // Remove gravity from the z-axis accelerometer bias calculation
  else {accel_bias[2] += (int32_t) 1000;}

    dest1[0] = (float) accel_bias[0];  // save accel biases in mg for use in main program
    dest1[1] = (float) accel_bias[1];  // accel data is 1 LSB/mg
    dest1[2] = (float) accel_bias[2];          

 // In NDF fusion mode, gyro full scale is at +/- 2000 dps, ODR is 32 Hz
   writeByte(BNO055_ADDRESS, BNO055_GYRO_CONFIG_0, Gbw << 3 | GFS_2000DPS );
   writeByte(BNO055_ADDRESS, BNO055_GYRO_CONFIG_1, GPwrMode);
   for(ii = 0; ii < sample_count; ii++) {
    int16_t gyro_temp[3] = {0, 0, 0};
    readBytes(BNO055_ADDRESS, BNO055_GYR_DATA_X_LSB, 6, &data[0]);  // Read the six raw data registers into data array
    gyro_temp[0] = (int16_t) (((int16_t)data[1] << 8) | data[0]) ;  // Form signed 16-bit integer for each sample in FIFO
    gyro_temp[1] = (int16_t) (((int16_t)data[3] << 8) | data[2]) ;
    gyro_temp[2] = (int16_t) (((int16_t)data[5] << 8) | data[4]) ;
    gyro_bias[0]  += (int32_t) gyro_temp[0];
    gyro_bias[1]  += (int32_t) gyro_temp[1];
    gyro_bias[2]  += (int32_t) gyro_temp[2];
    delay(35);  // at 32 Hz ODR, new gyro data available every 31 ms
   }
    gyro_bias[0]  /= (int32_t) sample_count;  // get average gyro bias in counts
    gyro_bias[1]  /= (int32_t) sample_count;
    gyro_bias[2]  /= (int32_t) sample_count;
 
    dest2[0] = (float) gyro_bias[0]/16.;  // save gyro biases in dps for use in main program
    dest2[1] = (float) gyro_bias[1]/16.;  // gyro data is 16 LSB/dps
    dest2[2] = (float) gyro_bias[2]/16.;          

  // Return to config mode to write accelerometer biases in offset register
  // This offset register is only used while in fusion mode when accelerometer full-scale is +/- 4g
  writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, CONFIGMODE );
  delay(25);
  
  //write biases to accelerometer offset registers ad 16 LSB/dps
  writeByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_X_LSB, (int16_t)accel_bias[0] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_X_MSB, ((int16_t)accel_bias[0] >> 8) & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Y_LSB, (int16_t)accel_bias[1] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Y_MSB, ((int16_t)accel_bias[1] >> 8) & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Z_LSB, (int16_t)accel_bias[2] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Z_MSB, ((int16_t)accel_bias[2] >> 8) & 0xFF);
  
  // Check that offsets were properly written to offset registers
//  Serial.println("Average accelerometer bias = "); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_X_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_X_LSB))); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Y_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Y_LSB))); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Z_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_ACC_OFFSET_Z_LSB)));

   //write biases to gyro offset registers
  writeByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_X_LSB, (int16_t)gyro_bias[0] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_X_MSB, ((int16_t)gyro_bias[0] >> 8) & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Y_LSB, (int16_t)gyro_bias[1] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Y_MSB, ((int16_t)gyro_bias[1] >> 8) & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Z_LSB, (int16_t)gyro_bias[2] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Z_MSB, ((int16_t)gyro_bias[2] >> 8) & 0xFF);
  
  // Select BNO055 system operation mode
  writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, OPRMode );

 // Check that offsets were properly written to offset registers
//  Serial.println("Average gyro bias = "); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_X_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_X_LSB))); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Y_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Y_LSB))); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Z_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_GYR_OFFSET_Z_LSB)));

   Serial.println("Accel/Gyro Calibration done!");
}

void magCalBNO055(float * dest1) 
{
  uint8_t data[6]; // data array to hold mag x, y, z, data
  uint16_t ii = 0, sample_count = 0;
  int32_t mag_bias[3] = {0, 0, 0};
  int16_t mag_max[3] = {0x8000, 0x8000, 0x8000}, mag_min[3] = {0x7FFF, 0x7FFF, 0x7FFF};
 
  Serial.println("Mag Calibration: Wave device in a figure eight until done!");
  delay(4000);
  
  // Select page 0 to read sensors
   writeByte(BNO055_ADDRESS, BNO055_PAGE_ID, 0x00);
   // Select BNO055 system operation mode as AMG for calibration
   writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, CONFIGMODE );
   delay(25);
   writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, AMG );

 // In NDF fusion mode, mag data is in 16 LSB/microTesla, ODR is 20 Hz in forced mode
   sample_count = 256;
   for(ii = 0; ii < sample_count; ii++) {
    int16_t mag_temp[3] = {0, 0, 0};
    readBytes(BNO055_ADDRESS, BNO055_MAG_DATA_X_LSB, 6, &data[0]);  // Read the six raw data registers into data array
    mag_temp[0] = (int16_t) (((int16_t)data[1] << 8) | data[0]) ;   // Form signed 16-bit integer for each sample in FIFO
    mag_temp[1] = (int16_t) (((int16_t)data[3] << 8) | data[2]) ;
    mag_temp[2] = (int16_t) (((int16_t)data[5] << 8) | data[4]) ;
    for (int jj = 0; jj < 3; jj++) {
      if (ii == 0) {
        mag_max[jj] = mag_temp[jj]; // Offsets may be large enough that mag_temp[i] may not be bipolar! 
        mag_min[jj] = mag_temp[jj]; // This prevents max or min being pinned to 0 if the values are unipolar...
      } else {
        if(mag_temp[jj] > mag_max[jj]) mag_max[jj] = mag_temp[jj];
        if(mag_temp[jj] < mag_min[jj]) mag_min[jj] = mag_temp[jj];
      }
    }
    delay(105);  // at 10 Hz ODR, new mag data is available every 100 ms
   }

 //   Serial.println("mag x min/max:"); Serial.println(mag_max[0]); Serial.println(mag_min[0]);
 //   Serial.println("mag y min/max:"); Serial.println(mag_max[1]); Serial.println(mag_min[1]);
 //   Serial.println("mag z min/max:"); Serial.println(mag_max[2]); Serial.println(mag_min[2]);

    mag_bias[0]  = (mag_max[0] + mag_min[0])/2;  // get average x mag bias in counts
    mag_bias[1]  = (mag_max[1] + mag_min[1])/2;  // get average y mag bias in counts
    mag_bias[2]  = (mag_max[2] + mag_min[2])/2;  // get average z mag bias in counts
    
    dest1[0] = (float) mag_bias[0] / 1.6;  // save mag biases in mG for use in main program
    dest1[1] = (float) mag_bias[1] / 1.6;  // mag data is 1.6 LSB/mg
    dest1[2] = (float) mag_bias[2] / 1.6;          

  // Return to config mode to write mag biases in offset register
  // This offset register is only used while in fusion mode when magnetometer sensitivity is 16 LSB/microTesla
  writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, CONFIGMODE );
  delay(25);
  
  //write biases to magnetometer offset registers as 16 LSB/microTesla
  writeByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_X_LSB, (int16_t)mag_bias[0] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_X_MSB, ((int16_t)mag_bias[0] >> 8) & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Y_LSB, (int16_t)mag_bias[1] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Y_MSB, ((int16_t)mag_bias[1] >> 8) & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Z_LSB, (int16_t)mag_bias[2] & 0xFF);
  writeByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Z_MSB, ((int16_t)mag_bias[2] >> 8) & 0xFF);
 
  // Check that offsets were properly written to offset registers
//  Serial.println("Average magnetometer bias = "); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_X_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_X_LSB))); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Y_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Y_LSB))); 
//  Serial.println((int16_t)((int16_t)readByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Z_MSB) << 8 | readByte(BNO055_ADDRESS, BNO055_MAG_OFFSET_Z_LSB)));
  // Select BNO055 system operation mode
  writeByte(BNO055_ADDRESS, BNO055_OPR_MODE, OPRMode );

   Serial.println("Mag Calibration done!");
}


// I2C communication with the MS5637 is a little different from that with the BNO055 and most other sensors
// For the MS5637, we write commands, and the MS5637 sends data in response, rather than directly reading
// MS5637 registers

        void MS5637Reset()
        {
        Wire.beginTransmission(MS5637_ADDRESS);  // Initialize the Tx buffer
	Wire.write(MS5637_RESET);                // Put reset command in Tx buffer
	Wire.endTransmission();                  // Send the Tx buffer
        }
        
        void MS5637PromRead(uint16_t * destination)
        {
        uint8_t data[2] = {0,0};
        for (uint8_t ii = 0; ii < 7; ii++) {
          Wire.beginTransmission(MS5637_ADDRESS);  // Initialize the Tx buffer
          Wire.write(0xA0 | ii << 1);              // Put PROM address in Tx buffer
          Wire.endTransmission(false);        // Send the Tx buffer, but send a restart to keep connection alive
//          Wire.endTransmission(false);        // Send the Tx buffer, but send a restart to keep connection alive
	  uint8_t i = 0;
          Wire.requestFrom(MS5637_ADDRESS, 2);   // Read two bytes from slave PROM address 
	  while (Wire.available()) {
          data[i++] = Wire.read(); }               // Put read results in the Rx buffer
          destination[ii] = (uint16_t) (((uint16_t) data[0] << 8) | data[1]); // construct PROM data for return to main program
        }
        }

        uint32_t MS5637Read(uint8_t CMD, uint8_t OSR)  // temperature data read
        {
        uint8_t data[3] = {0,0,0};
        Wire.beginTransmission(MS5637_ADDRESS);  // Initialize the Tx buffer
        Wire.write(CMD | OSR);                  // Put pressure conversion command in Tx buffer
        Wire.endTransmission(false);        // Send the Tx buffer, but send a restart to keep connection alive
//        Wire.endTransmission(false);        // Send the Tx buffer, but send a restart to keep connection alive
        
        switch (OSR)
        {
          case ADC_256: delay(1); break;  // delay for conversion to complete
          case ADC_512: delay(3); break;
          case ADC_1024: delay(4); break;
          case ADC_2048: delay(6); break;
          case ADC_4096: delay(10); break;
          case ADC_8192: delay(20); break;
        }
       
        Wire.beginTransmission(MS5637_ADDRESS);  // Initialize the Tx buffer
        Wire.write(0x00);                        // Put ADC read command in Tx buffer
//        Wire.endTransmission(false);        // Send the Tx buffer, but send a restart to keep connection alive
        Wire.endTransmission(false);        // Send the Tx buffer, but send a restart to keep connection alive
	uint8_t i = 0;
        Wire.requestFrom(MS5637_ADDRESS, 3);     // Read three bytes from slave PROM address 
	while (Wire.available()) {
        data[i++] = Wire.read(); }               // Put read results in the Rx buffer
        return (uint32_t) (((uint32_t) data[0] << 16) | (uint32_t) data[1] << 8 | data[2]); // construct PROM data for return to main program
        }



unsigned char MS5637checkCRC(uint16_t * n_prom)  // calculate checksum from PROM register contents
{
  int cnt;
  unsigned int n_rem = 0;
  unsigned char n_bit;
  
  n_prom[0] = ((n_prom[0]) & 0x0FFF);  // replace CRC byte by 0 for checksum calculation
  n_prom[7] = 0;
  for(cnt = 0; cnt < 16; cnt++)
  {
    if(cnt%2==1) n_rem ^= (unsigned short) ((n_prom[cnt>>1]) & 0x00FF);
    else         n_rem ^= (unsigned short)  (n_prom[cnt>>1]>>8);
    for(n_bit = 8; n_bit > 0; n_bit--)
    {
        if(n_rem & 0x8000)    n_rem = (n_rem<<1) ^ 0x3000;
        else                  n_rem = (n_rem<<1);
    }
  }
  n_rem = ((n_rem>>12) & 0x000F);
  return (n_rem ^ 0x00);
}

// I2C scan function

void I2Cscan()
{
// scan for i2c devices
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4) 
    {
      Serial.print("Unknown error at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.println(address,HEX);
    }    
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");
    
}

// I2C read/write functions for the BNO055 sensor

  void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
	Wire.beginTransmission(address);  // Initialize the Tx buffer
	Wire.write(subAddress);           // Put slave register address in Tx buffer
	Wire.write(data);                 // Put data in Tx buffer
	Wire.endTransmission();           // Send the Tx buffer
}

  uint8_t readByte(uint8_t address, uint8_t subAddress)
{
	uint8_t data; // `data` will store the register data	 
	Wire.beginTransmission(address);         // Initialize the Tx buffer
	Wire.write(subAddress);	                 // Put slave register address in Tx buffer
	Wire.endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
	Wire.requestFrom(address, 1);            // Read one byte from slave register address 
	data = Wire.read();                      // Fill Rx buffer with result
	return data;                             // Return data read from slave register
}

  void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
{  
	Wire.beginTransmission(address);   // Initialize the Tx buffer
	Wire.write(subAddress);            // Put slave register address in Tx buffer
	Wire.endTransmission(false);       // Send the Tx buffer, but send a restart to keep connection alive
	uint8_t i = 0;
  Wire.requestFrom(address, count);  // Read bytes from slave register address 
	while (Wire.available()) {
        dest[i++] = Wire.read(); }         // Put read results in the Rx buffer
}


================================================
FILE: Bosch/readme.md
================================================
Collection of sketches for Bosch sensors. I use [this](https://www.tindie.com/products/onehorse/bno-055-9-axis-motion-sensor-with-hardware-fusion/) for the BNO055 breakout board.

![](https://d3s5r33r268y59.cloudfront.net/44691/products/thumbs/2016-08-06T00:24:08.896Z-BNO055.top.jpg.855x570_q85_pad_rcrop.jpg)


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/BME280.cpp
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 This sketch uses SDA/SCL on pins 42/43 (back pads), respectively, and it uses the Dragonfly STM32L476RE Breakout Board.
 The BME280 is a simple but high resolution pressure/humidity/temperature sensor, which can be used in its high resolution
 mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 only 1 microAmp. The choice will depend on the application.
 
 Library may be used freely and without limit with attribution.
 
*/
 
#include "BME280.h"
#include "I2Cdev.h"

#define USBSerial Serial

BME280::BME280(I2Cdev* i2c_bus)
{
  _i2c_bus = i2c_bus;
}


uint8_t BME280::getChipID()
{
  uint8_t c = _i2c_bus->readByte(BME280_ADDRESS, BME280_ID);
  return c;
}

void BME280::resetBME280()
{
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_RESET, 0xB6);
}


int32_t BME280::readBME280Temperature()
{
  uint8_t rawData[3];  // 20-bit temperature register data stored here
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_TEMP_MSB, 3, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 16 | (uint32_t) rawData[1] << 8 | rawData[2]) >> 4);
}


int32_t BME280::readBME280Pressure()
{
  uint8_t rawData[3];  // 20-bit pressure register data stored here
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_PRESS_MSB, 3, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 16 | (uint32_t) rawData[1] << 8 | rawData[2]) >> 4);
}


int32_t BME280::BME280::readBME280Humidity()
{
  uint8_t rawData[2];  // 16-bit humiditye register data stored here
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_HUM_MSB, 2, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 24 | (uint32_t) rawData[1] << 16) ) >> 16;
}


void BME280::BME280forced()
{
    uint8_t temp = _i2c_bus->readByte(BME280_ADDRESS, BME280_CTRL_MEAS);
    _i2c_bus->writeByte(BME280_ADDRESS, BME280_CTRL_MEAS, temp | Forced);
 
    while( (_i2c_bus->readByte(BME280_ADDRESS, BME280_STATUS)) & 0x10) { } // wait for conversion byte to clear
}


void BME280::BME280Init(uint8_t Posr, uint8_t Hosr, uint8_t Tosr, uint8_t Mode, uint8_t IIRFilter, uint8_t SBy)
{
  // Configure the BME280
  // Set H oversampling rate
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_CTRL_HUM, 0x07 & Hosr);
  // Set T and P oversampling rates and sensor mode
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_CTRL_MEAS, Tosr << 5 | Posr << 2 | Mode);
  // Set standby time interval in normal mode and bandwidth
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_CONFIG, SBy << 5 | IIRFilter << 2);
  
  uint8_t calib[26];
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_CALIB00, 26, &calib[0]);
  _dig_T1 = (uint16_t)(((uint16_t) calib[1] << 8) | calib[0]);
  _dig_T2 = ( int16_t)((( int16_t) calib[3] << 8) | calib[2]);
  _dig_T3 = ( int16_t)((( int16_t) calib[5] << 8) | calib[4]);
  _dig_P1 = (uint16_t)(((uint16_t) calib[7] << 8) | calib[6]);
  _dig_P2 = ( int16_t)((( int16_t) calib[9] << 8) | calib[8]);
  _dig_P3 = ( int16_t)((( int16_t) calib[11] << 8) | calib[10]);
  _dig_P4 = ( int16_t)((( int16_t) calib[13] << 8) | calib[12]);
  _dig_P5 = ( int16_t)((( int16_t) calib[15] << 8) | calib[14]);
  _dig_P6 = ( int16_t)((( int16_t) calib[17] << 8) | calib[16]);
  _dig_P7 = ( int16_t)((( int16_t) calib[19] << 8) | calib[18]);
  _dig_P8 = ( int16_t)((( int16_t) calib[21] << 8) | calib[20]);
  _dig_P9 = ( int16_t)((( int16_t) calib[23] << 8) | calib[22]);
  _dig_H1 = calib[25];
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_CALIB26, 7, &calib[0]);
  _dig_H2 = ( int16_t)((( int16_t) calib[1] << 8) | calib[0]);
  _dig_H3 = calib[2];
  _dig_H4 = ( int16_t)(((( int16_t) calib[3] << 8) | (0x0F & calib[4]) << 4) >> 4);
  _dig_H5 = ( int16_t)(((( int16_t) calib[5] << 8) | (0xF0 & calib[4]) ) >> 4 );
  _dig_H6 = calib[6];
  Serial.println("Calibration coeficients:");
  Serial.print("_dig_T1 ="); 
  Serial.println(_dig_T1);
  Serial.print("_dig_T2 ="); 
  Serial.println(_dig_T2);
  Serial.print("_dig_T3 ="); 
  Serial.println(_dig_T3);
  Serial.print("_dig_P1 ="); 
  Serial.println(_dig_P1);
  Serial.print("_dig_P2 ="); 
  Serial.println(_dig_P2);
  Serial.print("_dig_P3 ="); 
  Serial.println(_dig_P3);
  Serial.print("_dig_P4 ="); 
  Serial.println(_dig_P4);
  Serial.print("_dig_P5 ="); 
  Serial.println(_dig_P5);
  Serial.print("_dig_P6 ="); 
  Serial.println(_dig_P6);
  Serial.print("_dig_P7 ="); 
  Serial.println(_dig_P7);
  Serial.print("_dig_P8 ="); 
  Serial.println(_dig_P8);
  Serial.print("_dig_P9 ="); 
  Serial.println(_dig_P9);
  Serial.print("_dig_H1 ="); 
  Serial.println(_dig_H1);
  Serial.print("_dig_H2 ="); 
  Serial.println(_dig_H2);
  Serial.print("_dig_H3 ="); 
  Serial.println(_dig_H3);
  Serial.print("_dig_H4 ="); 
  Serial.println(_dig_H4);
  Serial.print("_dig_H5 ="); 
  Serial.println(_dig_H5);
  Serial.print("_dig_H6 ="); 
  Serial.println(_dig_H6);
}


// Returns temperature in DegC, resolution is 0.01 DegC. Output value of
// “5123” equals 51.23 DegC.
int32_t BME280::BME280_compensate_T(int32_t adc_T)
{
  int32_t var1, var2, T;
  var1 = ((((adc_T >> 3) - ((int32_t)_dig_T1 << 1))) * ((int32_t)_dig_T2)) >> 11;
  var2 = (((((adc_T >> 4) - ((int32_t)_dig_T1)) * ((adc_T >> 4) - ((int32_t)_dig_T1))) >> 12) * ((int32_t)_dig_T3)) >> 14;
  _t_fine = var1 + var2;
  T = (_t_fine * 5 + 128) >> 8;
  return T;
}


// Returns pressure in Pa as unsigned 32 bit integer in Q24.8 format (24 integer bits and 8
//fractional bits).
//Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa
uint32_t BME280::BME280_compensate_P(int32_t adc_P)
{
  long long var1, var2, p;
  var1 = ((long long)_t_fine) - 128000;
  var2 = var1 * var1 * (long long)_dig_P6;
  var2 = var2 + ((var1*(long long)_dig_P5)<<17);
  var2 = var2 + (((long long)_dig_P4)<<35);
  var1 = ((var1 * var1 * (long long)_dig_P3)>>8) + ((var1 * (long long)_dig_P2)<<12);
  var1 = (((((long long)1)<<47)+var1))*((long long)_dig_P1)>>33;
  if(var1 == 0)
  {
    return 0;
    // avoid exception caused by division by zero
  }
  p = 1048576 - adc_P;
  p = (((p<<31) - var2)*3125)/var1;
  var1 = (((long long)_dig_P9) * (p>>13) * (p>>13)) >> 25;
  var2 = (((long long)_dig_P8) * p)>> 19;
  p = ((p + var1 + var2) >> 8) + (((long long)_dig_P7)<<4);
  return (uint32_t)p;
}


// Returns humidity in %RH as unsigned 32 bit integer in Q22.10 format (22integer and 10fractional bits).
// Output value of “47445”represents 47445/1024= 46.333%RH
uint32_t BME280::BME280_compensate_H(int32_t adc_H)
{
int32_t var;

var = (_t_fine - ((int32_t)76800));
var = (((((adc_H << 14) - (((int32_t)_dig_H4) << 20) - (((int32_t)_dig_H5) * var)) +
((int32_t)16384)) >> 15) * (((((((var * ((int32_t)_dig_H6)) >> 10) * (((var *
((int32_t)_dig_H3)) >> 11) + ((int32_t)32768))) >> 10) + ((int32_t)2097152)) * ((int32_t)_dig_H2) + 8192) >> 14));
var = (var - (((((var >> 15) * (var >> 15)) >> 7) * ((int32_t)_dig_H1)) >> 4));
var = (var < 0 ? 0 : var); 
var = (var > 419430400 ? 419430400 : var);
return(uint32_t)(var >> 12);
}


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/BME280.h
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 This sketch uses SDA/SCL on pins 42/43 (back pads), respectively, and it uses the Dragonfly STM32L476RE Breakout Board.
 The BME280 is a simple but high resolution pressure/humidity/temperature sensor, which can be used in its high resolution
 mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 only 1 microAmp. The choice will depend on the application.
 
 Library may be used freely and without limit with attribution.
 
*/
  
#ifndef BME280_h
#define BME280_h

#include "Arduino.h"
#include "I2CDev.h"
#include <Wire.h>

/* BME280 registers
*  http://www.mouser.com/ds/2/783/BST-BME280_DS001-11-844833.pdf
*/
#define BME280_HUM_LSB    0xFE
#define BME280_HUM_MSB    0xFD
#define BME280_TEMP_XLSB  0xFC
#define BME280_TEMP_LSB   0xFB
#define BME280_TEMP_MSB   0xFA
#define BME280_PRESS_XLSB 0xF9
#define BME280_PRESS_LSB  0xF8
#define BME280_PRESS_MSB  0xF7
#define BME280_CONFIG     0xF5
#define BME280_CTRL_MEAS  0xF4
#define BME280_STATUS     0xF3
#define BME280_CTRL_HUM   0xF2
#define BME280_RESET      0xE0
#define BME280_ID         0xD0  // should be 0x60
#define BME280_CALIB00    0x88
#define BME280_CALIB26    0xE1

#define BME280_ADDRESS           0x76   // Address of BMP280 altimeter when ADO = 0


#define  P_OSR_01 0x01
#define  P_OSR_02 0x02
#define  P_OSR_04 0x03
#define  P_OSR_08 0x04
#define  P_OSR_16 0x05

#define  H_OSR_01 0x01
#define  H_OSR_02 0x02
#define  H_OSR_04 0x03
#define  H_OSR_08 0x04
#define  H_OSR_16 0x05

#define  T_OSR_01 0x01
#define  T_OSR_02 0x02
#define  T_OSR_04 0x03
#define  T_OSR_08 0x04
#define  T_OSR_16 0x05

#define  full       0x00
#define  BW0_223ODR 0x01
#define  BW0_092ODR 0x02
#define  BW0_042ODR 0x03
#define  BW0_021ODR 0x04  

#define  BME280Sleep 0x00
#define  Forced      0x01
#define  Forced2     0x02
#define  Normal      0x03

#define  t_00_5ms 0x00
#define  t_62_5ms 0x01
#define  t_125ms  0x02
#define  t_250ms  0x03
#define  t_500ms  0x04
#define  t_1000ms 0x05
#define  t_10ms   0x06
#define  t_20ms   0x07 


class BME280
{
  public: 
  BME280(I2Cdev* i2c_bus);
  uint8_t getChipID();
  void resetBME280();
  int32_t readBME280Temperature();
  int32_t readBME280Pressure();
  int32_t readBME280Humidity();
  void BME280forced();
  void BME280Init(uint8_t Posr, uint8_t Hosr, uint8_t Tosr, uint8_t Mode, uint8_t IIRFilter, uint8_t SBy);
  int32_t  BME280_compensate_T(int32_t adc_T);
  uint32_t BME280_compensate_P(int32_t adc_P);
  uint32_t BME280_compensate_H(int32_t adc_H);
  
  private:
  uint8_t  _dig_H1, _dig_H3, _dig_H6;
  uint16_t _dig_T1, _dig_P1, _dig_H4, _dig_H5;
  int16_t  _dig_T2, _dig_T3, _dig_P2, _dig_P3, _dig_P4, _dig_P5, _dig_P6, _dig_P7, _dig_P8, _dig_P9, _dig_H2;
  int32_t  _t_fine;
  I2Cdev* _i2c_bus;
  };

#endif


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/CCS811.cpp
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 *  The AMS CCS811 is an air quality sensor that provides equivalent CO2 and volatile organic measurements from direct
 *  I2C register reads as well as current and voltage (effective resistance of the sensing element). Gas sensors, including 
 *  this MEMs gas sensor in the CCS811 measure resistance of a substrate that changes when exposed to inert gasses and 
 *  volatile organic compounds. Changed in concentration vary exponentially with the changes in resistance. The CCS811
 *  has an embedded ASIC calibrated against most common indoor pollutants that returns a good estimate of
 *  equivalent CO2 concentration in parts per million (400 - 8192 range) and volatile organic componds in parts per billion (0 - 1187).
 *  The sensor is quite sensitive to breath and other human emissions.
 *  
 *  Library may be used freely and without limit with attribution.
 *  
 */
#include "CCS811.h"
#include "I2Cdev.h"

#define USBSerial Serial

CCS811::CCS811(I2Cdev* i2c_bus)
{
  _i2c_bus = i2c_bus;   
}


uint8_t CCS811::getChipID()
{
 byte e = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_ID);  // Read WHO_AM_I register for CCS8110
 return e;
}


void CCS811::checkCCS811Status() 
{
   // Check CCS811 status
  uint8_t status = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_STATUS);
  Serial.print("status = 0X"); Serial.println(status, HEX);
  if(status & 0x80) {Serial.println("Firmware is in application mode. CCS811 is ready!");}
  else { Serial.println("Firmware is in boot mode!");}
  
  if(status & 0x10) {Serial.println("Valid application firmware loaded!");}
  else { Serial.println("No application firmware is loaded!");}

  if(status & 0x08) {Serial.println("New data available!");}
  else { Serial.println("No new data available!");}

  if(status & 0x01) {Serial.println("Error detected!");
        uint8_t error = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_ERROR_ID);
        if(error & 0x01) Serial.println("CCS811 received invalid I2C write request!");
        if(error & 0x02) Serial.println("CCS811 received invalid I2C read request!");
        if(error & 0x04) Serial.println("CCS811 received unsupported mode request!");
        if(error & 0x08) Serial.println("Sensor resistance measurement at maximum range!");
        if(error & 0x10) Serial.println("Heater current is not in range!");
        if(error & 0x20) Serial.println("Heater voltage is not being applied correctly!");
  }
  else { Serial.println("No error detected!");
  }
  
  Serial.println(" ");
  
  }


  void CCS811::CCS811init(uint8_t AQRate)
  {
    // initialize CCS811 and check version and status
  byte HWVersion = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_HW_VERSION);
  Serial.print("CCS811 Hardware Version = 0x"); Serial.println(HWVersion, HEX); 

  uint8_t FWBootVersion[2] = {0, 0}, FWAppVersion[2] = {0,0};
  _i2c_bus->readBytes(CCS811_ADDRESS, CCS811_FW_BOOT_VERSION, 2, &FWBootVersion[0]);
  Serial.println("CCS811 Firmware Boot Version: "); 
  Serial.print("Major = "); Serial.println((FWBootVersion[0] & 0xF0) >> 4); 
  Serial.print("Minor = "); Serial.println(FWBootVersion[0] & 0x04); 
  Serial.print("Trivial = "); Serial.println(FWBootVersion[1]); 
  
  _i2c_bus->readBytes(CCS811_ADDRESS, CCS811_FW_APP_VERSION, 2, &FWAppVersion[0]);
  Serial.println("CCS811 Firmware App Version: "); 
  Serial.print("Major = "); Serial.println((FWAppVersion[0] & 0xF0) >> 4); 
  Serial.print("Minor = "); Serial.println(FWAppVersion[0] & 0x04); 
  Serial.print("Trivial = "); Serial.println(FWAppVersion[1]); 

  // Check CCS811 status
  checkCCS811Status();
  _i2c_bus->writeReg(CCS811_ADDRESS, CCS811_APP_START);
  delay(100);
  checkCCS811Status();

  // set CCS811 measurement mode
  _i2c_bus->writeByte(CCS811_ADDRESS, CCS811_MEAS_MODE, AQRate << 4 | 0x08); // pulsed heating mode, enable interrupt
  uint8_t measmode = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_MEAS_MODE);
  Serial.print("Confirm measurement mode = 0x"); Serial.println(measmode, HEX);
  }


  void CCS811::compensateCCS811(int32_t compHumidity, int32_t compTemp)
  {
      // Update CCS811 humidity and temperature compensation
      uint8_t temp[5] = {0, 0, 0, 0, 0};
      temp[0] = CCS811_ENV_DATA;
      temp[1] = ((compHumidity % 1024) / 100) > 7 ? (compHumidity/1024 + 1)<<1 : (compHumidity/1024)<<1;
      temp[2] = 0;
      if(((compHumidity % 1024) / 100) > 2 && (((compHumidity % 1024) / 100) < 8))
      {
       temp[1] |= 1;
      }

      compTemp += 2500;
      temp[3] = ((compTemp % 100) / 100) > 7 ? (compTemp/100 + 1)<<1 : (compTemp/100)<<1;
      temp[4] = 0;
      if(((compTemp % 100) / 100) > 2 && (((compTemp % 100) / 100) < 8))
      {
       temp[3] |= 1;
      }

//      Wire.transfer(CCS811_ADDRESS, &temp[0], 5, NULL, 0);
     _i2c_bus->writeBytes(CCS811_ADDRESS, CCS811_ENV_DATA, 4, &temp[1]);
  }

   void CCS811::readCCS811Data(uint8_t * destination)
   {
      uint8_t rawData[8] = {0, 0, 0, 0, 0, 0, 0, 0};
      uint8_t status = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_STATUS);
      
      if(status & 0x01) { // check for errors
        uint8_t error = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_ERROR_ID);
        if(error & 0x01) Serial.println("CCS811 received invalid I2C write request!");
        if(error & 0x02) Serial.println("CCS811 received invalid I2C read request!");
        if(error & 0x04) Serial.println("CCS811 received unsupported mode request!");
        if(error & 0x08) Serial.println("Sensor resistance measurement at maximum range!");
        if(error & 0x10) Serial.println("Heater current is not in range!");
        if(error & 0x20) Serial.println("Heater voltage is not being applied correctly!");
      }

      _i2c_bus->readBytes(CCS811_ADDRESS, CCS811_ALG_RESULT_DATA, 8, &rawData[0]);

   for(int ii = 0; ii < 8; ii++)
   {
    destination[ii] = rawData[ii];
   }
   
   }


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/CCS811.h
================================================
#ifndef CCS811_h
#define CCS811_h

#include "Arduino.h"
#include "Wire.h"
#include "I2Cdev.h"

/* CCS811 Registers
http://www.mouser.com/ds/2/588/CCS811_DS000459_3-00-1098798.pdf
*/
#define CCS811_STATUS             0x00
#define CCS811_MEAS_MODE          0x01
#define CCS811_ALG_RESULT_DATA    0x02
#define CCS811_RAW_DATA           0x03
#define CCS811_ENV_DATA           0x05
#define CCS811_NTC                0x06
#define CCS811_THRESHOLDS         0x10
#define CCS811_BASELINE           0x11
#define CCS811_HW_ID              0x20  // WHO_AM_I should be 0x81
#define CCS811_ID                 0x20  // WHO_AM_I should be 0x1X
#define CCS811_HW_VERSION         0x21  
#define CCS811_FW_BOOT_VERSION    0x23
#define CCS811_FW_APP_VERSION     0x24
#define CCS811_ERROR_ID           0xE0
#define CCS811_APP_START          0xF4
#define CCS811_SW_RESET           0xFF

#define CCS811_ADDRESS            0x5A   // Address of the CCS811 Air Quality Sensor

#define  dt_idle  0x00
#define  dt_1sec  0x01
#define  dt_10sec 0x02
#define  dt_60sec 0x03

class CCS811
{
  public: 
  CCS811(I2Cdev* i2c_bus);
  void checkCCS811Status();
  void CCS811init(uint8_t AQRate);
  uint8_t getChipID();
  void compensateCCS811(int32_t compHumidity, int32_t compTemp);
  void readCCS811Data(uint8_t * destination);
  
  private:
  I2Cdev* _i2c_bus;
};


#endif


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/CCS811_BME280_ESP32C3Mini_WebServer.ino
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 *  The AMS CCS811 is an air quality sensor that provides equivalent CO2 and volatile organic measurements from direct
 *  I2C register reads as well as current and voltage (effective resistance of the sensing element). Gas sensors, including 
 *  this MEMs gas sensor in the CCS811 measure resistance of a substrate that changes when exposed to inert gasses and 
 *  volatile organic compounds. Changed in concentration vary exponentially with the changes in resistance. The CCS811
 *  has an embedded ASIC calibrated against most common indoor pollutants that returns a good estimate of
 *  equivalent CO2 concentration in parts per million (400 - 8192 range) and volatile organic componds in parts per billion (0 - 1187).
 *  The sensor is quite sensitive to breath and other human emissions.
 *  
 *  This sketch uses default SDA/SCL pins on the Ladybug development board.
 *  The BME280 is a simple but high resolution pressure/humidity/temperature sensor, which can be used in its high resolution
 *  mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 *  only 1 microAmp. The choice will depend on the application.
 
    Library may be used freely and without limit with attribution.
 
  */
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <driver/adc.h>
#include "USB.h"
#include "BME280.h"
#include "CCS811.h"
#include "I2Cdev.h"

#define Serial USBSerial

const char* ssid = "XXXXXXXXX";
const char* password = "XXXXXXXXXXXX";

WebServer server(80);

String webString="";     // String to display

void handleRoot() {
  server.send(200, "text/plain", "Hello from the environmental monitroing station ESP32!");
  delay(100);
}

  String createHTML(float var1, float var2, float var3, float var4, float var5, float var6, float var7, float var8) {
   webString = "<html><head><meta http-equiv=\"Refresh\" content=\"5\"></head><body><UL>"

  +String("<LI>Temperature = ")+String(var1)+String(" C</LI>") 
  +String("<LI>Temperature = ")+String(var2)+String(" F</LI>") 
  +String("<LI>Pressure = ")+String(var3)+String(" milliBar</LI>") 
  +String("<LI>Altitude = ")+String(var4)+String(" feet</LI>") 
  +String("<LI>Humidity = ")+String(var5)+String(" %RH</LI>") 
  +String("<LI>eCO2 = ")+String(var6)+String(" ppm</LI>") 
  +String("<LI>TVOC = ")+String(var7)+String(" ppb</LI>") 
  +String("<LI>Battery Voltage = ")+String(var8)+String(" V</LI>") 
     
  +"</UL></body></html>" ;
   return webString;
  }
  
void handleNotFound() {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

/* create an ESP32 hardware timer */
hw_timer_t * timer = NULL;
volatile bool alarmFlag = false;

void IRAM_ATTR onTimer(){
  alarmFlag = true;
}

#define I2C_BUS          Wire               // Define the I2C bus (Wire instance) you wish to use

I2Cdev                   i2c_0(&I2C_BUS);   // Instantiate the I2Cdev object and point to the desired I2C bus

#define SerialDebug true  // set to true to get Serial output for debugging
#define       myLed    2 // green led
const uint8_t myBat =  1;

float VBat = 0.0f;
uint32_t chipId = 0;

// BME280 definitions
/* Specify BME280 configuration
 *  Choices are:
 P_OSR_01, P_OSR_02, P_OSR_04, P_OSR_08, P_OSR_16 // pressure oversampling
 H_OSR_01, H_OSR_02, H_OSR_04, H_OSR_08, H_OSR_16 // humidity oversampling
 T_OSR_01, T_OSR_02, T_OSR_04, T_OSR_08, T_OSR_16 // temperature oversampling
 full, BW0_223ODR,BW0_092ODR, BW0_042ODR, BW0_021ODR // bandwidth at 0.021 x sample rate
 BME280Sleep, forced,, forced2, normal //operation modes
 t_00_5ms = 0, t_62_5ms, t_125ms, t_250ms, t_500ms, t_1000ms, t_10ms, t_20ms // determines sample rate
 */
uint8_t Posr = P_OSR_01, Hosr = H_OSR_01, Tosr = T_OSR_01, Mode = BME280Sleep, IIRFilter = full, SBy = t_1000ms;     // set pressure amd temperature output data rate

float Temperature, Pressure, Humidity;              // stores BME280 pressures sensor pressure and temperature
int32_t rawPress, rawTemp, rawHumidity, compTemp;   // pressure and temperature raw count output for BME280
uint32_t compHumidity, compPress;                   // variables to hold raw BME280 humidity value

float temperature_C, temperature_F, pressure, humidity, altitude; // Scaled output of the BME280

BME280 BME280(&i2c_0); // instantiate BME280 class


// CCS811 definitions
#define CCS811_intPin  4
#define CCS811_wakePin 7

/* Specify CCS811 sensor parameters
 *  Choices are   dt_idle , dt_1sec, dt_10sec, dt_60sec
 */
uint8_t AQRate = dt_10sec;  // set the sample rate
uint8_t rawData[8] = {0, 0, 0, 0, 0, 0, 0, 0};  // array to hold the raw data
uint16_t eCO2 = 0, TVOC = 0;
uint8_t Current = 0;
float Voltage = 0.0f;

volatile bool newCCS811Data  = true; // boolean flag for interrupt

CCS811 CCS811(&i2c_0); // instantiate CCS811 class


void setup()
{
  Serial.begin(115200);
  delay(4000);
  Serial.println("Serial enabled!");

  pinMode(myLed, OUTPUT);
  digitalWrite(myLed, LOW); // start with led on, active LOW

  for(int i=0; i<17; i=i+8) {
    chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xFF) << i;
  }

  Serial.printf("ESP32 Chip model = %s Rev %d\n", ESP.getChipModel(), ESP.getChipRevision());
  Serial.printf("This chip has %d cores\n", ESP.getChipCores());
  Serial.print("Chip ID: "); Serial.println(chipId);

  adc1_config_width(ADC_WIDTH_BIT_12);
  adc1_config_channel_atten(ADC1_CHANNEL_1, ADC_ATTEN_DB_11);

  pinMode(myBat, INPUT); // battery voltage monitor

  pinMode(CCS811_intPin, INPUT_PULLUP); // active LOW

  I2C_BUS.begin(0, 3);               // Set master mode, default on SDA on pin 0/SCL  on pin 3
  I2C_BUS.setClock(400000);          // I2C frequency at 400 kHz
  delay(1000);

  pinMode(CCS811_wakePin, OUTPUT);
  //Enable the CCS811 for I2C scan
  digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
  
  Serial.println("Scan for I2C devices:");
  i2c_0.I2Cscan();                   // should detect BME280 at 0x76 and CCS811 at 0x5A
  delay(1000);

  //Disable the CCS811 for I2C scan
  digitalWrite(CCS811_wakePin, HIGH); // set LOW to enable the CCS811 air quality sensor
  delay(1000);

  // Read the WHO_AM_I register of the BME280 this is a good test of communication
  byte BME280ChipID = BME280.getChipID();  // Read WHO_AM_I register for BME280
  Serial.print("BME280 "); Serial.print("I AM "); Serial.print(BME280ChipID, HEX); Serial.print(" I should be "); Serial.println(0x60, HEX);
  Serial.println(" ");
  delay(1000); 

  // Read the WHO_AM_I register of the CCS811 this is a good test of communication
  digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
  byte CCS811ChipID = CCS811.getChipID();
  digitalWrite(CCS811_wakePin, HIGH); // set HIGH to disable the CCS811 air quality sensor
  Serial.print("CCS811 "); Serial.print("I AM "); Serial.print(CCS811ChipID, HEX); Serial.print(" I should be "); Serial.println(0x81, HEX);
  Serial.println(" ");
  delay(1000); 
  
  if(BME280ChipID == 0x60 && CCS811ChipID == 0x81 ) {

   Serial.println("BME280+CCS811 are online..."); Serial.println(" ");
   digitalWrite(myLed, LOW);

   BME280.resetBME280();                                                        // reset BME280 before initilization
   delay(100);
   BME280.BME280Init(Posr, Hosr, Tosr, Mode, IIRFilter, SBy);                   // Initialize BME280 altimeter
   BME280.BME280forced();                                                       // get initial data sample, then go back to sleep

   // initialize CCS811 and check version and status
   digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
   CCS811.CCS811init(AQRate);
   digitalWrite(CCS811_wakePin, HIGH); // set HIGH to disable the CCS811 air quality sensor

   }
   else {
   if(BME280ChipID != 0x60) Serial.println(" BME280 not functioning!");    
   if(CCS811ChipID != 0x81) Serial.println(" CCS811 not functioning!");  
   while(1) { }; // no point proceeding, so wait here forever...
   }

  // Set up ESP32 timer
  /* Use 1st timer of 4 */
  /* 1 tick take 1/(80MHZ/80) = 1us so we set divider 80 and count up */
  timer = timerBegin(0, 80, true);

  /* Attach onTimer function to our timer */
  timerAttachInterrupt(timer, &onTimer, true);

  /* Set alarm to call onTimer function every second 1 tick is 1us
  => 1 second is 1000000us */
  /* Repeat the alarm (third parameter) */
  timerAlarmWrite(timer, 10000000, true); // update every ten seconds

  /* Start an alarm */
  timerAlarmEnable(timer);
  Serial.println("start timer");

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp32")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.onNotFound(handleNotFound);

  server.on("/ESP32Data", [](){ // define web server data

    // BME280 Data
    rawTemp =   BME280.readBME280Temperature();
    temperature_C = (float) BME280.BME280_compensate_T(rawTemp)/100.0f; // temperature in Centigrade
    temperature_F = 9.0f*temperature_C/5.0f + 32.0f;
    rawPress =  BME280.readBME280Pressure();
    pressure = (float) BME280.BME280_compensate_P(rawPress)/25600.0f; // Pressure in millibar
    altitude = 145366.45f*(1.0f - powf((pressure/1013.25f), 0.190284f));
    rawHumidity =  BME280.readBME280Humidity();
    humidity = (float) BME280.BME280_compensate_H(rawHumidity)/1024.0f; // Humidity in %RH

    // CCS811 Data
    digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
    CCS811.readCCS811Data(rawData);
    CCS811.compensateCCS811(compHumidity, compTemp); // compensate CCS811 using BME280 humidity and temperature
    digitalWrite(CCS811_wakePin, HIGH); // set LOW to enable the CCS811 air quality sensor 

    eCO2 = (uint16_t) ((uint16_t) rawData[0] << 8 | rawData[1]);
    TVOC = (uint16_t) ((uint16_t) rawData[2] << 8 | rawData[3]);
    Current = (rawData[6] & 0xFC) >> 2;
    Voltage = (float) ((uint16_t) ((((uint16_t)rawData[6] & 0x02) << 8) | rawData[7])) * (1.65f/1023.0f); 

    // Battery Voltage
    VBat = 2.0f * 2.60f * 1.15f * ((float) adc1_get_raw((adc1_channel_t)1)) / 4095.0f;
    
    createHTML(temperature_C, temperature_F, pressure, altitude, humidity, eCO2, TVOC, VBat);
    server.send(200, "text/html", webString);               // send to someone's browser when asked
  });

  server.begin();
  Serial.println("HTTP server started");
  
  attachInterrupt(CCS811_intPin,  myinthandler, FALLING); // enable CCS811 interrupt 
}

void loop()
{  
    // CCS811 data
    // If intPin goes LOW, all data registers have new data
    if(newCCS811Data == true) {  // On interrupt, read data
    newCCS811Data = false;  // reset newData flag
     
    digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
    CCS811.readCCS811Data(rawData);
    CCS811.compensateCCS811(compHumidity, compTemp); // compensate CCS811 using BME280 humidity and temperature
    digitalWrite(CCS811_wakePin, HIGH); // set LOW to enable the CCS811 air quality sensor 

    eCO2 = (uint16_t) ((uint16_t) rawData[0] << 8 | rawData[1]);
    TVOC = (uint16_t) ((uint16_t) rawData[2] << 8 | rawData[3]);
    Current = (rawData[6] & 0xFC) >> 2;
    Voltage = (float) ((uint16_t) ((((uint16_t)rawData[6] & 0x02) << 8) | rawData[7])) * (1.65f/1023.0f); 
    
    Serial.println("CCS811:");
    Serial.print("Eq CO2 in ppm = "); Serial.println(eCO2);
    Serial.print("TVOC in ppb = "); Serial.println(TVOC);
    Serial.print("Sensor current (uA) = "); Serial.println(Current);
    Serial.print("Sensor voltage (V) = "); Serial.println(Voltage, 2);  
    Serial.println(" ");
  }
            
   /*RTC Timer*/
   if (alarmFlag) { // update serial output whenever there is a timer alarm
      alarmFlag = false;

    /* BME280 sensor data */
    BME280.BME280forced();  // get one data sample, then go back to sleep

    rawTemp =  BME280.readBME280Temperature();
    compTemp = BME280.BME280_compensate_T(rawTemp);
    temperature_C = (float) compTemp/100.0f;
    temperature_F = 9.0f*temperature_C/5.0f + 32.0f;
     
    rawPress =  BME280.readBME280Pressure();
    pressure = (float) BME280.BME280_compensate_P(rawPress)/25600.f; // Pressure in mbar
    altitude = 145366.45f*(1.0f - powf((pressure/1013.25f), 0.190284f));   
   
    rawHumidity =  BME280.readBME280Humidity();
    compHumidity = BME280.BME280_compensate_H(rawHumidity);
    humidity = (float)compHumidity/1024.0f; // Humidity in %RH
 
    Serial.println("BME280:");
    Serial.print("Altimeter temperature = "); 
    Serial.print( temperature_C, 2); 
    Serial.println(" C"); // temperature in degrees Celsius
    Serial.print("Altimeter temperature = "); 
    Serial.print(temperature_F, 2); 
    Serial.println(" F"); // temperature in degrees Fahrenheit
    Serial.print("Altimeter pressure = "); 
    Serial.print(pressure, 2);  
    Serial.println(" mbar");// pressure in millibar
    Serial.print("Altitude = "); 
    Serial.print(altitude, 2); 
    Serial.println(" feet");
    Serial.print("Altimeter humidity = "); 
    Serial.print(humidity, 1);  
    Serial.println(" %RH");// pressure in millibar
    Serial.println(" ");

    uint16_t Counts = adc1_get_raw((adc1_channel_t)1);
    /* ADC at attenuation 11 should rad from 0 to 2.6 V nominally. The resistor divider
     *  is 1/2, and a calibration factor of 1.15 is applied to bring measurements into 
     *  agreement with multimeter */
    VBat = 2.0f * 2.60f * 1.15f * ((float) Counts) / 4095.0f;
    Serial.print("Battery voltage = "); Serial.print(VBat, 2); Serial.println(" V");

    server.handleClient(); // update web server page
      
    digitalWrite(myLed, LOW); delay(10); digitalWrite(myLed, HIGH); // blink led at end of loop
    }  
    
 yield(); //allow the cpu to switch to other tasks
//     ESP32.sleep();    // time out in deep sleep mode to save power
}

//===================================================================================================================
//====== Set of useful functions
//===================================================================================================================

void myinthandler()
{
  newCCS811Data = true;
}


void alarmMatch()
{
  alarmFlag = true;
}


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/I2CDev.cpp
================================================
/*
 * Copyright (c) 2018 Tlera Corp.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimers.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimers in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Tlera Corp, nor the names of its contributors
 *     may be used to endorse or promote products derived from this Software
 *     without specific prior written permission.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * WITH THE SOFTWARE.
 */

#include "Arduino.h"
#include "I2Cdev.h"

#define USBSerial Serial

I2Cdev::I2Cdev(TwoWire* i2c_bus)                                                                                                             // Class constructor
{
  _i2c_bus = i2c_bus;
}

I2Cdev::~I2Cdev()                                                                                                                            // Class destructor
{
}

/**
* @fn: readByte(uint8_t address, uint8_t subAddress)
*
* @brief: Read one byte from an I2C device
* 
* @params: I2C slave device address, Register subAddress
* @returns: unsigned short read
*/
uint8_t I2Cdev::readByte(uint8_t address, uint8_t subAddress)
{
  uint8_t data = 0;                             // `data` will store the register data   
  _i2c_bus->beginTransmission(address);         // Initialize the Tx buffer
  _i2c_bus->write(subAddress);                  // Put slave register address in Tx buffer
  _i2c_bus->endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
  _i2c_bus->requestFrom(address, 1);            // Read one byte from slave register address  
  data = _i2c_bus->read();                      // Fill Rx buffer with result
  return data;                                  // Return data read from slave register
  
}


/**
* @fn: readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
*
* @brief: Read multiple bytes from an I2C device
* 
* @params: I2C slave device address, Register subAddress, number of btes to be read, aray to store the read data
* @returns: void
*/
void I2Cdev::readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
{  
  _i2c_bus->beginTransmission(address);   // Initialize the Tx buffer
  _i2c_bus->write(subAddress);            // Put slave register address in Tx buffer
  _i2c_bus->endTransmission(false);       // Send the Tx buffer, but send a restart to keep connection alive
  uint8_t i = 0;
  _i2c_bus->requestFrom(address, count);  // Read bytes from slave register address 
  while (_i2c_bus->available()) {
        dest[i++] = _i2c_bus->read(); }   // Put read results in the Rx buffer
}


/**
* @fn: writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data)
*
* @brief: Write one byte to an I2C device
* 
* @params: I2C slave device address, Register subAddress, data to be written
* @returns: void
*/
void I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data)
{
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  _i2c_bus->write(regAddr);              // Put slave register address in Tx buffer
  _i2c_bus->write(data);                 // Put data in Tx buffer
  _i2c_bus->endTransmission();           // Send the Tx buffer
}

/**
* @fn: writeReg(uint8_t devAddr, uint8_t regAddr)
*
* @brief: Write register to an I2C device
* 
* @params: I2C slave device address, Register subAddress, data to be written
* @returns: void
*/
void I2Cdev::writeReg(uint8_t devAddr, uint8_t regAddr)
{
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  _i2c_bus->write(regAddr);              // Put slave register address in Tx buffer
  _i2c_bus->endTransmission();           // Send the Tx buffer
}


/**
* @fn: writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t data)
*
* @brief: Write multiple bytes to an I2C device
* 
* @params: I2C slave device address, Register subAddress, byte count, data array to be written
* @returns: void
*/
void I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t count, uint8_t *dest)
{
  uint8_t temp[1 + count];
  
  temp[0] = regAddr;
  for (uint8_t ii = 0; ii < count; ii++)
  { 
    temp[ii + 1] = dest[ii];
  }
  
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  
  for (uint8_t jj = 0; jj < count + 1; jj++)
  {
  _i2c_bus->write(temp[jj]);            // Put data in Tx buffer
  }
  
  _i2c_bus->endTransmission();          // Send the Tx buffer
}



/**
* @fn:I2Cscan()
* @brief: Scan the I2C bus for active I2C slave devices
* 
* @params: void
* @returns: void
*/
void I2Cdev::I2Cscan() 
{
  // Scan for i2c devices
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  {
    // The i2c_scanner uses the return value of the Wire.endTransmisstion to see if a device did acknowledge to the address.
    _i2c_bus->beginTransmission(address);
    error = _i2c_bus->endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16) 
      Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");
      nDevices++;
    }
    else if (error==4) 
    {
      Serial.print("Unknow error at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.println(address,HEX);
    }    
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("I2C scan complete\n");
}


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/I2CDev.h
================================================
/*
 * Copyright (c) 2018 Tlera Corp.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimers.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimers in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Tlera Corp, nor the names of its contributors
 *     may be used to endorse or promote products derived from this Software
 *     without specific prior written permission.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * WITH THE SOFTWARE.
 */

#ifndef _I2CDEV_H_
#define _I2CDEV_H_

#include <Wire.h>

class I2Cdev {
    public:
                                        I2Cdev(TwoWire*);
                                        ~I2Cdev();                                                                                                                     // Class destructor for durable instances
         uint8_t                        readByte(uint8_t address, uint8_t subAddress);
         void                           readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest);
         void                           writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data);
         void                           writeReg(uint8_t devAddr, uint8_t regAddr);
         void                           writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t count, uint8_t *dest);
         void                           I2Cscan();
    private:
         TwoWire*                       _i2c_bus;                                                                                                                      // Class constructor argument
};

#endif //_I2CDEV_H_


================================================
FILE: CCS811_BME280_ESP32C3Mini_WebServer/Readme.md
================================================
Environmental Monitoring sketch

Demonstration of a simple webserver pushing data from BME280 (pressure, temperature, humidity) and CCS811 (eCO2 and TVOC) sensors to a local web server via wifi.

The ESP32 is an ESP32 C3 Mini module on a custom development board using the native USB for programming with the Arduino IDE and USB serial output.

![image](https://user-images.githubusercontent.com/6698410/155865582-daab5d08-0a00-4984-9684-b989d95954c0.jpg)

![ESP32Data](https://user-images.githubusercontent.com/6698410/155866112-22a74cbd-d34c-4b75-ac39-dd21a73026d8.jpg)

The web server update is based on a simple timer (here every 10 seconds). I heven't gotten deep sleep to work yet since the ExternalWakeUp example won't compile. But the idea is to manage the power usage of the ESP32 by keeping it in deep sleep mode either on a timer or using the CCS811 (with 60 second sample period) to wake up the ESP32 on data ready interrupt.

The [ESP32 C3 Mini](https://www.digikey.com/en/products/detail/espressif-systems/ESP32-C3-MINI-1-H4/14548936?utm_adgroup=&utm_source=bing&utm_medium=cpc&utm_campaign=Shopping_DK%2BSupplier_Other&utm_term=&utm_content=&utm_id=bi_cmp-384720322_adg-1301822093609990_ad-81363949567673_pla-4584963495352066_dev-c_ext-_prd-14548936) is an inexpensive, fairly small, easy-to-use module that embeds wifi and BLE, and has just enough GPIOs available to be useful for environmental end nodes. Being able to program it with native USB (no CP2102 or FTDI tranceiver!) is a real plus.

The development board [design](https://oshpark.com/shared_projects/wibSiWQn) is open source and available at the OSH Park shared space.


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/BME280.cpp
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 This sketch uses SDA/SCL on pins 42/43 (back pads), respectively, and it uses the Dragonfly STM32L476RE Breakout Board.
 The BME280 is a simple but high resolution pressure/humidity/temperature sensor, which can be used in its high resolution
 mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 only 1 microAmp. The choice will depend on the application.
 
 Library may be used freely and without limit with attribution.
 
*/
 
#include "BME280.h"
#include "I2Cdev.h"

#define SerialDebug false  // set to true to get Serial output for debugging

BME280::BME280(I2Cdev* i2c_bus)
{
  _i2c_bus = i2c_bus;
}


uint8_t BME280::getChipID()
{
  uint8_t c = _i2c_bus->readByte(BME280_ADDRESS, BME280_ID);
  return c;
}

void BME280::resetBME280()
{
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_RESET, 0xB6);
}


int32_t BME280::readBME280Temperature()
{
  uint8_t rawData[3];  // 20-bit temperature register data stored here
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_TEMP_MSB, 3, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 16 | (uint32_t) rawData[1] << 8 | rawData[2]) >> 4);
}


int32_t BME280::readBME280Pressure()
{
  uint8_t rawData[3];  // 20-bit pressure register data stored here
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_PRESS_MSB, 3, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 16 | (uint32_t) rawData[1] << 8 | rawData[2]) >> 4);
}


int32_t BME280::BME280::readBME280Humidity()
{
  uint8_t rawData[2];  // 16-bit humiditye register data stored here
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_HUM_MSB, 2, &rawData[0]);  
  return (uint32_t) (((uint32_t) rawData[0] << 24 | (uint32_t) rawData[1] << 16) ) >> 16;
}


void BME280::BME280forced()
{
    uint8_t temp = _i2c_bus->readByte(BME280_ADDRESS, BME280_CTRL_MEAS);
    _i2c_bus->writeByte(BME280_ADDRESS, BME280_CTRL_MEAS, temp | Forced);
 
    while( (_i2c_bus->readByte(BME280_ADDRESS, BME280_STATUS)) & 0x10) { } // wait for conversion byte to clear
}


void BME280::BME280Init(uint8_t Posr, uint8_t Hosr, uint8_t Tosr, uint8_t Mode, uint8_t IIRFilter, uint8_t SBy)
{
  // Configure the BME280
  // Set H oversampling rate
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_CTRL_HUM, 0x07 & Hosr);
  // Set T and P oversampling rates and sensor mode
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_CTRL_MEAS, Tosr << 5 | Posr << 2 | Mode);
  // Set standby time interval in normal mode and bandwidth
  _i2c_bus->writeByte(BME280_ADDRESS, BME280_CONFIG, SBy << 5 | IIRFilter << 2);
  
  uint8_t calib[26];
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_CALIB00, 26, &calib[0]);
  _dig_T1 = (uint16_t)(((uint16_t) calib[1] << 8) | calib[0]);
  _dig_T2 = ( int16_t)((( int16_t) calib[3] << 8) | calib[2]);
  _dig_T3 = ( int16_t)((( int16_t) calib[5] << 8) | calib[4]);
  _dig_P1 = (uint16_t)(((uint16_t) calib[7] << 8) | calib[6]);
  _dig_P2 = ( int16_t)((( int16_t) calib[9] << 8) | calib[8]);
  _dig_P3 = ( int16_t)((( int16_t) calib[11] << 8) | calib[10]);
  _dig_P4 = ( int16_t)((( int16_t) calib[13] << 8) | calib[12]);
  _dig_P5 = ( int16_t)((( int16_t) calib[15] << 8) | calib[14]);
  _dig_P6 = ( int16_t)((( int16_t) calib[17] << 8) | calib[16]);
  _dig_P7 = ( int16_t)((( int16_t) calib[19] << 8) | calib[18]);
  _dig_P8 = ( int16_t)((( int16_t) calib[21] << 8) | calib[20]);
  _dig_P9 = ( int16_t)((( int16_t) calib[23] << 8) | calib[22]);
  _dig_H1 = calib[25];
  _i2c_bus->readBytes(BME280_ADDRESS, BME280_CALIB26, 7, &calib[0]);
  _dig_H2 = ( int16_t)((( int16_t) calib[1] << 8) | calib[0]);
  _dig_H3 = calib[2];
  _dig_H4 = ( int16_t)(((( int16_t) calib[3] << 8) | (0x0F & calib[4]) << 4) >> 4);
  _dig_H5 = ( int16_t)(((( int16_t) calib[5] << 8) | (0xF0 & calib[4]) ) >> 4 );
  _dig_H6 = calib[6];
  
 if(SerialDebug)  {
  USBSerial.println("Calibration coeficients:");
  USBSerial.print("_dig_T1 ="); 
  USBSerial.println(_dig_T1);
  USBSerial.print("_dig_T2 ="); 
  USBSerial.println(_dig_T2);
  USBSerial.print("_dig_T3 ="); 
  USBSerial.println(_dig_T3);
  USBSerial.print("_dig_P1 ="); 
  USBSerial.println(_dig_P1);
  USBSerial.print("_dig_P2 ="); 
  USBSerial.println(_dig_P2);
  USBSerial.print("_dig_P3 ="); 
  USBSerial.println(_dig_P3);
  USBSerial.print("_dig_P4 ="); 
  USBSerial.println(_dig_P4);
  USBSerial.print("_dig_P5 ="); 
  USBSerial.println(_dig_P5);
  USBSerial.print("_dig_P6 ="); 
  USBSerial.println(_dig_P6);
  USBSerial.print("_dig_P7 ="); 
  USBSerial.println(_dig_P7);
  USBSerial.print("_dig_P8 ="); 
  USBSerial.println(_dig_P8);
  USBSerial.print("_dig_P9 ="); 
  USBSerial.println(_dig_P9);
  USBSerial.print("_dig_H1 ="); 
  USBSerial.println(_dig_H1);
  USBSerial.print("_dig_H2 ="); 
  USBSerial.println(_dig_H2);
  USBSerial.print("_dig_H3 ="); 
  USBSerial.println(_dig_H3);
  USBSerial.print("_dig_H4 ="); 
  USBSerial.println(_dig_H4);
  USBSerial.print("_dig_H5 ="); 
  USBSerial.println(_dig_H5);
  USBSerial.print("_dig_H6 ="); 
  USBSerial.println(_dig_H6);
 }
}


// Returns temperature in DegC, resolution is 0.01 DegC. Output value of
// “5123” equals 51.23 DegC.
int32_t BME280::BME280_compensate_T(int32_t adc_T)
{
  int32_t var1, var2, T;
  var1 = ((((adc_T >> 3) - ((int32_t)_dig_T1 << 1))) * ((int32_t)_dig_T2)) >> 11;
  var2 = (((((adc_T >> 4) - ((int32_t)_dig_T1)) * ((adc_T >> 4) - ((int32_t)_dig_T1))) >> 12) * ((int32_t)_dig_T3)) >> 14;
  _t_fine = var1 + var2;
  T = (_t_fine * 5 + 128) >> 8;
  return T;
}


// Returns pressure in Pa as unsigned 32 bit integer in Q24.8 format (24 integer bits and 8
//fractional bits).
//Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa
uint32_t BME280::BME280_compensate_P(int32_t adc_P)
{
  long long var1, var2, p;
  var1 = ((long long)_t_fine) - 128000;
  var2 = var1 * var1 * (long long)_dig_P6;
  var2 = var2 + ((var1*(long long)_dig_P5)<<17);
  var2 = var2 + (((long long)_dig_P4)<<35);
  var1 = ((var1 * var1 * (long long)_dig_P3)>>8) + ((var1 * (long long)_dig_P2)<<12);
  var1 = (((((long long)1)<<47)+var1))*((long long)_dig_P1)>>33;
  if(var1 == 0)
  {
    return 0;
    // avoid exception caused by division by zero
  }
  p = 1048576 - adc_P;
  p = (((p<<31) - var2)*3125)/var1;
  var1 = (((long long)_dig_P9) * (p>>13) * (p>>13)) >> 25;
  var2 = (((long long)_dig_P8) * p)>> 19;
  p = ((p + var1 + var2) >> 8) + (((long long)_dig_P7)<<4);
  return (uint32_t)p;
}


// Returns humidity in %RH as unsigned 32 bit integer in Q22.10 format (22integer and 10fractional bits).
// Output value of “47445”represents 47445/1024= 46.333%RH
uint32_t BME280::BME280_compensate_H(int32_t adc_H)
{
int32_t var;

var = (_t_fine - ((int32_t)76800));
var = (((((adc_H << 14) - (((int32_t)_dig_H4) << 20) - (((int32_t)_dig_H5) * var)) +
((int32_t)16384)) >> 15) * (((((((var * ((int32_t)_dig_H6)) >> 10) * (((var *
((int32_t)_dig_H3)) >> 11) + ((int32_t)32768))) >> 10) + ((int32_t)2097152)) * ((int32_t)_dig_H2) + 8192) >> 14));
var = (var - (((((var >> 15) * (var >> 15)) >> 7) * ((int32_t)_dig_H1)) >> 4));
var = (var < 0 ? 0 : var); 
var = (var > 419430400 ? 419430400 : var);
return(uint32_t)(var >> 12);
}


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/BME280.h
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 This sketch uses SDA/SCL on pins 42/43 (back pads), respectively, and it uses the Dragonfly STM32L476RE Breakout Board.
 The BME280 is a simple but high resolution pressure/humidity/temperature sensor, which can be used in its high resolution
 mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 only 1 microAmp. The choice will depend on the application.
 
 Library may be used freely and without limit with attribution.
 
*/
  
#ifndef BME280_h
#define BME280_h

#include "Arduino.h"
#include "I2CDev.h"
#include <Wire.h>

/* BME280 registers
*  http://www.mouser.com/ds/2/783/BST-BME280_DS001-11-844833.pdf
*/
#define BME280_HUM_LSB    0xFE
#define BME280_HUM_MSB    0xFD
#define BME280_TEMP_XLSB  0xFC
#define BME280_TEMP_LSB   0xFB
#define BME280_TEMP_MSB   0xFA
#define BME280_PRESS_XLSB 0xF9
#define BME280_PRESS_LSB  0xF8
#define BME280_PRESS_MSB  0xF7
#define BME280_CONFIG     0xF5
#define BME280_CTRL_MEAS  0xF4
#define BME280_STATUS     0xF3
#define BME280_CTRL_HUM   0xF2
#define BME280_RESET      0xE0
#define BME280_ID         0xD0  // should be 0x60
#define BME280_CALIB00    0x88
#define BME280_CALIB26    0xE1

#define BME280_ADDRESS           0x76   // Address of BMP280 altimeter when ADO = 0


#define  P_OSR_01 0x01
#define  P_OSR_02 0x02
#define  P_OSR_04 0x03
#define  P_OSR_08 0x04
#define  P_OSR_16 0x05

#define  H_OSR_01 0x01
#define  H_OSR_02 0x02
#define  H_OSR_04 0x03
#define  H_OSR_08 0x04
#define  H_OSR_16 0x05

#define  T_OSR_01 0x01
#define  T_OSR_02 0x02
#define  T_OSR_04 0x03
#define  T_OSR_08 0x04
#define  T_OSR_16 0x05

#define  full       0x00
#define  BW0_223ODR 0x01
#define  BW0_092ODR 0x02
#define  BW0_042ODR 0x03
#define  BW0_021ODR 0x04  

#define  BME280Sleep 0x00
#define  Forced      0x01
#define  Forced2     0x02
#define  Normal      0x03

#define  t_00_5ms 0x00
#define  t_62_5ms 0x01
#define  t_125ms  0x02
#define  t_250ms  0x03
#define  t_500ms  0x04
#define  t_1000ms 0x05
#define  t_10ms   0x06
#define  t_20ms   0x07 


class BME280
{
  public: 
  BME280(I2Cdev* i2c_bus);
  uint8_t getChipID();
  void resetBME280();
  int32_t readBME280Temperature();
  int32_t readBME280Pressure();
  int32_t readBME280Humidity();
  void BME280forced();
  void BME280Init(uint8_t Posr, uint8_t Hosr, uint8_t Tosr, uint8_t Mode, uint8_t IIRFilter, uint8_t SBy);
  int32_t  BME280_compensate_T(int32_t adc_T);
  uint32_t BME280_compensate_P(int32_t adc_P);
  uint32_t BME280_compensate_H(int32_t adc_H);
  
  private:
  uint8_t  _dig_H1, _dig_H3, _dig_H6;
  uint16_t _dig_T1, _dig_P1, _dig_H4, _dig_H5;
  int16_t  _dig_T2, _dig_T3, _dig_P2, _dig_P3, _dig_P4, _dig_P5, _dig_P6, _dig_P7, _dig_P8, _dig_P9, _dig_H2;
  int32_t  _t_fine;
  I2Cdev* _i2c_bus;
  };

#endif


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/CCS811.cpp
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 *  The AMS CCS811 is an air quality sensor that provides equivalent CO2 and volatile organic measurements from direct
 *  I2C register reads as well as current and voltage (effective resistance of the sensing element). Gas sensors, including 
 *  this MEMs gas sensor in the CCS811 measure resistance of a substrate that changes when exposed to inert gasses and 
 *  volatile organic compounds. Changed in concentration vary exponentially with the changes in resistance. The CCS811
 *  has an embedded ASIC calibrated against most common indoor pollutants that returns a good estimate of
 *  equivalent CO2 concentration in parts per million (400 - 8192 range) and volatile organic compounds in parts per billion (0 - 1187).
 *  The sensor is quite sensitive to breath and other human emissions.
 *  
 *  Library may be used freely and without limit with attribution.
 *  
 */
#include "CCS811.h"
#include "I2Cdev.h"

#define SerialDebug false  // set to true to get Serial output for debugging

CCS811::CCS811(I2Cdev* i2c_bus)
{
  _i2c_bus = i2c_bus;   
}


uint8_t CCS811::getChipID()
{
 byte e = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_ID);  // Read WHO_AM_I register for CCS8110
 return e;
}


void CCS811::checkCCS811Status() 
{
   // Check CCS811 status
  uint8_t status = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_STATUS);
  if(SerialDebug) {USBSerial.print("status = 0X"); USBSerial.println(status, HEX);}
  if(status & 0x80 && SerialDebug) {USBSerial.println("Firmware is in application mode. CCS811 is ready!");}
  else { 
    if(SerialDebug) {USBSerial.println("Firmware is in boot mode!");}
   }
  
  if(status & 0x10 && SerialDebug) {USBSerial.println("Valid application firmware loaded!");}
  else { 
    if(SerialDebug) {USBSerial.println("No application firmware is loaded!");}
  }
  if(status & 0x08 && SerialDebug) {
   USBSerial.println("New data available!");
  }
  else { 
    if(SerialDebug) {USBSerial.println("No new data available!");}
  }

  if(status & 0x01 && SerialDebug) {USBSerial.println("Error detected!");
        uint8_t error = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_ERROR_ID);
        if(error & 0x01 && SerialDebug) USBSerial.println("CCS811 received invalid I2C write request!");
        if(error & 0x02 && SerialDebug) USBSerial.println("CCS811 received invalid I2C read request!");
        if(error & 0x04 && SerialDebug) USBSerial.println("CCS811 received unsupported mode request!");
        if(error & 0x08 && SerialDebug) USBSerial.println("Sensor resistance measurement at maximum range!");
        if(error & 0x10 && SerialDebug) USBSerial.println("Heater current is not in range!");
        if(error & 0x20 && SerialDebug) USBSerial.println("Heater voltage is not being applied correctly!");
  }
  else { 
    if(SerialDebug) {USBSerial.println("No error detected!");}
  }
  
  if(SerialDebug) USBSerial.println(" ");
  
  }


  void CCS811::CCS811init(uint8_t AQRate)
  {
    // initialize CCS811 and check version and status
  byte HWVersion = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_HW_VERSION);
    if(SerialDebug) {USBSerial.print("CCS811 Hardware Version = 0x"); USBSerial.println(HWVersion, HEX); }

  uint8_t FWBootVersion[2] = {0, 0}, FWAppVersion[2] = {0,0};
  _i2c_bus->readBytes(CCS811_ADDRESS, CCS811_FW_BOOT_VERSION, 2, &FWBootVersion[0]);
  if(SerialDebug) {  
    USBSerial.println("CCS811 Firmware Boot Version: "); 
    USBSerial.print("Major = "); USBSerial.println((FWBootVersion[0] & 0xF0) >> 4); 
    USBSerial.print("Minor = "); USBSerial.println(FWBootVersion[0] & 0x04); 
    USBSerial.print("Trivial = "); USBSerial.println(FWBootVersion[1]); 
  }
  _i2c_bus->readBytes(CCS811_ADDRESS, CCS811_FW_APP_VERSION, 2, &FWAppVersion[0]);
  if(SerialDebug) {
    USBSerial.println("CCS811 Firmware App Version: "); 
    USBSerial.print("Major = "); USBSerial.println((FWAppVersion[0] & 0xF0) >> 4); 
    USBSerial.print("Minor = "); USBSerial.println(FWAppVersion[0] & 0x04); 
    USBSerial.print("Trivial = "); USBSerial.println(FWAppVersion[1]); 
  }

  // Check CCS811 status
  checkCCS811Status();
  _i2c_bus->writeReg(CCS811_ADDRESS, CCS811_APP_START);
  delay(100);
  checkCCS811Status();

  // set CCS811 measurement mode
  _i2c_bus->writeByte(CCS811_ADDRESS, CCS811_MEAS_MODE, AQRate << 4 | 0x08); // pulsed heating mode, enable interrupt
  uint8_t measmode = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_MEAS_MODE);
  if(SerialDebug) {USBSerial.print("Confirm measurement mode = 0x"); USBSerial.println(measmode, HEX);}
  }


  void CCS811::compensateCCS811(int32_t compHumidity, int32_t compTemp)
  {
      // Update CCS811 humidity and temperature compensation
      uint8_t temp[5] = {0, 0, 0, 0, 0};
      temp[0] = CCS811_ENV_DATA;
      temp[1] = ((compHumidity % 1024) / 100) > 7 ? (compHumidity/1024 + 1)<<1 : (compHumidity/1024)<<1;
      temp[2] = 0;
      if(((compHumidity % 1024) / 100) > 2 && (((compHumidity % 1024) / 100) < 8))
      {
       temp[1] |= 1;
      }

      compTemp += 2500;
      temp[3] = ((compTemp % 100) / 100) > 7 ? (compTemp/100 + 1)<<1 : (compTemp/100)<<1;
      temp[4] = 0;
      if(((compTemp % 100) / 100) > 2 && (((compTemp % 100) / 100) < 8))
      {
       temp[3] |= 1;
      }

//      Wire.transfer(CCS811_ADDRESS, &temp[0], 5, NULL, 0);
     _i2c_bus->writeBytes(CCS811_ADDRESS, CCS811_ENV_DATA, 4, &temp[1]);
  }

   void CCS811::readCCS811Data(uint8_t * destination)
   {
      uint8_t rawData[8] = {0, 0, 0, 0, 0, 0, 0, 0};
      uint8_t status = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_STATUS);
      
      if(status & 0x01) { // check for errors
        uint8_t error = _i2c_bus->readByte(CCS811_ADDRESS, CCS811_ERROR_ID);
        if(error & 0x01 && SerialDebug) USBSerial.println("CCS811 received invalid I2C write request!");
        if(error & 0x02 && SerialDebug) USBSerial.println("CCS811 received invalid I2C read request!");
        if(error & 0x04 && SerialDebug) USBSerial.println("CCS811 received unsupported mode request!");
        if(error & 0x08 && SerialDebug) USBSerial.println("Sensor resistance measurement at maximum range!");
        if(error & 0x10 && SerialDebug) USBSerial.println("Heater current is not in range!");
        if(error & 0x20 && SerialDebug) USBSerial.println("Heater voltage is not being applied correctly!");
      }

      _i2c_bus->readBytes(CCS811_ADDRESS, CCS811_ALG_RESULT_DATA, 8, &rawData[0]);

   for(int ii = 0; ii < 8; ii++)
   {
    destination[ii] = rawData[ii];
   }
   
   }


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/CCS811.h
================================================
#ifndef CCS811_h
#define CCS811_h

#include "Arduino.h"
#include "Wire.h"
#include "I2Cdev.h"

/* CCS811 Registers
http://www.mouser.com/ds/2/588/CCS811_DS000459_3-00-1098798.pdf
*/
#define CCS811_STATUS             0x00
#define CCS811_MEAS_MODE          0x01
#define CCS811_ALG_RESULT_DATA    0x02
#define CCS811_RAW_DATA           0x03
#define CCS811_ENV_DATA           0x05
#define CCS811_NTC                0x06
#define CCS811_THRESHOLDS         0x10
#define CCS811_BASELINE           0x11
#define CCS811_HW_ID              0x20  // WHO_AM_I should be 0x81
#define CCS811_ID                 0x20  // WHO_AM_I should be 0x1X
#define CCS811_HW_VERSION         0x21  
#define CCS811_FW_BOOT_VERSION    0x23
#define CCS811_FW_APP_VERSION     0x24
#define CCS811_ERROR_ID           0xE0
#define CCS811_APP_START          0xF4
#define CCS811_SW_RESET           0xFF

#define CCS811_ADDRESS            0x5A   // Address of the CCS811 Air Quality Sensor

#define  dt_idle  0x00
#define  dt_1sec  0x01
#define  dt_10sec 0x02
#define  dt_60sec 0x03

class CCS811
{
  public: 
  CCS811(I2Cdev* i2c_bus);
  void checkCCS811Status();
  void CCS811init(uint8_t AQRate);
  uint8_t getChipID();
  void compensateCCS811(int32_t compHumidity, int32_t compTemp);
  void readCCS811Data(uint8_t * destination);
  
  private:
  I2Cdev* _i2c_bus;
};


#endif


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/CCS811_BME280_ESP32C3Mini_deepSleep.ino
================================================
/* 06/16/2017 Copyright Tlera Corporation
 *  
 *  Created by Kris Winer
 *  
 *  The AMS CCS811 is an air quality sensor that provides equivalent CO2 and volatile organic measurements from direct
 *  I2C register reads as well as current and voltage (effective resistance of the sensing element). Gas sensors, including 
 *  this MEMs gas sensor in the CCS811 measure resistance of a substrate that changes when exposed to inert gasses and 
 *  volatile organic compounds. Changed in concentration vary exponentially with the changes in resistance. The CCS811
 *  has an embedded ASIC calibrated against most common indoor pollutants that returns a good estimate of
 *  equivalent CO2 concentration in parts per million (400 - 8192 range) and volatile organic componds in parts per billion (0 - 1187).
 *  The sensor is quite sensitive to breath and other human emissions.
 *  
  *  The BME280 is a simple but high resolution pressure/humidity/temperature sensor, which can be used in its high resolution
 *  mode but with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of
 *  only 1 microAmp. The choice will depend on the application.
 
    Library may be used freely and without limit with attribution.
 
  */
#include <Arduino.h>
#include <driver/adc.h>
#include "BME280.h"
#include "CCS811.h"
#include "I2Cdev.h"

#define uS_TO_S_FACTOR 1000000ULL  /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP  600        /* Time ESP32 will go to sleep (in seconds) */

RTC_DATA_ATTR int bootCount = 0;

void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;

  wakeup_reason = esp_sleep_get_wakeup_cause();

  switch(wakeup_reason)
  {
//      case ESP_SLEEP_WAKEUP_EXT0 : USBSerial.println("Wakeup caused by external signal using RTC_IO"); break;
//      case ESP_SLEEP_WAKEUP_EXT1 : USBSerial.println("Wakeup caused by external signal using RTC_CNTL"); break;
//      case ESP_SLEEP_WAKEUP_TIMER : USBSerial.println("Wakeup caused by timer"); break;
//      case ESP_SLEEP_WAKEUP_TOUCHPAD : USBSerial.println("Wakeup caused by touchpad"); break;
//      case ESP_SLEEP_WAKEUP_ULP : USBSerial.println("Wakeup caused by ULP program"); break;
//      default : USBSerial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
  }
}

#define I2C_BUS          Wire               // Define the I2C bus (Wire instance) you wish to use

I2Cdev                   i2c_0(&I2C_BUS);   // Instantiate the I2Cdev object and point to the desired I2C bus

#define SerialDebug false  // set to true to get Serial output for debugging
const uint8_t myLed =  2;  // green led
const uint8_t myBat =  1;  // battery monitor

float VBat = 0.0f;
uint32_t chipId = 0;

// BME280 definitions
/* Specify BME280 configuration
 *  Choices are:
 P_OSR_01, P_OSR_02, P_OSR_04, P_OSR_08, P_OSR_16 // pressure oversampling
 H_OSR_01, H_OSR_02, H_OSR_04, H_OSR_08, H_OSR_16 // humidity oversampling
 T_OSR_01, T_OSR_02, T_OSR_04, T_OSR_08, T_OSR_16 // temperature oversampling
 full, BW0_223ODR,BW0_092ODR, BW0_042ODR, BW0_021ODR // bandwidth at 0.021 x sample rate
 BME280Sleep, forced,, forced2, normal //operation modes
 t_00_5ms = 0, t_62_5ms, t_125ms, t_250ms, t_500ms, t_1000ms, t_10ms, t_20ms // determines sample rate
 */
uint8_t Posr = P_OSR_01, Hosr = H_OSR_01, Tosr = T_OSR_01, Mode = BME280Sleep, IIRFilter = full, SBy = t_1000ms;     // set pressure amd temperature output data rate

float Temperature, Pressure, Humidity;              // stores BME280 pressures sensor pressure and temperature
int32_t rawPress, rawTemp, rawHumidity, compTemp;   // pressure and temperature raw count output for BME280
uint32_t compHumidity, compPress;                   // variables to hold raw BME280 humidity value

float temperature_C, temperature_F, pressure, humidity, altitude; // Scaled output of the BME280

BME280 BME280(&i2c_0); // instantiate BME280 class


// CCS811 definitions
#define CCS811_intPin  4
#define CCS811_wakePin 7

/* Specify CCS811 sensor parameters
 *  Choices are   dt_idle , dt_1sec, dt_10sec, dt_60sec
 */
//uint8_t AQRate = dt_60sec;  // set the sample rate
uint8_t AQRate = dt_idle;  // set the sample rate
uint8_t rawData[8] = {0, 0, 0, 0, 0, 0, 0, 0};  // array to hold the raw data
uint16_t eCO2 = 0, TVOC = 0;
uint8_t Current = 0;
float Voltage = 0.0f;

volatile bool newCCS811Data  = true; // boolean flag for interrupt

CCS811 CCS811(&i2c_0); // instantiate CCS811 class


void setup()
{
  if(SerialDebug) USBSerial.begin(115200);
  if(SerialDebug) USBSerial.println("Serial enabled!");

  pinMode(myLed, OUTPUT);
  digitalWrite(myLed, HIGH); // start with led off, active LOW
  pinMode(myBat, INPUT); // battery voltage monitor
  pinMode(CCS811_intPin, INPUT); // active LOW

  //Increment boot number and print it every reboot
  ++bootCount;
   if(SerialDebug) USBSerial.println("Boot number: " + String(bootCount));

  //Print the wakeup reason for ESP32
  print_wakeup_reason();

  if(bootCount == 1) { /*... Only need to do this part once on startup! */
    for(int i=0; i<17; i=i+8) {
      chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xFF) << i;
    }

   if(SerialDebug) USBSerial.printf("ESP32 Chip model = %s Rev %d\n", ESP.getChipModel(), ESP.getChipRevision());
   if(SerialDebug) USBSerial.printf("This chip has %d cores\n", ESP.getChipCores());
   if(SerialDebug){USBSerial.print("Chip ID: "); USBSerial.println(chipId);}
  } /*... Only need to do this part once on startup! */

  adc1_config_width(ADC_WIDTH_BIT_12);
  adc1_config_channel_atten(ADC1_CHANNEL_1, ADC_ATTEN_DB_11);

  I2C_BUS.begin(0, 3);               // Set master mode, default on SDA on pin 0/SCL  on pin 3
  I2C_BUS.setClock(400000);          // I2C frequency at 400 kHz

  pinMode(CCS811_wakePin, OUTPUT);
  digitalWrite(CCS811_wakePin, HIGH); // set HIGH to disable the CCS811 air quality sensor

  if(bootCount == 1) { /*... Only need to do this part once on startup! */
  //Enable the CCS811 for I2C scan
  digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
  
  if(SerialDebug) USBSerial.println("Scan for I2C devices:");
  i2c_0.I2Cscan();                   // should detect BME280 at 0x76 and CCS811 at 0x5A

  //Disable the CCS811 for I2C scan
  digitalWrite(CCS811_wakePin, HIGH); // set HIGH to disable the CCS811 air quality sensor
  delay(1);

  // Read the WHO_AM_I register of the BME280 this is a good test of communication
  byte BME280ChipID = BME280.getChipID();  // Read WHO_AM_I register for BME280
  if(SerialDebug){ 
    USBSerial.print("BME280 "); USBSerial.print("I AM "); USBSerial.print(BME280ChipID, HEX); USBSerial.print(" I should be "); USBSerial.println(0x60, HEX);
    USBSerial.println(" ");
  }

  // Read the WHO_AM_I register of the CCS811 this is a good test of communication
  digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
  byte CCS811ChipID = CCS811.getChipID();
  digitalWrite(CCS811_wakePin, HIGH); // set HIGH to disable the CCS811 air quality sensor
  if(SerialDebug) {
    USBSerial.print("CCS811 "); USBSerial.print("I AM "); USBSerial.print(CCS811ChipID, HEX); USBSerial.print(" I should be "); USBSerial.println(0x81, HEX);
    USBSerial.println(" ");
  }
  
  if(BME280ChipID == 0x60 && CCS811ChipID == 0x81 ) {

   if(SerialDebug) {USBSerial.println("BME280+CCS811 are online..."); USBSerial.println(" ");}
   digitalWrite(myLed, LOW);

   BME280.resetBME280();                                                        // reset BME280 before initilization
   delay(10);
   BME280.BME280Init(Posr, Hosr, Tosr, Mode, IIRFilter, SBy);                   // Initialize BME280 altimeter
   BME280.BME280forced();                                                       // get initial data sample, then go back to sleep

   // initialize CCS811 and check version and status
   digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
   CCS811.CCS811init(AQRate);
   digitalWrite(CCS811_wakePin, HIGH); // set HIGH to disable the CCS811 air quality sensor

   }
   else {
   if(BME280ChipID != 0x60 && SerialDebug) USBSerial.println(" BME280 not functioning!");    
   if(CCS811ChipID != 0x81 && SerialDebug) USBSerial.println(" CCS811 not functioning!");  
   while(1) { }; // no point proceeding, so wait here forever...
   }
  } /*... Only need to do this part once on startup! */
  

    /*   Put here anything you want to do before going to sleep */
    digitalWrite(CCS811_wakePin, LOW); // set LOW to enable the CCS811 air quality sensor
    CCS811.readCCS811Data(rawData);
    CCS811.compensateCCS811(compHumidity, compTemp); // compensate CCS811 using BME280 humidity and temperature
    digitalWrite(CCS811_wakePin, HIGH); // set HIGH to disable the CCS811 air quality sensor 

    eCO2 = (uint16_t) ((uint16_t) rawData[0] << 8 | rawData[1]);
    TVOC = (uint16_t) ((uint16_t) rawData[2] << 8 | rawData[3]);
    Current = (rawData[6] & 0xFC) >> 2;
    Voltage = (float) ((uint16_t) ((((uint16_t)rawData[6] & 0x02) << 8) | rawData[7])) * (1.65f/1023.0f); 
    
     if(SerialDebug){
      USBSerial.println("CCS811:");
      USBSerial.print("Eq CO2 in ppm = "); USBSerial.println(eCO2);
      USBSerial.print("TVOC in ppb = "); USBSerial.println(TVOC);
      USBSerial.print("Sensor current (uA) = "); USBSerial.println(Current);
      USBSerial.print("Sensor voltage (V) = "); USBSerial.println(Voltage, 2);  
      USBSerial.println(" ");
     }

    /* BME280 sensor data */
    BME280.BME280Init(Posr, Hosr, Tosr, Mode, IIRFilter, SBy);                   // Initialize BME280 altimeter
    BME280.BME280forced();  // get one data sample, then go back to sleep

    rawTemp =  BME280.readBME280Temperature();
    compTemp = BME280.BME280_compensate_T(rawTemp);
    temperature_C = (float) compTemp/100.0f;
    temperature_F = 9.0f*temperature_C/5.0f + 32.0f;
     
    rawPress =  BME280.readBME280Pressure();
    pressure = (float) BME280.BME280_compensate_P(rawPress)/25600.f; // Pressure in mbar
    altitude = 145366.45f*(1.0f - powf((pressure/1013.25f), 0.190284f));   
   
    rawHumidity =  BME280.readBME280Humidity();
    compHumidity = BME280.BME280_compensate_H(rawHumidity);
    humidity = (float)compHumidity/1024.0f; // Humidity in %RH

    if(SerialDebug) {
    USBSerial.println("BME280:");
    USBSerial.print("Altimeter temperature = "); 
    USBSerial.print( temperature_C, 2); 
    USBSerial.println(" C"); // temperature in degrees Celsius
    USBSerial.print("Altimeter temperature = "); 
    USBSerial.print(temperature_F, 2); 
    USBSerial.println(" F"); // temperature in degrees Fahrenheit
    USBSerial.print("Altimeter pressure = "); 
    USBSerial.print(pressure, 2);  
    USBSerial.println(" mbar");// pressure in millibar
    USBSerial.print("Altitude = "); 
    USBSerial.print(altitude, 2); 
    USBSerial.println(" feet");
    USBSerial.print("Altimeter humidity = "); 
    USBSerial.print(humidity, 1);  
    USBSerial.println(" %RH");// pressure in millibar
    USBSerial.println(" ");
    }
    /* ADC at attenuation 11 should read from 0 to 2.6 V nominally. The resistor divider
     *  is 1/2, and a calibration factor of 1.15 is applied to bring measurements into 
     *  agreement with multimeter */
    VBat = 2.0f * 2.60f * 1.15f * ((float) adc1_get_raw((adc1_channel_t)1)) / 4095.0f;
    if(SerialDebug) {USBSerial.print("Battery voltage = "); USBSerial.print(VBat, 2); USBSerial.println(" V");}
      
    digitalWrite(myLed, LOW); delay(1); digitalWrite(myLed, HIGH); // blink led at end of loop

    esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
    if(SerialDebug) USBSerial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) + " Seconds");
  
    //Go to sleep now
    if(SerialDebug) USBSerial.println("Going to sleep now");
    if(SerialDebug) USBSerial.flush(); 
    esp_deep_sleep_start();
    if(SerialDebug) USBSerial.println("This will never be printed");
}

void loop()
{
}


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/I2CDev.cpp
================================================
/*
 * Copyright (c) 2018 Tlera Corp.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimers.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimers in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Tlera Corp, nor the names of its contributors
 *     may be used to endorse or promote products derived from this Software
 *     without specific prior written permission.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * WITH THE SOFTWARE.
 */

#include "Arduino.h"
#include "I2Cdev.h"

#define SerialDebug false  // set to true to get Serial output for debugging

I2Cdev::I2Cdev(TwoWire* i2c_bus)                                                                                                             // Class constructor
{
  _i2c_bus = i2c_bus;
}

I2Cdev::~I2Cdev()                                                                                                                            // Class destructor
{
}

/**
* @fn: readByte(uint8_t address, uint8_t subAddress)
*
* @brief: Read one byte from an I2C device
* 
* @params: I2C slave device address, Register subAddress
* @returns: unsigned short read
*/
uint8_t I2Cdev::readByte(uint8_t address, uint8_t subAddress)
{
  uint8_t data = 0;                             // `data` will store the register data   
  _i2c_bus->beginTransmission(address);         // Initialize the Tx buffer
  _i2c_bus->write(subAddress);                  // Put slave register address in Tx buffer
  _i2c_bus->endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
  _i2c_bus->requestFrom(address, 1);            // Read one byte from slave register address  
  data = _i2c_bus->read();                      // Fill Rx buffer with result
  return data;                                  // Return data read from slave register
  
}


/**
* @fn: readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
*
* @brief: Read multiple bytes from an I2C device
* 
* @params: I2C slave device address, Register subAddress, number of btes to be read, aray to store the read data
* @returns: void
*/
void I2Cdev::readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
{  
  _i2c_bus->beginTransmission(address);   // Initialize the Tx buffer
  _i2c_bus->write(subAddress);            // Put slave register address in Tx buffer
  _i2c_bus->endTransmission(false);       // Send the Tx buffer, but send a restart to keep connection alive
  uint8_t i = 0;
  _i2c_bus->requestFrom(address, count);  // Read bytes from slave register address 
  while (_i2c_bus->available()) {
        dest[i++] = _i2c_bus->read(); }   // Put read results in the Rx buffer
}


/**
* @fn: writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data)
*
* @brief: Write one byte to an I2C device
* 
* @params: I2C slave device address, Register subAddress, data to be written
* @returns: void
*/
void I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data)
{
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  _i2c_bus->write(regAddr);              // Put slave register address in Tx buffer
  _i2c_bus->write(data);                 // Put data in Tx buffer
  _i2c_bus->endTransmission();           // Send the Tx buffer
}

/**
* @fn: writeReg(uint8_t devAddr, uint8_t regAddr)
*
* @brief: Write register to an I2C device
* 
* @params: I2C slave device address, Register subAddress, data to be written
* @returns: void
*/
void I2Cdev::writeReg(uint8_t devAddr, uint8_t regAddr)
{
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  _i2c_bus->write(regAddr);              // Put slave register address in Tx buffer
  _i2c_bus->endTransmission();           // Send the Tx buffer
}


/**
* @fn: writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t data)
*
* @brief: Write multiple bytes to an I2C device
* 
* @params: I2C slave device address, Register subAddress, byte count, data array to be written
* @returns: void
*/
void I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t count, uint8_t *dest)
{
  uint8_t temp[1 + count];
  
  temp[0] = regAddr;
  for (uint8_t ii = 0; ii < count; ii++)
  { 
    temp[ii + 1] = dest[ii];
  }
  
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  
  for (uint8_t jj = 0; jj < count + 1; jj++)
  {
  _i2c_bus->write(temp[jj]);            // Put data in Tx buffer
  }
  
  _i2c_bus->endTransmission();          // Send the Tx buffer
}



/**
* @fn:I2Cscan()
* @brief: Scan the I2C bus for active I2C slave devices
* 
* @params: void
* @returns: void
*/
void I2Cdev::I2Cscan() 
{
  // Scan for i2c devices
  byte error, address;
  int nDevices;

  if(SerialDebug) USBSerial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  {
    // The i2c_scanner uses the return value of the Wire.endTransmission to see if a device did acknowledge to the address.
    _i2c_bus->beginTransmission(address);
    error = _i2c_bus->endTransmission();

    if (error == 0 && SerialDebug)
    {
      USBSerial.print("I2C device found at address 0x");
      if (address<16) 
      USBSerial.print("0");
      USBSerial.print(address,HEX);
      USBSerial.println("  !");
      nDevices++;
    }
    else if (error==4 && SerialDebug) 
    {
      USBSerial.print("Unknown error at address 0x");
      if (address<16) 
        USBSerial.print("0");
        USBSerial.println(address,HEX);
    }    
  }
  if (nDevices == 0 && SerialDebug)
    USBSerial.println("No I2C devices found\n");
  else
    if(SerialDebug) USBSerial.println("I2C scan complete\n");
}


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/I2CDev.h
================================================
/*
 * Copyright (c) 2018 Tlera Corp.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimers.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimers in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Tlera Corp, nor the names of its contributors
 *     may be used to endorse or promote products derived from this Software
 *     without specific prior written permission.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * WITH THE SOFTWARE.
 */

#ifndef _I2CDEV_H_
#define _I2CDEV_H_

#include <Wire.h>

class I2Cdev {
    public:
                                        I2Cdev(TwoWire*);
                                        ~I2Cdev();                                                                                                                     // Class destructor for durable instances
         uint8_t                        readByte(uint8_t address, uint8_t subAddress);
         void                           readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest);
         void                           writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data);
         void                           writeReg(uint8_t devAddr, uint8_t regAddr);
         void                           writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t count, uint8_t *dest);
         void                           I2Cscan();
    private:
         TwoWire*                       _i2c_bus;                                                                                                                      // Class constructor argument
};

#endif //_I2CDEV_H_


================================================
FILE: CCS811_BME280_ESP32C3Mini_deepSleep/Readme.md
================================================
Sketch showing how to use the ESP32C3Mini1 as an environmental data logger. 

I am using a custom ESP32C3Mini1 development board with native USB for programming (no CP2102).

The CCS811 air quality sensor and BME280 humidity/pressure/temperature sensors are on a breakout board and are configured in setup once, 
their data is read and then the ESP32 goes into deep sleep for some time (10 minutes in the sketch). Upon wakeup, the sensor configuration is skipped if the bootcount variable is greater than 1 and the data is read and the ESP32C3 goes into deep sleep, etc. The cycle repeats.

![image](https://user-images.githubusercontent.com/6698410/155865582-daab5d08-0a00-4984-9684-b989d95954c0.jpg)

The idea is to log the data on the native SPIFFS (up to 3 MByte available) and send data updates via either BLE or ESPNow. These bits will be added when I assemble the next version which has the sensors (in this case APDS9253 ambient light sensor, HDC2010 humidity sensor, and LPS22HB barometer) directly on the ESP32C3Mini1 development board.

I measured deep sleep current with no sensors of 8.9 uA. However, this is with a simple 1 MOhm+1 MOhm voltage divider, so at least 2 uA come from this. In the new verson I added a dual FET to eliminate this current draw. Another 300 nA comes from the MCP1812 LDO. The data sheet specs 5 uA as typical, so 8.9 - ~2 - 0.3 is ~6.6 uA is in the ball park. The average current when the ESP32C3Mini is awake is ~18 mA for ~0.25 seconds; this is without BLE or ESPNow. So I expect running at a 10 minute data update duty cycle will use ~15 uA. Probably a bit more with BLE or ESPNow. In any case, I expect to be able to run this kind of environmental data logger for at least six months on a small (~100 mAH) LiPo battery.  

One oddity is that if I enable USBSerial output by setting SerialDebug = true in every file where USBSerial is called then the sketch works well, sending serial output to the serial monitor. However, upon wake from deep sleep the program stalls unless the serial monitor is closed then opened again. This happens even when running from battery with no USB connected. So in order to run this sketch as a data logger, one has to set SerialDebug to false everywhere then it works just fine.


================================================
FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32.ino
================================================
#include "LSM6DSM.h"
#include "LIS2MDL.h"
#include "LPS22HB.h"
#include "USFS.h"

#define I2C_BUS          Wire                           // Define the I2C bus (Wire instance) you wish to use

I2Cdev                   i2c_0(&I2C_BUS);               // Instantiate the I2Cdev object and point to the desired I2C bus

bool SerialDebug = true;  // set to true to get Serial output for debugging
bool passThru  = false;

#define myLed 5
#define pinGND 12
#define pin3V3 13

void EM7180intHandler();
void myinthandler1();
void myinthandler2();
void myinthandler3();

// global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System)
float pi = 3.141592653589793238462643383279502884f;
float GyroMeasError = pi * (40.0f / 180.0f);   // gyroscope measurement error in rads/s (start at 40 deg/s)
float GyroMeasDrift = pi * (0.0f  / 180.0f);   // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)
float beta = sqrtf(3.0f / 4.0f) * GyroMeasError;   // compute beta
float zeta = sqrtf(3.0f / 4.0f) * GyroMeasDrift;   // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value
uint32_t delt_t = 0;                      // used to control display output rate
uint32_t sumCount = 0;                    // used to control display output rate
float pitch, yaw, roll, Yaw, Pitch, Roll;
float a12, a22, a31, a32, a33;            // rotation matrix coefficients for Euler angles and gravity components
float A112, A22, A31, A32, A33;            // rotation matrix coefficients for Hardware Euler angles and gravity components
float deltat = 0.0f, sum = 0.0f;          // integration interval for both filter schemes
uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval
uint32_t Now = 0;                         // used to calculate integration interval
float lin_ax, lin_ay, lin_az;             // linear acceleration (acceleration with gravity component subtracted)
float lin_Ax, lin_Ay, lin_Az;             // Hardware linear acceleration (acceleration with gravity component subtracted)
float q[4] = {1.0f, 0.0f, 0.0f, 0.0f};    // vector to hold quaternion
float Q[4] = {1.0f, 0.0f, 0.0f, 0.0f};    // hardware quaternion data register
float eInt[3] = {0.0f, 0.0f, 0.0f};       // vector to hold integral error for Mahony method

//LSM6DSM definitions
#define LSM6DSM_intPin1 10  // interrupt1 pin definitions, significant motion
#define LSM6DSM_intPin2 9   // interrupt2 pin definitions, data ready

/* Specify sensor parameters (sample rate is twice the bandwidth)
 * choices are:
      AFS_2G, AFS_4G, AFS_8G, AFS_16G  
      GFS_245DPS, GFS_500DPS, GFS_1000DPS, GFS_2000DPS 
      AODR_12_5Hz, AODR_26Hz, AODR_52Hz, AODR_104Hz, AODR_208Hz, AODR_416Hz, AODR_833Hz, AODR_1660Hz, AODR_3330Hz, AODR_6660Hz
      GODR_12_5Hz, GODR_26Hz, GODR_52Hz, GODR_104Hz, GODR_208Hz, GODR_416Hz, GODR_833Hz, GODR_1660Hz, GODR_3330Hz, GODR_6660Hz
*/ 
uint8_t Ascale = AFS_2G, Gscale = GFS_245DPS, AODR = AODR_208Hz, GODR = GODR_416Hz;

float aRes, gRes;              // scale resolutions per LSB for the accel and gyro sensor2
float accelBias[3] = {-0.00499, 0.01540, 0.02902}, gyroBias[3] = {-0.50, 0.14, 0.28}; // offset biases for the accel and gyro
int16_t LSM6DSMData[7];        // Stores the 16-bit signed sensor output
float   Gtemperature;           // Stores the real internal gyro temperature in degrees Celsius
float ax, ay, az, gx, gy, gz;  // variables to hold latest accel/gyro data values 

bool newLSM6DSMData = false;
bool newLSM6DSMTap  = false;

LSM6DSM LSM6DSM(LSM6DSM_intPin1, LSM6DSM_intPin2, &i2c_0); // instantiate LSM6DSM class


//LIS2MDL definitions
#define LIS2MDL_intPin  8 // interrupt for magnetometer data ready

/* Specify sensor parameters (sample rate is twice the bandwidth)
 * choices are: MODR_10Hz, MOIDR_20Hz, MODR_50 Hz and MODR_100Hz
*/ 
uint8_t MODR = MODR_100Hz;

float mRes = 0.0015f;            // mag sensitivity
float magBias[3] = {0,0,0}, magScale[3]  = {0,0,0}; // Bias corrections for magnetometer
int16_t LIS2MDLData[4];          // Stores the 16-bit signed sensor output
float Mtemperature;              // Stores the real internal chip temperature in degrees Celsius
float mx, my, mz;                // variables to hold latest mag data values 
uint8_t LIS2MDLstatus;

bool newLIS2MDLData = false;

LIS2MDL LIS2MDL(LIS2MDL_intPin, &i2c_0); // instantiate LIS2MDL class


// LPS22H definitions
uint8_t LPS22H_intPin = 5;

/* Specify sensor parameters (sample rate is twice the bandwidth) 
   Choices are P_1Hz, P_10Hz P_25 Hz, P_50Hz, and P_75Hz
 */
uint8_t PODR = P_25Hz;     // set pressure amd temperature output data rate
uint8_t LPS22Hstatus;
float temperature, pressure, altitude;

bool newLPS22HData = false;

LPS22H LPS22H(LPS22H_intPin, &i2c_0);


const uint8_t USFS_intPin = 27;
bool newEM7180Data = false;
int16_t accelCount[3];  // Stores the 16-bit signed accelerometer sensor output
int16_t gyroCount[3];   // Stores the 16-bit signed gyro sensor output
int16_t magCount[3];    // Stores the 16-bit signed magnetometer sensor output
int16_t tempCount, rawPressure, rawTemperature;            // temperature raw count output
float   Temperature, Pressure, Altitude; //  temperature in degrees Celsius, pressure in mbar
float Ax, Ay, Az, Gx, Gy, Gz, Mx, My, Mz; // variables to hold latest sensor data values


/* Choose EM7180, LSM6DSM, LIS2MDL sample rates and bandwidths
   Choices are:
   accBW, gyroBW 0x00 = 250 Hz, 0x01 = 184 Hz, 0x02 = 92 Hz, 0x03 = 41 Hz, 0x04 = 20 Hz, 0x05 = 10 Hz, 0x06 = 5 Hz, 0x07 = no filter (3600 Hz)
   QRtDiv 0x00, 0x01, 0x02, etc quat rate = gyroRt/(1 + QRtDiv)
   magRt 8 Hz = 0x08 or 100 Hz 0x64
   accRt, gyroRt 1000, 500, 250, 200, 125, 100, 50 Hz enter by choosing desired rate
   and dividing by 10, so 200 Hz would be 200/10 = 20 = 0x14
   sample rate of barometer is baroRt/2 so for 25 Hz enter 50 = 0x32
   LSM6DSM accel/gyro rates 0f 833 Hz set Rt variables to 0x53
*/
uint8_t accBW = 0x03, gyroBW = 0x03, QRtDiv = 0x03, magRt = 0x64, accRt = 0x53, gyroRt = 0x53, baroRt = 0x32;
/*
   Choose sensor full ranges
   Choices are 2, 4, 8, 16 g for accFS, 250, 500, 1000, and 2000 dps for gyro FS and 1000 uT for magFS expressed as HEX values
*/
uint16_t accFS = 0x02, gyroFS = 0x7D0, magFS = 0x3E8;

USFS USFS(USFS_intPin, passThru, &i2c_0);


void setup() {  
  Serial.begin(115200);
  delay(4000);

  // Configure led
  pinMode(myLed, OUTPUT);
  digitalWrite(myLed, HIGH); // start with led on

   pinMode(pinGND, OUTPUT);
  digitalWrite(pinGND, LOW);

  pinMode(pin3V3, OUTPUT);
  digitalWrite(pin3V3, HIGH);

  pinMode(USFS_intPin, INPUT);
  
  Wire.begin(16, 15, 400000); //(SDA, SCL) (21,22) are default on ESP32, 400 kHz I2C clock
  delay(1000);
 
  i2c_0.I2Cscan(); // which I2C device are on the bus?

  if(!passThru)
  {
  // Initialize the USFS
  USFS.getChipID();        // check ROM/RAM version of EM7180
  USFS.loadfwfromEEPROM(); // load EM7180 firmware from EEPROM
  USFS.initEM7180(accBW, gyroBW, accFS, gyroFS, magFS, QRtDiv, magRt, accRt, gyroRt, baroRt); // set MPU and MS5637 sensor parameters
  } // end of "if(!passThru)" handling

  if(passThru)
  {
  // Read the LSM6DSM Chip ID register, this is a good test of communication
  Serial.println("LSM6DSM accel/gyro...");
  byte c = LSM6DSM.getChipID();  // Read CHIP_ID register for LSM6DSM
  Serial.print("LSM6DSM "); Serial.print("I AM "); Serial.print(c, HEX); Serial.print(" I should be "); Serial.println(0x6A, HEX);
  Serial.println(" ");
  delay(1000); 

  // Read the LIS2MDL Chip ID register, this is a good test of communication
  Serial.println("LIS2MDL mag...");
  byte d = LIS2MDL.getChipID();  // Read CHIP_ID register for LSM6DSM
  Serial.print("LIS2MDL "); Serial.print("I AM "); Serial.print(d, HEX); Serial.print(" I should be "); Serial.println(0x40, HEX);
  Serial.println(" ");
  delay(1000); 

  Serial.println("LPS22HB barometer...");
  uint8_t e = LPS22H.getChipID();
  Serial.print("LPS25H "); Serial.print("I AM "); Serial.print(e, HEX); Serial.print(" I should be "); Serial.println(0xB1, HEX);
  delay(1000); 
  

  if(c == 0x6A && d == 0x40 && e == 0xB1) // check if all I2C sensors have acknowledged
  {
   Serial.println("LSM6DSM and LIS2MDL and LPS22HB are online..."); Serial.println(" ");
   
   digitalWrite(myLed, LOW);

   LSM6DSM.reset();  // software reset LSM6DSM to default registers

   // get sensor resolutions, only need to do this once
   aRes = LSM6DSM.getAres(Ascale);
   gRes = LSM6DSM.getGres(Gscale);

   LSM6DSM.init(Ascale, Gscale, AODR, GODR);

   LSM6DSM.selfTest();

   LSM6DSM.offsetBias(gyroBias, accelBias);
   Serial.println("accel biases (mg)"); Serial.println(1000.0f * accelBias[0]); Serial.println(1000.0f * accelBias[1]); Serial.println(1000.0f * accelBias[2]);
   Serial.println("gyro biases (dps)"); Serial.println(gyroBias[0]); Serial.println(gyroBias[1]); Serial.println(gyroBias[2]);
   delay(1000); 

   LIS2MDL.reset(); // software reset LIS2MDL to default registers

   mRes = 0.0015f;  // fixed sensitivity and full scale (+/- 49.152 Gauss); 
   
   LIS2MDL.init(MODR);

   LIS2MDL.selfTest();

   LIS2MDL.offsetBias(magBias, magScale);
   Serial.println("mag biases (mG)"); Serial.println(1000.0f * magBias[0]); Serial.println(1000.0f * magBias[1]); Serial.println(1000.0f * magBias[2]); 
   Serial.println("mag scale (mG)"); Serial.println(magScale[0]); Serial.println(magScale[1]); Serial.println(magScale[2]); 
   delay(2000); // add delay to see results before serial spew of data

   LPS22H.Init(PODR);  // Initialize LPS22H altimeter
   delay(1000);

   digitalWrite(myLed, HIGH);
   
  }
  else 
  {
  if(c != 0x6A) Serial.println(" LSM6DSM not functioning!");
  if(d != 0x40) Serial.println(" LIS2MDL not functioning!");    
  if(e != 0xB1) Serial.println(" LPS22HB not functioning!");   

  while(1){};
  }
  }  // end of "if(passThru)" handling


  if(!passThru)
  {
    attachInterrupt(USFS_intPin, EM7180intHandler, RISING);  // define interrupt for INT pin output of EM7180
 
    USFS.checkEM7180Status();
  }

  if(passThru)
  {
  attachInterrupt(LSM6DSM_intPin2, myinthandler1, RISING);  // define interrupt for intPin2 output of LSM6DSM
  attachInterrupt(LIS2MDL_intPin , myinthandler2, RISING);  // define interrupt for intPin  output of LIS2MDL
  attachInterrupt(LPS22H_intPin  , myinthandler3, RISING);  // define interrupt for intPin  output of LPS22HB

  LIS2MDLstatus = LIS2MDL.status();  // read status register to clear interrupt before main loop
  }

  digitalWrite(myLed, LOW); // turn led off when successfully through setup

}

/* End of setup */

void loop() {

   if(passThru)
   {
   // If intPin goes high, either all data registers have new data
   if(newLSM6DSMData == true) {   // On interrupt, read data
      newLSM6DSMData = false;     // reset newData flag

     LSM6DSM.readData(LSM6DSMData); // INT2 cleared on any read
   
   // Now we'll calculate the accleration value into actual g's
     ax = (float)LSM6DSMData[4]*aRes - accelBias[0];  // get actual g value, this depends on scale being set
     ay = (float)LSM6DSMData[5]*aRes - accelBias[1];   
     az = (float)LSM6DSMData[6]*aRes - accelBias[2];  

   // Calculate the gyro value into actual degrees per second
     gx = (float)LSM6DSMData[1]*gRes - gyroBias[0];  // get actual gyro value, this depends on scale being set
     gy = (float)LSM6DSMData[2]*gRes - gyroBias[1];  
     gz = (float)LSM6DSMData[3]*gRes - gyroBias[2]; 

    for(uint8_t i = 0; i < 10; i++) { // iterate a fixed number of times per data read cycle
    Now = micros();
    deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
    lastUpdate = Now;

    sum += deltat; // sum for averaging filter update rate
    sumCount++;

    USFS.MadgwickQuaternionUpdate(-ax, ay, az, gx*pi/180.0f, -gy*pi/180.0f, -gz*pi/180.0f,  mx,  my, -mz);
    }
    
   }

    // If intPin goes high, either all data registers have new data
   if(newLIS2MDLData == true) {   // On interrupt, read data
      newLIS2MDLData = false;     // reset newData flag

     LIS2MDLstatus = LIS2MDL.status();
     
     if(LIS2MDLstatus & 0x08) // if all axes have new data ready
     {
      LIS2MDL.readData(LIS2MDLData);  
   
   // Now we'll calculate the accleration value into actual G's
     mx = (float)LIS2MDLData[0]*mRes - magBias[0];  // get actual G value 
     my = (float)LIS2MDLData[1]*mRes - magBias[1];   
     mz = (float)LIS2MDLData[2]*mRes - magBias[2]; 
     mx *= magScale[0];
     my *= magScale[1];
     mz *= magScale[2];  
     }
   }
   }  // end of "if(passThru)" handling

   if(!passThru)
   {
      /*EM7180*/
  // If intpin goes high, all data registers have new data
  if (newEM7180Data == true) { // On interrupt, read data
    newEM7180Data = false;  // reset newData flag

    // Check event status register, way to chech data ready by polling rather than interrupt
    uint8_t eventStatus = USFS.checkEM7180Status(); // reading clears the register

    // Check for errors
    if (eventStatus & 0x02) { // error detected, what is it?

      uint8_t errorStatus = USFS.checkEM7180Errors();
      if (errorStatus != 0x00) { // is there an error?
        Serial.print(" EM7180 sensor status = "); Serial.println(errorStatus);
        if (errorStatus == 0x11) Serial.print("Magnetometer failure!");
        if (errorStatus == 0x12) Serial.print("Accelerometer failure!");
        if (errorStatus == 0x14) Serial.print("Gyro failure!");
        if (errorStatus == 0x21) Serial.print("Magnetometer initialization failure!");
        if (errorStatus == 0x22) Serial.print("Accelerometer initialization failure!");
        if (errorStatus == 0x24) Serial.print("Gyro initialization failure!");
        if (errorStatus == 0x30) Serial.print("Math error!");
        if (errorStatus == 0x80) Serial.print("Invalid sample rate!");
      }

      // Handle errors ToDo

    }

    // if no errors, see if new data is ready
    if (eventStatus & 0x10) { // new acceleration data available
      USFS.readSENtralAccelData(accelCount);

      // Now we'll calculate the accleration value into actual g's
      Ax = (float)accelCount[0] * 0.000488f; // get actual g value
      Ay = (float)accelCount[1] * 0.000488f;
      Az = (float)accelCount[2] * 0.000488f;
    }

    if (eventStatus & 0x20) { // new gyro data available
      USFS.readSENtralGyroData(gyroCount);

      // Now we'll calculate the gyro value into actual dps's
      Gx = (float)gyroCount[0] * 0.153f; // get actual dps value
      Gy = (float)gyroCount[1] * 0.153f;
      Gz = (float)gyroCount[2] * 0.153f;
    }

    if (eventStatus & 0x08) { // new mag data available
      USFS.readSENtralMagData(magCount);

      // Now we'll calculate the mag value into actual G's
      Mx = (float)magCount[0] * 0.305176f; // get actual G value
      My = (float)magCount[1] * 0.305176f;
      Mz = (float)magCount[2] * 0.305176f;
    }

    if (eventStatus & 0x04) { // new quaternion data available
      USFS.readSENtralQuatData(Q);
    }

    // get MS5637 pressure
    if (eventStatus & 0x40) { // new baro data available
      rawPressure = USFS.readSENtralBaroData();
      Pressure = (float)rawPressure * 0.01f + 1013.25f; // pressure in mBar

      // get MS5637 temperature
      rawTemperature = USFS.readSENtralTempData();
      Temperature = (float) rawTemperature * 0.01f; // temperature in degrees C
    }
  } 
   } // end of "if(!passThru)" handling
   
   // end sensor interrupt handling
    
   if(passThru)
   {
    if(SerialDebug) {
    Serial.print("ax = "); Serial.print((int)1000*ax);  
    Serial.print(" ay = "); Serial.print((int)1000*ay); 
    Serial.print(" az = "); Serial.print((int)1000*az); Serial.println(" mg");
    Serial.print("gx = "); Serial.print( gx, 2); 
    Serial.print(" gy = "); Serial.print( gy, 2); 
    Serial.print(" gz = "); Serial.print( gz, 2); Serial.println(" deg/s");
    Serial.print("mx = "); Serial.print((int)1000*mx);  
    Serial.print(" my = "); Serial.print((int)1000*my); 
    Serial.print(" mz = "); Serial.print((int)1000*mz); Serial.println(" mG");
    
    Serial.print("q0 = "); Serial.print(q[0]);
    Serial.print(" qx = "); Serial.print(q[1]); 
    Serial.print(" qy = "); Serial.print(q[2]); 
    Serial.print(" qz = "); Serial.println(q[3]); 
    }

    // get pressure and temperature from the LPS22HB
    LPS22Hstatus = LPS22H.status();

    if(LPS22Hstatus & 0x01) { // if new pressure data available
    pressure = (float) LPS22H.readAltimeterPressure()/4096.0f;
    temperature = (float) LPS22H.readAltimeterTemperature()/100.0f; 
    
    altitude = 145366.45f*(1.0f - pow((pressure/1013.25f), 0.190284f)); 

      if(SerialDebug) {
      Serial.print("Altimeter temperature = "); Serial.print( temperature, 2); Serial.println(" C"); // temperature in degrees Celsius  
      Serial.print("Altimeter temperature = "); Serial.print(9.0f*temperature/5.0f + 32.0f, 2); Serial.println(" F"); // temperature in degrees Fahrenheit
      Serial.print("Altimeter pressure = "); Serial.print(pressure, 2);  Serial.println(" mbar");// pressure in millibar
      Serial.print("Altitude = "); Serial.print(altitude, 2); Serial.println(" feet");
      }
    }

    Gtemperature = ((float) LSM6DSMData[0]) / 256.0f + 25.0f; // Gyro chip temperature in degrees Centigrade
    // Print temperature in degrees Centigrade      
    if(SerialDebug) {
      Serial.print("Gyro temperature is ");  Serial.print(Gtemperature, 1);  Serial.println(" degrees C"); // Print T values to tenths of s degree C
    }

    LIS2MDLData[3] = LIS2MDL.readTemperature();
    Mtemperature = ((float) LIS2MDLData[3]) / 8.0f + 25.0f; // Mag chip temperature in degrees Centigrade
    // Print temperature in degrees Centigrade      
    if(SerialDebug) {
      Serial.print("Mag temperature is ");  Serial.print(Mtemperature, 1);  Serial.println(" degrees C"); // Print T values to tenths of s degree C
    }

    a12 =   2.0f * (q[1] * q[2] + q[0] * q[3]);
    a22 =   q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3];
    a31 =   2.0f * (q[0] * q[1] + q[2] * q[3]);
    a32 =   2.0f * (q[1] * q[3] - q[0] * q[2]);
    a33 =   q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3];
    pitch = -asinf(a32);
    roll  = atan2f(a31, a33);
    yaw   = atan2f(a12, a22);
    pitch *= 180.0f / pi;
    yaw   *= 180.0f / pi; 
    yaw   += 13.8f; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04
    if(yaw < 0) yaw   += 360.0f; // Ensure yaw stays between 0 and 360
    roll  *= 180.0f / pi;
    lin_ax = ax + a31;
    lin_ay = ay + a32;
    lin_az = az - a33;

    if(SerialDebug) {
    Serial.print("Yaw, Pitch, Roll: ");
    Serial.print(yaw, 2);
    Serial.print(", ");
    Serial.print(pitch, 2);
    Serial.print(", ");
    Serial.println(roll, 2);

    Serial.print("Grav_x, Grav_y, Grav_z: ");
    Serial.print(-a31*1000.0f, 2);
    Serial.print(", ");
    Serial.print(-a32*1000.0f, 2);
    Serial.print(", ");
    Serial.print(a33*1000.0f, 2);  Serial.println(" mg");
    Serial.print("Lin_ax, Lin_ay, Lin_az: ");
    Serial.print(lin_ax*1000.0f, 2);
    Serial.print(", ");
    Serial.print(lin_ay*1000.0f, 2);
    Serial.print(", ");
    Serial.print(lin_az*1000.0f, 2);  Serial.println(" mg");
    
    Serial.print("rate = "); Serial.print((float)sumCount/sum, 2); Serial.println(" Hz");
    }

//     Serial.print(millis()/1000);Serial.print(",");
//     Serial.print(yaw, 2); Serial.print(","); Serial.print(pitch, 2); Serial.print(","); Serial.print(roll, 2); Serial.print(","); Serial.println(Pressure, 2);

    sumCount = 0;
    sum = 0;      

    }  // end of "if(passThru)" handling

    if(!passThru)
    {

      if (SerialDebug) {
      Serial.print("Ax = "); Serial.print((int)1000 * Ax);
      Serial.print(" Ay = "); Serial.print((int)1000 * Ay);
      Serial.print(" Az = "); Serial.print((int)1000 * Az); Serial.println(" mg");
      Serial.print("Gx = "); Serial.print( Gx, 2);
      Serial.print(" Gy = "); Serial.print( Gy, 2);
      Serial.print(" Gz = "); Serial.print( Gz, 2); Serial.println(" deg/s");
      Serial.print("Mx = "); Serial.print( (int)Mx);
      Serial.print(" My = "); Serial.print( (int)My);
      Serial.print(" Mz = "); Serial.print( (int)Mz); Serial.println(" mG");

      Serial.println("Hardware quaternions:");
      Serial.print("Q0 = "); Serial.print(Q[0]);
      Serial.print(" Qx = "); Serial.print(Q[1]);
      Serial.print(" Qy = "); Serial.print(Q[2]);
      Serial.print(" Qz = "); Serial.println(Q[3]);
    }

    //Hardware AHRS:
    A112 =   2.0f * (Q[1] * Q[2] + Q[0] * Q[3]);
    A22 =   Q[0] * Q[0] + Q[1] * Q[1] - Q[2] * Q[2] - Q[3] * Q[3];
    A31 =   2.0f * (Q[0] * Q[1] + Q[2] * Q[3]);
    A32 =   2.0f * (Q[1] * Q[3] - Q[0] * Q[2]);
    A33 =   Q[0] * Q[0] - Q[1] * Q[1] - Q[2] * Q[2] + Q[3] * Q[3];
    Pitch = -asinf(A32);
    Roll  = atan2f(A31, A33);
    Yaw   = atan2f(A112, A22);
    Pitch *= 180.0f / pi;
    Yaw   *= 180.0f / pi;
    Yaw   += 13.8f; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04
    if (Yaw < 0) Yaw   += 360.0f ; // Ensure yaw stays between 0 and 360
    Roll  *= 180.0f / pi;
    lin_Ax = Ax + A31;
    lin_Ay = Ay + A32;
    lin_Az = Az - A33;

    if (SerialDebug) {
      Serial.print("Hardware Yaw, pitch, Roll: ");
      Serial.print(Yaw, 2);
      Serial.print(", ");
      Serial.print(Pitch, 2);
      Serial.print(", ");
      Serial.println(Roll, 2);

      Serial.print("Hardware Grav_x, Grav_y, Grav_z: ");
      Serial.print(-A31 * 1000, 2);
      Serial.print(", ");
      Serial.print(-A32 * 1000, 2);
      Serial.print(", ");
      Serial.print(A33 * 1000, 2);  Serial.println(" mg");
      Serial.print("Hardware Lin_ax, Lin_ay, Lin_az: ");
      Serial.print(lin_Ax * 1000, 2);
      Serial.print(", ");
      Serial.print(lin_Ay * 1000, 2);
      Serial.print(", ");
      Serial.print(lin_Az * 1000, 2);  Serial.println(" mg");

      Serial.println("MS5637:");
      Serial.print("Altimeter temperature = ");
      Serial.print(Temperature, 2);
      Serial.println(" C"); // temperature in degrees Celsius
      Serial.print("Altimeter temperature = ");
      Serial.print(9.0f * Temperature / 5.0f + 32.0f, 2);
      Serial.println(" F"); // temperature in degrees Fahrenheit
      Serial.print("Altimeter pressure = ");
      Serial.print(Pressure, 2);
      Serial.println(" mbar");// pressure in millibar
      Altitude = 145366.45f * (1.0f - powf(((Pressure) / 1013.25f), 0.190284f));
      Serial.print("Altitude = ");
      Serial.print(Altitude, 2);
      Serial.println(" feet");
      Serial.println(" ");
    }
    
    } // end of "if(!passThru)" handling
   
      digitalWrite(myLed, HIGH); delay(1); digitalWrite(myLed, LOW);  // flash led for 10 milliseconds
      delay(500);
 
}  //end of loop

/*  End of main loop */


void myinthandler1()
{
  newLSM6DSMData = true;
}

void myinthandler2()
{
  newLIS2MDLData = true;
}

void myinthandler3()
{
  newLPS22HData = true;
}

void EM7180intHandler()
{
  newEM7180Data = true;
}






================================================
FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/I2Cdev.cpp
================================================
/*
 * Copyright (c) 2018 Tlera Corp.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimers.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimers in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Tlera Corp, nor the names of its contributors
 *     may be used to endorse or promote products derived from this Software
 *     without specific prior written permission.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * WITH THE SOFTWARE.
 */

#include "Arduino.h"
#include "I2Cdev.h"

I2Cdev::I2Cdev(TwoWire* i2c_bus)                                                                                                             // Class constructor
{
  _i2c_bus = i2c_bus;
}

I2Cdev::~I2Cdev()                                                                                                                            // Class destructor
{
}

/**
* @fn: readByte(uint8_t address, uint8_t subAddress)
*
* @brief: Read one byte from an I2C device
* 
* @params: I2C slave device address, Register subAddress
* @returns: unsigned short read
*/
uint8_t I2Cdev::readByte(uint8_t address, uint8_t subAddress)
{
  uint8_t data = 0;                             // `data` will store the register data   
  _i2c_bus->beginTransmission(address);         // Initialize the Tx buffer
  _i2c_bus->write(subAddress);                  // Put slave register address in Tx buffer
  _i2c_bus->endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
  _i2c_bus->requestFrom(address, 1);            // Read one byte from slave register address  
  data = _i2c_bus->read();                      // Fill Rx buffer with result
  return data;                                  // Return data read from slave register
  
}


/**
* @fn: readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
*
* @brief: Read multiple bytes from an I2C device
* 
* @params: I2C slave device address, Register subAddress, number of btes to be read, aray to store the read data
* @returns: void
*/
void I2Cdev::readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
{  
  _i2c_bus->beginTransmission(address);   // Initialize the Tx buffer
  _i2c_bus->write(subAddress);            // Put slave register address in Tx buffer
  _i2c_bus->endTransmission(false);       // Send the Tx buffer, but send a restart to keep connection alive
  uint8_t i = 0;
  _i2c_bus->requestFrom(address, count);  // Read bytes from slave register address 
  while (_i2c_bus->available()) {
        dest[i++] = _i2c_bus->read(); }   // Put read results in the Rx buffer
}


/**
* @fn: writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data)
*
* @brief: Write one byte to an I2C device
* 
* @params: I2C slave device address, Register subAddress, data to be written
* @returns: void
*/
void I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data)
{
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  _i2c_bus->write(regAddr);           // Put slave register address in Tx buffer
  _i2c_bus->write(data);                 // Put data in Tx buffer
  _i2c_bus->endTransmission();           // Send the Tx buffer
}


/**
* @fn: writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t data)
*
* @brief: Write multiple bytes to an I2C device
* 
* @params: I2C slave device address, Register subAddress, byte count, data array to be written
* @returns: void
*/
void I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t count, uint8_t *dest)
{
  uint8_t temp[1 + count];
  
  temp[0] = regAddr;
  for (uint8_t ii = 0; ii < count; ii++)
  { 
    temp[ii + 1] = dest[ii];
  }
  
  _i2c_bus->beginTransmission(devAddr);  // Initialize the Tx buffer
  
  for (uint8_t jj = 0; jj < count + 1; jj++)
  {
  _i2c_bus->write(temp[jj]);            // Put data in Tx buffer
  }
  
  _i2c_bus->endTransmission();           // Send the Tx buffer
}



/**
* @fn:I2Cscan()
* @brief: Scan the I2C bus for active I2C slave devices
* 
* @params: void
* @returns: void
*/
void I2Cdev::I2Cscan() 
{
  // Scan for i2c devices
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  {
    // The i2c_scanner uses the return value of the Wire.endTransmisstion to see if a device did acknowledge to the address.
    _i2c_bus->beginTransmission(address);
    error = _i2c_bus->endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16) 
      Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");
      nDevices++;
    }
    else if (error==4) 
    {
      Serial.print("Unknown error at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.println(address,HEX);
    }    
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("I2C scan complete\n");
}



================================================
FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/I2Cdev.h
================================================
/*
 * Copyright (c) 2018 Tlera Corp.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimers.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimers in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Tlera Corp, nor the names of its contributors
 *     may be used to endorse or promote products derived from this Software
 *     without specific prior written permission.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * WITH THE SOFTWARE.
 */

#ifndef _I2CDEV_H_
#define _I2CDEV_H_

#include <Wire.h>

class I2Cdev {
    public:
                                        I2Cdev(TwoWire*);
                                        ~I2Cdev();                                                                                                                     // Class destructor for durable instances
         uint8_t                        readByte(uint8_t address, uint8_t subAddress);
         void                           readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest);
         void                           writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data);
         void                           writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t count, uint8_t *dest);
         void                           I2Cscan();
         
    private:
         TwoWire*                       _i2c_bus;                                                                                                                      // Class constructor argument
};

#endif //_I2CDEV_H_


================================================
FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LIS2MDL.cpp
================================================
/* 09/23/2017 Copyright Tlera Corporation

    Created by Kris Winer

  This sketch uses SDA/SCL on pins 21/20 (Butterfly default), respectively, and it uses the Butterfly STM32L433CU Breakout Board.
  The LIS2MDL is a low power magnetometer, here used as 3 DoF in a 9 DoF absolute orientation solution.

  Library may be used freely and without limit with attribution.

*/

#include "LIS2MDL.h"

LIS2MDL::LIS2MDL(uint8_t intPin, I2Cdev* i2c_bus)
{
  _intPin = intPin;
  _i2c_bus = i2c_bus;
}


uint8_t LIS2MDL::getChipID()
{
  uint8_t c = _i2c_bus->readByte(LIS2MDL_ADDRESS, LIS2MDL_WHO_AM_I);
  return c;
}


void LIS2MDL::reset()
{
  // reset device
  uint8_t temp = _i2c_bus->readByte(LIS2MDL_ADDRESS, LIS2MDL_CFG_REG_A);
  _i2c_bus->writeByte(LIS2MDL_ADDRESS, LIS2MDL_CFG_REG_A, temp | 0x20); // Set bit 5 to 1 to reset LIS2MDL
  delay(1);
  _i2c_bus->writeByte(LIS2MDL_ADDRESS, LIS2MDL_CFG_REG_A, temp | 0x40); // Set bit 6 to 1 to boot LIS2MDL
  delay(100); // Wait for all registers to reset 
}

void LIS2MDL::init(uint8_t MODR)
{
 // enable temperature compensation (bit 7 == 1), continuous mode (bits 0:1 == 00)
 _i2c_bus->writeByte(LIS2MDL_ADDRESS, LIS2MDL_CFG_REG_A, 0x80 | MODR<<2);  

 // enable low pass filter (bit 0 == 1), set to ODR/4
 _i2c_bus->writeByte(LIS2MDL_ADDRESS, LIS2MDL_CFG_REG_B, 0x01);  

 // enable data ready on interrupt pin (bit 0 == 1), enable block data read (bit 4 == 1)
 _i2c_bus->writeByte(LIS2MDL_ADDRESS, LIS2MDL_CFG_REG_C, 0x01 | 0x10);  
}


uint8_t LIS2MDL::status()
{
  // Read the status register of the altimeter  
  uint8_t temp = _i2c_bus->readByte(LIS2MDL_ADDRESS, LIS2MDL_STATUS_REG);   
  return temp;
}


void LIS2MDL::readData(int16_t * destination)
{
  uint8_t rawData[6];  // x/y/z mag register data stored here
  _i2c_bus->readBytes(LIS2MDL_ADDRESS, (0x80 | LIS2MDL_OUTX_L_REG), 8, &rawData[0]);  // Read the 6 raw data registers into data array

  destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  
  destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; 
}


int16_t LIS2MDL::readTemperature()
{
  uint8_t rawData[2];  // x/y/z mag register data stored here
  _i2c_bus->readBytes(LIS2MDL_ADDRESS, (0x80 | LIS2MDL_TEMP_OUT_L_REG), 2, &rawData[0]);  // Read the 8 raw data registers into data array
  int16_t temp = ((int16_t)rawData[1] << 8) | rawData[0] ;       // Turn the MSB and LSB into a signed 16-bit value
  return temp;
}


void LIS2MDL::offsetBias(float * dest1, float * dest2)
{
  int32_t mag_bias[3] = {0, 0, 0}, mag_scale[3] = {0, 0, 0};
  int16_t mag_max[3] = {-32767, -32767, -32767}, mag_min[3] = {32767, 32767, 32767}, mag_temp[3] = {0, 0, 0};
  float _mRes = 0.0015f;
  
  Serial.println("Calculate mag offset bias: move all around to sample the complete response surface!");
  delay(4000);

  for (int ii = 0; ii < 4000; ii++)
  {
    readData(mag_temp);
       for (int jj = 0; jj < 3; jj++) {
      if(mag_temp[jj] > mag_max[jj]) mag_max[jj] = mag_temp[jj];
      if(mag_temp[jj] < mag_min[jj]) mag_min[jj] = mag_temp[jj];
    }
    delay(12);
  }

  _mRes = 0.0015f; // fixed sensitivity
    // Get hard iron correction
    mag_bias[0]  = (m
Download .txt
gitextract_wmdjks10/

├── Bosch/
│   ├── BME280_VEML6040_LTSleep.ino
│   ├── BNO055_MS5637.ino
│   └── readme.md
├── CCS811_BME280_ESP32C3Mini_WebServer/
│   ├── BME280.cpp
│   ├── BME280.h
│   ├── CCS811.cpp
│   ├── CCS811.h
│   ├── CCS811_BME280_ESP32C3Mini_WebServer.ino
│   ├── I2CDev.cpp
│   ├── I2CDev.h
│   └── Readme.md
├── CCS811_BME280_ESP32C3Mini_deepSleep/
│   ├── BME280.cpp
│   ├── BME280.h
│   ├── CCS811.cpp
│   ├── CCS811.h
│   ├── CCS811_BME280_ESP32C3Mini_deepSleep.ino
│   ├── I2CDev.cpp
│   ├── I2CDev.h
│   └── Readme.md
├── EM7180/
│   ├── EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/
│   │   ├── EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32.ino
│   │   ├── I2Cdev.cpp
│   │   ├── I2Cdev.h
│   │   ├── LIS2MDL.cpp
│   │   ├── LIS2MDL.h
│   │   ├── LPS22HB.cpp
│   │   ├── LPS22HB.h
│   │   ├── LSM6DSM.cpp
│   │   ├── LSM6DSM.h
│   │   ├── USFS.cpp
│   │   └── USFS.h
│   └── Readme.md
├── ESP32C3MiniEnvSensor/
│   ├── ESP32C3Mini_EnvSensor.v02b/
│   │   ├── APDS9253.cpp
│   │   ├── APDS9253.h
│   │   ├── ESP32C3Mini_EnvSensor.v02b.ino
│   │   ├── HDC2010.cpp
│   │   ├── HDC2010.h
│   │   ├── I2Cdev.cpp
│   │   ├── I2Cdev.h
│   │   ├── LPS22HB.cpp
│   │   ├── LPS22HB.h
│   │   ├── SPIFlash.cpp
│   │   └── SPIFlash.h
│   ├── Readme.md
│   ├── SPIFlash_ESP32C3Mini/
│   │   └── SPIFlash_ESP32C3Mini.ino
│   └── readSPIFlash_ESP32C3Mini_EnvSensor.v02b/
│       ├── SPIFlash.cpp
│       ├── SPIFlash.h
│       └── readSPIFlash_ESP32C3Mini_EnvSensor.v02b.ino
├── MPU9250_MS5637/
│   ├── MPU9250_MS5637_AHRS.ino
│   ├── MS5637.ino
│   ├── quaternionFilters.ino
│   └── readme.md
├── MPU9250_MS5637_AHRS_UDP/
│   ├── MPU9250_MS5637_AHRS_UDP.ino
│   ├── quaternionFilters.ino
│   └── readme.md
├── PWM/
│   ├── ledcWrite_demo_ESP32.ino
│   └── readme.md
├── README.md
├── SPI/
│   ├── Readme.md
│   └── SPIFlash_ESP32.ino
├── VISHAY/
│   ├── VEML6040.ino
│   └── readme.md
├── VL53L0x/
│   ├── VL53L0X_ESP32.ino
│   └── readme.md
└── extras/
    └── FreeIMU_cube_UDP_ES32/
        ├── AverageCompassVals.pde
        ├── FreeIMU_cube_UDP_ES32.pde
        ├── Kalman.pde
        ├── MathUtils.java
        ├── MotionDetect.pde
        ├── ODO.pde
        ├── Quaternion.java
        ├── SMA.pde
        ├── StopWatch.pde
        ├── Unused.pde
        ├── code/
        │   └── RXTXcomm.jar
        └── data/
            ├── ArialMT-10.vlw
            └── CourierNew36.vlw
Download .txt
SYMBOL INDEX (89 symbols across 19 files)

FILE: CCS811_BME280_ESP32C3Mini_WebServer/BME280.h
  function class (line 83) | class BME280

FILE: CCS811_BME280_ESP32C3Mini_WebServer/CCS811.h
  function class (line 35) | class CCS811

FILE: CCS811_BME280_ESP32C3Mini_WebServer/I2CDev.h
  function class (line 34) | class I2Cdev {

FILE: CCS811_BME280_ESP32C3Mini_deepSleep/BME280.h
  function class (line 83) | class BME280

FILE: CCS811_BME280_ESP32C3Mini_deepSleep/CCS811.h
  function class (line 35) | class CCS811

FILE: CCS811_BME280_ESP32C3Mini_deepSleep/I2CDev.h
  function class (line 34) | class I2Cdev {

FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/I2Cdev.h
  function class (line 34) | class I2Cdev {

FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LIS2MDL.h
  function class (line 53) | class LIS2MDL

FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LPS22HB.h
  function class (line 55) | class LPS22H

FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LSM6DSM.h
  function class (line 157) | class LSM6DSM

FILE: EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/USFS.h
  function class (line 86) | class USFS

FILE: ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/APDS9253.h
  function class (line 78) | class APDS9253{

FILE: ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/HDC2010.h
  function class (line 85) | class HDC2010

FILE: ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/I2Cdev.h
  function class (line 34) | class I2Cdev {

FILE: ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/LPS22HB.h
  function class (line 72) | class LPS22HB

FILE: ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/SPIFlash.h
  function class (line 58) | class SPIFlash

FILE: ESP32C3MiniEnvSensor/readSPIFlash_ESP32C3Mini_EnvSensor.v02b/SPIFlash.h
  function class (line 57) | class SPIFlash

FILE: extras/FreeIMU_cube_UDP_ES32/MathUtils.java
  class MathUtils (line 33) | public class MathUtils /**implements PConstants*/ {
    method projectVectorOnAxis (line 40) | public static PVector projectVectorOnAxis(PVector src, PVector directi...
    method projectVectorOnPlane (line 55) | public static PVector projectVectorOnPlane(PVector src, PVector normal) {
    method squaredNorm (line 67) | public static float squaredNorm(PVector v) {
    method orthogonalVector (line 77) | public static PVector orthogonalVector(PVector v) {
    method fromMatrix (line 93) | public static final PMatrix3D fromMatrix(float[][] m) {
    method fromOpenGLMatrix (line 103) | public static final PMatrix3D fromOpenGLMatrix(float[][] matrix) {
    method fromArray (line 111) | public static final PMatrix3D fromArray(float[] a) {
    method fromOpenGLArray (line 120) | public static final PMatrix3D fromOpenGLArray(float[] array) {
    method toMatrix (line 128) | public static final float[][] toMatrix(PMatrix3D pM) {
    method toOpenGLArray (line 138) | public static final float[] toOpenGLArray(PMatrix3D pM) {
    method toOpenGLMatrix (line 146) | public static final float[][] toOpenGLMatrix(PMatrix3D pM) {
    method transpose3x3Matrix (line 153) | public static final float[][] transpose3x3Matrix(float[][] m) {
    method transpose4x4Matrix (line 164) | public static final float[][] transpose4x4Matrix(float[][] m) {
    method fromArrayTo4x4Matrix (line 176) | public static final float[][] fromArrayTo4x4Matrix(float[] m) {
    method from4x4MatrixToArray (line 189) | public static final float[] from4x4MatrixToArray(float[][] mat) {
    method get3x3UpperLeftMatrixFromPMatrix3D (line 201) | public static final float[][] get3x3UpperLeftMatrixFromPMatrix3D(PMatr...

FILE: extras/FreeIMU_cube_UDP_ES32/Quaternion.java
  class Quaternion (line 36) | public class Quaternion extends PApplet {
    method Quaternion (line 64) | public Quaternion () {
    method Quaternion (line 76) | public Quaternion (float x, float y, float z, float w) {
    method Quaternion (line 96) | public Quaternion(float x, float y, float z, float w, boolean normaliz...
    method Quaternion (line 123) | public Quaternion(float[] q) {
    method Quaternion (line 133) | public Quaternion(float[] q, boolean normalize) {
    method Quaternion (line 162) | public Quaternion(Quaternion q1) {
    method Quaternion (line 173) | public Quaternion(Quaternion q1, boolean normalize) {
    method set (line 182) | public void set(Quaternion q1) {
    method set (line 190) | public void set(Quaternion q1, boolean normalize) {
    method Quaternion (line 210) | public Quaternion(PVector axis, float angle) {
    method Quaternion (line 225) | public Quaternion(PVector from, PVector to) {
    method conjugate (line 232) | public final void conjugate() {
    method conjugate (line 244) | public final void conjugate(Quaternion q1) {
    method negate (line 254) | public final void negate() {
    method dotProduct (line 269) | public final float dotProduct(Quaternion b) {
    method dotProduct (line 283) | public final static float dotProduct(Quaternion a, Quaternion b) {
    method multiply (line 294) | public final void multiply(Quaternion q1) {
    method multiply (line 315) | public final static Quaternion multiply(Quaternion q1, Quaternion q2) {
    method multiply (line 334) | public final PVector multiply(PVector v) {
    method multiply (line 351) | public static final PVector multiply(Quaternion q1, PVector v) {
    method multiplyInverse (line 363) | public final void multiplyInverse(Quaternion q1) {
    method multiplyInverse (line 379) | public static final Quaternion multiplyInverse(Quaternion q1, Quaterni...
    method inverse (line 396) | public final Quaternion inverse() {
    method invert (line 407) | public final void invert() {
    method invert (line 421) | public final void invert(Quaternion q1) {
    method normalize (line 433) | public final float normalize() {
    method rotate (line 456) | public final PVector rotate(PVector v) {
    method inverseRotate (line 485) | public final PVector inverseRotate(PVector v) {
    method fromAxisAngle (line 503) | public void fromAxisAngle(PVector axis, float angle) {
    method fromTaitBryan (line 523) | public void fromTaitBryan(PVector angles) {
    method fromTaitBryan (line 530) | public void fromTaitBryan(float roll, float pitch, float yaw) {
    method fromEulerAngles (line 541) | public void fromEulerAngles(PVector angles) {
    method fromEulerAngles (line 563) | public void fromEulerAngles(float roll, float pitch, float yaw) {
    method taitBryanAngles (line 575) | public PVector taitBryanAngles() {
    method eulerAngles (line 597) | public PVector eulerAngles() {
    method fromTo (line 649) | public void fromTo(PVector from, PVector to) {
    method fromRotationMatrix (line 689) | public final void fromRotationMatrix(float m[][]) {
    method fromMatrix (line 731) | public final void fromMatrix(PMatrix3D pM) {
    method fromRotatedBasis (line 752) | public final void fromRotatedBasis(PVector X, PVector Y, PVector Z) {
    method axis (line 775) | public final PVector axis() {
    method angle (line 799) | public final float angle() {
    method rotationMatrix (line 813) | public final float[][] rotationMatrix() {
    method matrix (line 823) | public final PMatrix3D matrix() {
    method inverseMatrix (line 871) | public final PMatrix3D inverseMatrix() {
    method inverseRotationMatrix (line 882) | public final float[][] inverseRotationMatrix() {
    method log (line 891) | public final Quaternion log() {
    method exp (line 910) | public final Quaternion exp() {
    method randomQuaternion (line 932) | public final static Quaternion randomQuaternion() {
    method slerp (line 949) | public static final Quaternion slerp(Quaternion a, Quaternion b, float...
    method slerp (line 973) | public static final Quaternion slerp(Quaternion a, Quaternion b, float t,
    method squad (line 1020) | public static final Quaternion squad(Quaternion a, Quaternion tgA,
    method lnDif (line 1037) | public static final Quaternion lnDif(Quaternion a, Quaternion b) {
    method squadTangent (line 1056) | public static final Quaternion squadTangent(Quaternion before,
    method squaredNorm (line 1073) | public static float squaredNorm(Quaternion q) {
Condensed preview — 76 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (650K chars).
[
  {
    "path": "Bosch/BME280_VEML6040_LTSleep.ino",
    "chars": 23624,
    "preview": "/* BME280 and VEML6040 Basic Example Code using ESP32\n by: Kris Winer\n date: December 14, 2016\n license: Beerware - Use "
  },
  {
    "path": "Bosch/BNO055_MS5637.ino",
    "chars": 50763,
    "preview": "/* BNO055_MS5637_ESP32 Basic Example Code\n by: Kris Winer\n date: December 14, 2016\n license: Beerware - Use this code ho"
  },
  {
    "path": "Bosch/readme.md",
    "chars": 311,
    "preview": "Collection of sketches for Bosch sensors. I use [this](https://www.tindie.com/products/onehorse/bno-055-9-axis-motion-se"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/BME280.cpp",
    "chars": 7178,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n This sketch uses SDA/SCL on pins 42/4"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/BME280.h",
    "chars": 2951,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n This sketch uses SDA/SCL on pins 42/4"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/CCS811.cpp",
    "chars": 6029,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n *  The AMS CCS811 is an air quality s"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/CCS811.h",
    "chars": 1390,
    "preview": "#ifndef CCS811_h\r\n#define CCS811_h\r\n\r\n#include \"Arduino.h\"\r\n#include \"Wire.h\"\r\n#include \"I2Cdev.h\"\r\n\r\n/* CCS811 Register"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/CCS811_BME280_ESP32C3Mini_WebServer.ino",
    "chars": 15344,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n *  The AMS CCS811 is an air quality s"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/I2CDev.cpp",
    "chars": 6745,
    "preview": "/*\r\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/I2CDev.h",
    "chars": 2771,
    "preview": "/*\r\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_WebServer/Readme.md",
    "chars": 1648,
    "preview": "Environmental Monitoring sketch\n\nDemonstration of a simple webserver pushing data from BME280 (pressure, temperature, hu"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/BME280.cpp",
    "chars": 7370,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n This sketch uses SDA/SCL on pins 42/4"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/BME280.h",
    "chars": 2951,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n This sketch uses SDA/SCL on pins 42/4"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/CCS811.cpp",
    "chars": 6699,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n *  The AMS CCS811 is an air quality s"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/CCS811.h",
    "chars": 1390,
    "preview": "#ifndef CCS811_h\r\n#define CCS811_h\r\n\r\n#include \"Arduino.h\"\r\n#include \"Wire.h\"\r\n#include \"I2Cdev.h\"\r\n\r\n/* CCS811 Register"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/CCS811_BME280_ESP32C3Mini_deepSleep.ino",
    "chars": 12269,
    "preview": "/* 06/16/2017 Copyright Tlera Corporation\r\n *  \r\n *  Created by Kris Winer\r\n *  \r\n *  The AMS CCS811 is an air quality s"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/I2CDev.cpp",
    "chars": 6906,
    "preview": "/*\r\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/I2CDev.h",
    "chars": 2771,
    "preview": "/*\r\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "CCS811_BME280_ESP32C3Mini_deepSleep/Readme.md",
    "chars": 2255,
    "preview": "Sketch showing how to use the ESP32C3Mini1 as an environmental data logger. \n\nI am using a custom ESP32C3Mini1 developme"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32.ino",
    "chars": 23119,
    "preview": "#include \"LSM6DSM.h\"\n#include \"LIS2MDL.h\"\n#include \"LPS22HB.h\"\n#include \"USFS.h\"\n\n#define I2C_BUS          Wire         "
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/I2Cdev.cpp",
    "chars": 6056,
    "preview": "/*\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any pe"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/I2Cdev.h",
    "chars": 2650,
    "preview": "/*\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any pe"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LIS2MDL.cpp",
    "chars": 5888,
    "preview": "/* 09/23/2017 Copyright Tlera Corporation\n\n    Created by Kris Winer\n\n  This sketch uses SDA/SCL on pins 21/20 (Butterfl"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LIS2MDL.h",
    "chars": 2489,
    "preview": "/* 09/23/2017 Copyright Tlera Corporation\r\n\r\n    Created by Kris Winer\r\n\r\n  This sketch uses SDA/SCL on pins 21/20 (Butt"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LPS22HB.cpp",
    "chars": 1991,
    "preview": "/* 09/23/2017 Copyright Tlera Corporation\n\n    Created by Kris Winer\n\n  This sketch uses SDA/SCL on pins 21/20 (Butterfl"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LPS22HB.h",
    "chars": 2259,
    "preview": "/* 09/23/2017 Copyright Tlera Corporation\n\n    Created by Kris Winer\n\n  This sketch uses SDA/SCL on pins 21/20 (Butterfl"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LSM6DSM.cpp",
    "chars": 8229,
    "preview": "/* 09/23/2017 Copyright Tlera Corporation\n\n    Created by Kris Winer\n\n  This sketch uses SDA/SCL on pins 21/20 (Butterfl"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/LSM6DSM.h",
    "chars": 6865,
    "preview": "/* 09/23/2017 Copyright Tlera Corporation\n\n    Created by Kris Winer\n\n  This sketch uses SDA/SCL on pins 21/20 (Butterfl"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/USFS.cpp",
    "chars": 35535,
    "preview": "/* 06/29/2017 Copyright Tlera Corporation\n *  \n *  Created by Kris Winer\n *  \n *  \n *  Library may be used freely and wi"
  },
  {
    "path": "EM7180/EM7180_LSM6DSM_LIS2MDL_LPS22HB_ESP32/USFS.h",
    "chars": 6505,
    "preview": "#ifndef USFS_h\n#define USFSh_h\n\n#include \"Arduino.h\"\n#include \"Wire.h\"\n#include \"I2Cdev.h\"   \n\n// EM7180 SENtral registe"
  },
  {
    "path": "EM7180/Readme.md",
    "chars": 257,
    "preview": "\nSketch for the [Ultimate Sensor Fusion Solution](https://www.tindie.com/products/onehorse/ultimate-sensor-fusion-soluti"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/APDS9253.cpp",
    "chars": 3338,
    "preview": "/******************************************************************************\r\n *\r\n * Copyright (c) 2021 Tlera Corpora"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/APDS9253.h",
    "chars": 2612,
    "preview": "/******************************************************************************\r\n *\r\n * Copyright (c) 2021 Tlera Corpora"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/ESP32C3Mini_EnvSensor.v02b.ino",
    "chars": 19337,
    "preview": "/* ESP32 C3 Mini Environmental Sensor\r\n \r\n   This example code is in the public domain.\r\n*/\r\n#include \"Arduino.h\"\r\n#incl"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/HDC2010.cpp",
    "chars": 5327,
    "preview": "/*\r\n * Copyright (c) 2021 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/HDC2010.h",
    "chars": 4001,
    "preview": "/*\r\n * Copyright (c) 2021 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/I2Cdev.cpp",
    "chars": 5318,
    "preview": "/*\r\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/I2Cdev.h",
    "chars": 2705,
    "preview": "/*\r\n * Copyright (c) 2018 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/LPS22HB.cpp",
    "chars": 4051,
    "preview": "/*\r\n * Copyright (c) 2021 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/LPS22HB.h",
    "chars": 3303,
    "preview": "/*\r\n * Copyright (c) 2021 Tlera Corp.  All rights reserved.\r\n *\r\n * Permission is hereby granted, free of charge, to any"
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/SPIFlash.cpp",
    "chars": 10269,
    "preview": "/* SPIFlash.cpp\r\nSketch by Kris Winer December 16. 2016\r\n\r\nLicense: Use this sketch any way you choose; if you like it, "
  },
  {
    "path": "ESP32C3MiniEnvSensor/ESP32C3Mini_EnvSensor.v02b/SPIFlash.h",
    "chars": 3076,
    "preview": "/* SPIFlash.h\r\nSketch by Kris Winer December 16. 2016\r\n\r\nLicense: Use this sketch any way you choose; if you like it, bu"
  },
  {
    "path": "ESP32C3MiniEnvSensor/Readme.md",
    "chars": 5859,
    "preview": "**ESP32C3Mini-hosted environmental data logger**\n\nThe idea is to use the remarkably [cheap](https://www.digikey.com/en/p"
  },
  {
    "path": "ESP32C3MiniEnvSensor/SPIFlash_ESP32C3Mini/SPIFlash_ESP32C3Mini.ino",
    "chars": 13533,
    "preview": "/* SPIFlash_ESP32C3Mini SPIFlash Test\r\nSketch by Kris Winer December 16. 2016\r\n\r\nLicense: Use this sketch any way you ch"
  },
  {
    "path": "ESP32C3MiniEnvSensor/readSPIFlash_ESP32C3Mini_EnvSensor.v02b/SPIFlash.cpp",
    "chars": 10205,
    "preview": "/* SPIFlash.cpp\r\nSketch by Kris Winer December 16. 2016\r\n\r\nLicense: Use this sketch any way you choose; if you like it, "
  },
  {
    "path": "ESP32C3MiniEnvSensor/readSPIFlash_ESP32C3Mini_EnvSensor.v02b/SPIFlash.h",
    "chars": 3074,
    "preview": "/* SPIFlash.h\r\nSketch by Kris Winer December 16. 2016\r\n\r\nLicense: Use this sketch any way you choose; if you like it, bu"
  },
  {
    "path": "ESP32C3MiniEnvSensor/readSPIFlash_ESP32C3Mini_EnvSensor.v02b/readSPIFlash_ESP32C3Mini_EnvSensor.v02b.ino",
    "chars": 5864,
    "preview": "/* readSPIFlash_ESP32C3Mini_EnvSensor.v02b\r\n *  \r\n2021 Copyright Tlera Corporation \r\n\r\nApril 30, 2022\r\n\r\nSketch to read "
  },
  {
    "path": "MPU9250_MS5637/MPU9250_MS5637_AHRS.ino",
    "chars": 57499,
    "preview": "/* MPU9250_MS5637_ESP32 Basic Example Code\n by: Kris Winer\n date: December 14, 2016\n license: Beerware - Use this code h"
  },
  {
    "path": "MPU9250_MS5637/MS5637.ino",
    "chars": 9573,
    "preview": "#include \"Wire.h\"   \n\n// See MS5637-02BA03 Low Voltage Barometric Pressure Sensor Data Sheet\n#define MS5637_RESET      0"
  },
  {
    "path": "MPU9250_MS5637/quaternionFilters.ino",
    "chars": 9411,
    "preview": "// Implementation of Sebastian Madgwick's \"...efficient orientation filter for... inertial/magnetic sensor arrays\"\n// (s"
  },
  {
    "path": "MPU9250_MS5637/readme.md",
    "chars": 523,
    "preview": "Sketch for the MPU9250 9 DoF motion sensor including open-source sensor fusion using either the Madgwick or Mahony algor"
  },
  {
    "path": "MPU9250_MS5637_AHRS_UDP/MPU9250_MS5637_AHRS_UDP.ino",
    "chars": 61695,
    "preview": "/* MPU9250_MS5637_ESP32 Basic Example Code\n by: Kris Winer\n date: December 14, 2016\n license: Beerware - Use this code h"
  },
  {
    "path": "MPU9250_MS5637_AHRS_UDP/quaternionFilters.ino",
    "chars": 9420,
    "preview": "\n// Implementation of Sebastian Madgwick's \"...efficient orientation filter for... inertial/magnetic sensor arrays\"\n// ("
  },
  {
    "path": "MPU9250_MS5637_AHRS_UDP/readme.md",
    "chars": 523,
    "preview": "Sketch for the MPU9250 9 DoF motion sensor including open-source sensor fusion using either the Madgwick or Mahony algor"
  },
  {
    "path": "PWM/ledcWrite_demo_ESP32.ino",
    "chars": 3484,
    "preview": "/*\n  ledcWrite_demo_ESP32.ino\n  Runs through the full 255 color spectrum for an rgb led \n  Demonstrate ledcWrite functio"
  },
  {
    "path": "PWM/readme.md",
    "chars": 323,
    "preview": "Sketch using the ledcWrite utility to sweep through 256 colors of an rgb led using pins 12, 13, and 14 with setup as fol"
  },
  {
    "path": "README.md",
    "chars": 643,
    "preview": "# ESP32 Arduino sketch repository\n\nThese are sketches I have found to run on my own 1.4\" x 0.7\" ESP32 development board "
  },
  {
    "path": "SPI/Readme.md",
    "chars": 3299,
    "preview": "I use [this](https://www.tindie.com/products/onehorse/spi-flash-memory-add-ons-for-teensy-3x/) for the SPI NOR flash add"
  },
  {
    "path": "SPI/SPIFlash_ESP32.ino",
    "chars": 11005,
    "preview": "/* SPIFlash_ESP32.ino\nSketch by Kris Winer December 16, 2016\n\nLicense: Use this sketch any way you choose; if you like i"
  },
  {
    "path": "VISHAY/VEML6040.ino",
    "chars": 6829,
    "preview": "/* VEML6040 Basic Example Code\n by: Kris Winer\n date: December 14, 2016\n license: Beerware - Use this code however you'd"
  },
  {
    "path": "VISHAY/readme.md",
    "chars": 310,
    "preview": "Sketch for the VEML6040 RGBW ambient light sensor. I use [this](https://www.tindie.com/products/onehorse/veml6040-rgbw-c"
  },
  {
    "path": "VL53L0x/VL53L0X_ESP32.ino",
    "chars": 4518,
    "preview": "/* This example shows how to use continuous mode to take\nrange measurements with the VL53L0X. It is based on\nvl53l0x_Con"
  },
  {
    "path": "VL53L0x/readme.md",
    "chars": 453,
    "preview": "Sketch to read the time-of-flight ranging sensor VL53L0X with 200 cm range and better than 1% accuracy. I use [this](htt"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/AverageCompassVals.pde",
    "chars": 2908,
    "preview": "/*==============================================================================\r\n \r\n Copyright (c) 2010-2013 Christophe"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/FreeIMU_cube_UDP_ES32.pde",
    "chars": 15753,
    "preview": "/**\r\nVisualize a cube which will assumes the orientation described\r\nin a quaternion coming from the serial port.\r\n\r\nINST"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/Kalman.pde",
    "chars": 413,
    "preview": "public class MyKalman {\r\n//private float Q = 0.001;\r\n//private float R = 0.1;\r\nprivate float Q = 0.0000005;\r\nprivate flo"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/MathUtils.java",
    "chars": 7204,
    "preview": "\r\n/**\r\n *                     ProScene (version 1.1.1)      \r\n *    Copyright (c) 2010-2012 by National University of Co"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/MotionDetect.pde",
    "chars": 2340,
    "preview": "public float MotionDetect() {\r\n  \r\n    /*###################################################################\r\n    \r\n    "
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/ODO.pde",
    "chars": 5894,
    "preview": "\r\n/**************************************************************************\r\n//This function allows movement end detec"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/Quaternion.java",
    "chars": 31059,
    "preview": "\r\n/**\r\n *                     ProScene (version 1.1.1)      \r\n *    Copyright (c) 2010-2012 by National University of Co"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/SMA.pde",
    "chars": 1119,
    "preview": "\r\nimport java.util.LinkedList;\r\nimport java.util.Queue;\r\npublic class MovingAverage {\r\n    private final Queue<Float> wi"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/StopWatch.pde",
    "chars": 880,
    "preview": "// This class based on code found here: http://www.goldb.org/stopwatchjava.html\r\n// http://forum.processing.org/one/topi"
  },
  {
    "path": "extras/FreeIMU_cube_UDP_ES32/Unused.pde",
    "chars": 4932,
    "preview": "/*\r\n//****************************************************************************\r\n//The purpose of the calibration rou"
  }
]

// ... and 3 more files (download for full content)

About this extraction

This page contains the full source code of the kriswiner/ESP32 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 76 files (602.6 KB), approximately 194.5k tokens, and a symbol index with 89 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!