// Method to read a 16-bit value from a register and return it in little endian format private UInt16 ReadUInt16_LittleEndian(byte register) { byte[] writeBuffer = new byte[] { register }; byte[] readBuffer = new byte[] { 0x00, 0x00 }; bme280.WriteRead(writeBuffer, readBuffer); int h = readBuffer[1] << 8; int l = readBuffer[0]; UInt16 value = (UInt16)(h + l); return(value); }
// Method to initialize the BME280 sensor using the I2C interface public async Task InitializeDevice() { Debug.WriteLine("BME280::Initializing device with I2C interface"); try { bme280 = new I2CDevicePI(bus, BME280_Address); if (bme280 == null) // Check if a device was found at the slave address provided by BME280_Address { Debug.WriteLine("Device not found"); return; } else // Since we found a device, let's verify that it is a BME280 by looking at the signature { Debug.WriteLine("BME280::Verifying device signature"); var WriteBuffer = new byte[] { (byte)Registers.BME280_REGISTER_CHIPID }; // This register stores the signature value var ReadBuffer = new byte[] { 0xFF }; // Initialized to an arbitrary number bme280.WriteRead(WriteBuffer, ReadBuffer); // Read the device signature and store in ReadBuffer[0] if (ReadBuffer[0] != BME280_Signature) // Verify the device signature { Debug.WriteLine("BME280::Signature mismatch"); return; } Debug.WriteLine("BME280::Getting device ready"); // As per the data sheet's instructions, we need some stuff before we can // start taking measurements using the BME280's registers. await ReadCalibrationCoefficients(); // Read the compensation coefficients from the factory await WriteControlRegister(); // Write to the control register await WriteControlRegisterHumidity(); // Write to the humidity control register Debug.WriteLine("BME280::Device is ready"); } init = true; } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace); throw; } }