Skip to content

Instantly share code, notes, and snippets.

@ianfiske
Last active April 17, 2016 12:51
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 ianfiske/e1d722eeb7789284d5d8 to your computer and use it in GitHub Desktop.
Save ianfiske/e1d722eeb7789284d5d8 to your computer and use it in GitHub Desktop.
Read temperature from DS18B20 on Electric Imp
#require "Onewire.class.nut:1.0.0"
ow <- Onewire(hardware.uart12);
power <- hardware.pin8;
power.configure(ANALOG_IN);
local success = ow.init();
if (!success) {
// Report error. Note if the Onewire object instantiated in
// debug mode, the object will report errors
server.error("1-Wire error.");
return;
}
function readTemperature() {
ow.reset();
ow.skipRom();
ow.writeByte(0x44);
// Give the sensor enough time for sampling
imp.sleep(0.8);
// Tell the sensor to transmit the reading
ow.reset();
ow.skipRom();
ow.writeByte(0xBE);
// Read the temperature value from the sensor's RAM
local tempLSB = ow.readByte();
local tempMSB = ow.readByte();
// Signal that we don't need any more data by resetting the bus
ow.reset();
// Calculate the temperature from LSB and MSB
local tempCelsius;
if (tempMSB >> 3 == 31) {
//server.log(tempMSB*256 + tempLSB);
tempCelsius = -(((tempMSB*256 + tempLSB) ^ 0x0FFFF) + 1)/16;
} else {
tempCelsius = ((tempMSB * 256) + tempLSB) / 16.0;
}
return (tempCelsius);
}
function reportTemperature() {
local temp = readTemperature();
agent.send("temp", temp);
imp.wakeup(10, reportTemperature);
}
reportTemperature();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment