Instantly share code, notes, and snippets.

Embed
What would you like to do?
Complete code after Post 1
// 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;
}
}
setPoint <- 68;
sensor <- TemperatureSensor(hardware.i2c12);
function updateTemp() {
// Read the ambient temperature
temp <- readTemp();
// If it's below what it should be, turn on the heat.
if (temp < setPoint) {
heatOn();
} else {
// If it's not below, that means it's above. Turn the heat on!
heatOff();
}
}
function mainLoop() {
updateTemp();
// in 60 seconds, call mainLoop again
imp.wakeup(60, mainLoop);
}
function readTemp() {
server.log("reading temperature: ");
temp <- sensor.getTemperature('F');
server.log(temp);
return temp;
}
// heatControlWire lets us control pin1 of the electric imp.
heatControlWire <- hardware.pin5;
// Configure it so that 1 = 3.3v and 0 = 0v.
heatControlWire.configure(DIGITAL_OUT);
function heatOn() {
// debug message so you know what the imp is doing
server.log("heat is on");
heatControlWire.write(1);
}
function heatOff() {
server.log("heat is off");
heatControlWire.write(0);
}
mainLoop();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment