Skip to content

Instantly share code, notes, and snippets.

@gillesdemey
Forked from seppestas/sht21.js
Created October 23, 2017 17:04
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 gillesdemey/c5e4ba37f66e901a389180578706061b to your computer and use it in GitHub Desktop.
Save gillesdemey/c5e4ba37f66e901a389180578706061b to your computer and use it in GitHub Desktop.
// Module to talk to the SHT21 temperature and humidity sensor over I2C
var i2c = require('i2c');
// Register addresses
const TRIGGER_T_MEASUREMENT_NO_HOLD = 0xF3;
const TRIGGER_RH_MEASUREMENT_NO_HOLD = 0xF5;
const WRITE_USER_REGISTER = 0xE6;
const READ_USER_REGISTER = 0xE7;
const SOFT_RESET = 0xFE;
const STATUS_BITS_MASK = 0x0003;
function SHT21(i2c_address, i2c_options) {
i2c_address = i2c_address || 0x40;
i2c_options = i2c_options || {};
this.wire = new i2c(i2c_address, i2c_options);
}
function parseTemperature(data) {
var st = (data[0] << 8) + data[1];
return 175.72 * st/(1<<16) - 46.85;
}
SHT21.prototype.readTemperature = function(cb) {
var wire = this.wire;
wire.writeByte(TRIGGER_T_MEASUREMENT_NO_HOLD, function(err) {
if (err) {
cb(err, null);
return;
}
setTimeout(function() {
wire.read(3, function(err, data) {
if (err) {
cb(err, null);
return;
}
cb(null, parseTemperature(data));
});
}, 100);
});
};
function parseHumidity(data) {
var srh = (data[0] << 8) + data[1];
return 125 * srh/(1<<16) - 6;
}
SHT21.prototype.readHumidity = function(cb) {
var wire = this.wire;
wire.writeByte(TRIGGER_RH_MEASUREMENT_NO_HOLD, function(err) {
if (err) {
cb(err, null);
return;
}
setTimeout(function() {
wire.read(3, function(err, data) {
if (err) {
cb(err, null);
return;
}
cb(null, parseHumidity(data));
});
}, 50);
});
};
module.exports = SHT21;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment