Skip to content

Instantly share code, notes, and snippets.

@airtonix
Created November 22, 2018 12:26
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 airtonix/224d68c260ee3e40487026b7085deca4 to your computer and use it in GitHub Desktop.
Save airtonix/224d68c260ee3e40487026b7085deca4 to your computer and use it in GitHub Desktop.
NodeRed I2C
...
functionGlobalContext: {
i2c:require('i2c'),
os:require('os'),
fs:require('fs'),
glob:require('glob'),
ua:require('universal-analytics')
// jfive:require("johnny-five"),
// j5board:require("johnny-five").Board({repl:false})
}
...
const i2c = global.get('i2c');
const deviceAddress = 0x40;
const temperatureCommand = 0xF3;
const humidityCommand = 0xF5;
const wire = new i2c(deviceAddress, {device: '/dev/i2c-1'});
function readWire({command, readBytes}) {
return new Promise((resolve, reject) => {
wire.writeByte(command, () => {
setTimeout(() => {
wire.read(readBytes, function(err, response) {
resolve(response);
});
}, 250);
})
});
}
function getHumidity () {
return readWire({command: humidityCommand, readBytes: 2 })
.then(([msb, lsb]) => {
return {
msb, lsb,
value: -6 + (((msb * 256 + lsb) * 125.0) / 65536.0)
};
});
}
getHumidity()
.then((humidity) => {
node.send([
{payload: humidity, topic: 'humidity'}
]);
});
return;
const i2c = global.get('i2c');
const deviceAddress = 0x40;
const temperatureCommand = 0xF3;
const humidityCommand = 0xF5;
const wire = new i2c(deviceAddress, {device: '/dev/i2c-1'});
function readWire({command, readBytes}) {
return new Promise((resolve, reject) => {
wire.writeByte(command, () => {
setTimeout(() => {
wire.read(readBytes, function(err, response) {
resolve(response);
});
}, 250);
})
});
}
function getTemperature () {
return readWire({command: temperatureCommand, readBytes: 2 })
.then(([msb, lsb]) => {
return {
msb, lsb,
value: -46.85 + (((msb * 256 + lsb) * 175.72) / 65536.0)
};
});
}
getTemperature()
.then((temperature) => {
node.send({payload: temperature, topic: 'temperature'});
});
return;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment