Skip to content

Instantly share code, notes, and snippets.

@evilmachina
Last active January 4, 2016 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evilmachina/91fdc7bad85f865cef4a to your computer and use it in GitHub Desktop.
Save evilmachina/91fdc7bad85f865cef4a to your computer and use it in GitHub Desktop.
local thingspeakUrl = "http://api.thingspeak.com/update";
local headers = {"Content-Type": "application/x-www-form-urlencoded",
"X-THINGSPEAKAPIKEY":"key"};
local field = "field1";
function httpPostToThingspeak (data) {
local request = http.post(thingspeakUrl, headers, data);
local response = request.sendsync();
return response;
}
device.on("updateTemp", function(temp) {
local response = httpPostToThingspeak(field +"="+temp);
server.log(response.body);
});
/** Temperature monitor using TMP102 chip over I2C */
// Temperature Sensor Class for TMP102
class TemperatureSensor
{
i2cPort = null;
i2cAddress = null;
constructor(port)
{
hardware.configure(I2C_12);
i2cPort = hardware.i2c12;
i2cPort.configure(CLOCK_SPEED_100_KHZ);
i2cAddress = (0x48) << 1;
server.log(format("i2cAddress=%x", i2cAddress));
// Start continuous conversion
i2cPort.write(i2cAddress, "");
i2cPort.write(i2cAddress, "0");
imp.sleep(0.05);
}
// Retrieve temperature (from local sensor) in deg F
function getTemperature()
{
local data = i2cPort.read(i2cAddress, "\x00", 2);
if (data == null)
{
server.show("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;
local volt = hardware.voltage();
return temperature;
}
}
// Instantiate the sensor
local sensor = TemperatureSensor(I2C_12);
function getTemp()
{
local temp = sensor.getTemperature();
server.log(temp);
if (temp != null)
{
server.log("Current temp is "+temp+" °C");
agent.send("updateTemp", temp);
}
}
imp.onidle(function() {
getTemp();
server.sleepfor(600);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment