Matt Speakman
Published © Apache-2.0

Raspberry Pi I2C Humidity and Temperature Sensor

Uses C# and the UWP to poll a Honeywell HIH6120 for the data and then performs the math operations to the data received.

IntermediateFull instructions provided12 hours3,529
Raspberry Pi I2C Humidity and Temperature Sensor

Things used in this project

Hardware components

Raspberry Pi 2 Model B
Raspberry Pi 2 Model B
×1
Honeywell HIH 6120
×1

Software apps and online services

Windows 10 IoT Core
Microsoft Windows 10 IoT Core

Story

Read more

Code

InitI2CDevice

C#
At the moment it is a private async method that reads from the I2C device which is a Honeywell 6120 Temp and Humidity sensor
private async void InitI2cDevice()
  {
      // Create a new settings object passing the address
      var settings = new I2cConnectionSettings(0x27);
      settings.BusSpeed = I2cBusSpeed.FastMode;

      // Get all of the I2C devices on this bus
      string aqs = I2cDevice.GetDeviceSelector();
      var dis = await DeviceInformation.FindAllAsync(aqs);

      // Retrieve the I2C device we want using the settings created
      var honeywell = await I2cDevice.FromIdAsync(dis[0].Id, settings);

      try
      {
          // An empty array of bytes to read the response into
          byte[] readBuff = new byte[4];
          // The address of the device as a byte array
          byte[] regAddrBuff = new byte[] { 0x27 };

          // Perform the Write and the Read Operation
          honeywell.WriteRead(regAddrBuff, readBuff);

          // This is the basic math operation needed to do the conversion
          // 2 to the power of 14 minus 2
          var multiplier = Math.Pow(2, 14) - 2;

          // Need to do a bitwise comparison to only retrieve the bits we need and to do the math operation as a 14 bit UINT is returned
          // Also changes a textbox text called Humidity to the value
          this.Humidity.Text = (((readBuff[0] & 0x3f) << 8 | readBuff[1]) * 100.0 /multiplier).ToString();

// Take readBuff[2] and advance it by 6 bits
// Then take readBuff[3] and move it back 2 bits
// This gives us a 14 bit integer which is what we are after
          double measurement = (readBuff[2] << 6) | (readBuff[3] >> 2);
          double celsius = ((measurement / multiplier) * 165) - 40;

          data.Celsius = (int)celsius;
          this.Celsius.Text = celsius.ToString();
          // Fahrenheit for ease of use
          this.Fahrenheit.Text = (celsius * 1.8 + 32).ToString();
      }
      /* If the write fails do nothing */
      catch (Exception)
      {
      }

      finally
      {
          // Call the dispose method which takes care of telling the device to stop sending signals
          I2CAccel.Dispose();
      }
  }

Credits

Matt Speakman

Matt Speakman

1 project • 5 followers
.NET MVC Web developer by day. Raspberry Pi by night!!!!

Comments