Instantly share code, notes, and snippets.

@rcoh /tmp102.nut
Last active Aug 29, 2015

Embed
What would you like to do?
TMP 102 Electric IMP i2c
// Adapted from:
// http://techgurka.blogspot.com/2013/04/quick-temperature-graph-using-electric.html
class TemperatureSensor {
i2cPort = null;
constructor(port) {
i2cPort = port;
i2cPort.configure(CLOCK_SPEED_100_KHZ);
}
// Retrieve temperature (from local sensor) in deg F
function getTemperature(unit) {
i2cPort.write(0x90, "");
i2cPort.write(0x90, "0");
// Wait for conversion to finish
imp.sleep(0.05);
local data = i2cPort.read(0x90, "\x00", 2);
if (data == null) {
server.log("Error reading TMP102");
return null;
}
// Remove two's complement if negative temperature
local degrees = data[0];
if (degrees & 0x80)
degrees = -((degrees - 1) ^ 0xFF);
// Calculate no of steps. Each step is 0.0625 degrees centigrades
local steps = degrees * 16 + (data[1] >> 4);
local temperature = steps * 0.0625;
if (unit == 'F')
temperature = temperature * 9 / 5 + 32;
return temperature;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment