Thursday, February 28, 2013

Maple Mini & TMP102 Temperature Sensor

The TMP102 temperature sensor and breakout board from Sparkfun connects to the Maple Mini via I2C (using the Maple Wire library - included with the Maple IDE). The following basic example reads the temperature in Celsius from the TMP102, converts it to Fahrenheit, and prints the results to the USB serial console.

The code is adapted from the Arduino example code at bildr.

Connections:


TMP102   Maple Mini
GND      GND
V+       VCC
SCL      16 (i2c1 - scl)
SDA      15 (i2c1 - sda)
ALT      GND
ADD0     GND (sets I2C addr. to 0x48)

Note: The I2C address can be changed by connecting the TMP102's ADD0 to the Maple Mini. Connecting it to VCC sets the address to 0x49.

The breakout board includes 1k Ohm pull-up resistors on SDA and SCL, which seem to be sufficient for the I2C connection.

Code:


#include <Wire.h>

int tmp102Address = 0x48;

void setup(){
  Wire.begin(15, 16);
}

void loop(){
  float celsius = getTemperature();
  SerialUSB.print("Celsius: ");
  SerialUSB.println(celsius);
  SerialUSB.print("Fahrenheit: ");
  float fahrenheit = (1.8 * celsius) + 32;
  SerialUSB.println(fahrenheit);
  delay(1000);
}

float getTemperature(){
  Wire.requestFrom(tmp102Address, 2); 
  byte MSB = Wire.receive();
  byte LSB = Wire.receive();
  //it's a 12bit int, using two's compliment for negative
  int TemperatureSum = ((MSB << 8) | LSB) >> 4; 
  float celsius = TemperatureSum*0.0625;
  return celsius;
}