I2C Sensors

Some sensors can only be interfaced with microcontrollers via the I2C protocol.

These include sensors such as UV light, inertial measurement unit (IMUs), barometric pressure, accurate temperature sensors. Some I2C devices are also output devices, such as 8x8 LED matrices, LCD displays etc.

Here we will focus on sensors, in our case a UV light index sensor.

The key to successfully working with I2C sensors is to find one that provides an extensive Arduino code library and examples that allow for easy setup and testing. One could write low-level libraries to interface with the sensor chip, but that can take a lot of time.

In our case, choose I2C sensors that can operate at 3.3V. The good news is most if not all I2C sensors are compatible with 3.3V.

Wiring is simple – just power, ground, a data line and a clock line. Code-wise, it all depends on the level of support provided by the author of the code library. Typically most Adafruit and Sparkfun-designed sensor boards have excellent documentation and examples.


Libraries Used


Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <Wire.h>               // when using I2C, always include Wire.h
#include "Adafruit_SI1145.h"    // imports the library into the sketch for later use

Adafruit_SI1145 uv = Adafruit_SI1145();

int senseVal = 0;

// code in this setup function runs just once, when mote is powered up or reset
void setup() {
    Serial.begin(9600);         // Open a connection via the Serial port / USB cable – useful for debugging
    Wire.begin(2, 14);          // explicitly define the I2C pins as 2 (SDA) and 14 (SCL)
    if (! uv.begin()) {
      Serial.println("Didn't find Si1145");
      while (1);
    }
}

// code in this loop function runs forever, until you cut power!
void loop() {
  Serial.println("===================");
  Serial.print("Vis: "); Serial.println(uv.readVisible());
  Serial.print("IR: "); Serial.println(uv.readIR());

  float UVindex = uv.readUV();
  // the index is multiplied by 100 so to get the
  // integer index, divide by 100!
  UVindex /= 100.0;  
  Serial.print("UV: ");  Serial.println(UVindex);

  delay(1000);
}