Created
August 18, 2016 17:04
-
-
Save idrabenia/143fbdabb4bbe3b2f7120a90c9f97d35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var i2c = require('i2c'); | |
var address = 0x39; | |
var wire = new i2c(address, {device: '/dev/i2c-1'}); | |
var express = require('express'); | |
var app = express(); | |
app.get('/', function (req, res) { | |
readLux(function (err, luxVal) { | |
err && console.log(err.toString()); | |
luxVal && console.log('Lux: ' + luxVal); | |
res.send({ lux: luxVal, error: err && err.toString() }); | |
}); | |
}); | |
app.listen(3000, function () { | |
setUpSensor(); | |
console.log('Example app listening on port 3000!'); | |
}); | |
function setUpSensor() { | |
wire.writeBytes(0x80, [0x03], noop); | |
} | |
function readLightData(address, cb) { | |
wire.readBytes(address, 2, function(err, res) { | |
if (err) { | |
cb && cb(err); | |
return; | |
} | |
var val = (res[1] << 8) + res[0]; | |
cb && cb(undefined, val); | |
val === 0 && setUpSensor(); | |
}); | |
} | |
function calculateLux(ch0, ch1) { | |
var self = this; | |
var gainMultiplier = 1; | |
var timeMultiplier = 1; | |
var scaling; | |
var lux = 0; | |
var channelRatio = 1; | |
scaling = timeMultiplier * gainMultiplier; | |
ch0 *= scaling; | |
ch1 *= scaling; | |
channelRatio = ch1 / ch0; | |
console.log('channelRatio: ' + channelRatio); | |
// T/FN/CL | |
if ((0 < channelRatio) && (channelRatio <= 0.50)) { | |
lux = 0.0304 * ch0 - 0.062 * ch0 * Math.pow(channelRatio, 1.4); | |
console.log('lux: ' + lux); | |
} else if ((0.50 < channelRatio) && (channelRatio <= 0.61)) { | |
lux = 0.0224 * ch0 - 0.031 * ch1; | |
} else if ((0.61 < channelRatio) && (channelRatio <= 0.80)) { | |
lux = 0.0128 * ch0 - 0.0153 * ch1; | |
} else if ((0.80 < channelRatio) && (channelRatio <= 1.30)) { | |
lux = 0.00146 * ch0 - 0.00112 * ch1; | |
} else if (channelRatio > 1.30) { | |
lux = 0; | |
} | |
return Math.round(lux * 100) / 100; | |
} | |
function readLux(cb) { | |
readLightData(0xAC, function (err0, ch0) { | |
if (err0) { | |
cb && cb(err0); | |
return; | |
} | |
readLightData(0xAE, function (err1, ch1) { | |
if (err1) { | |
cb && cb(err1); | |
return; | |
} | |
var luxVal = calculateLux(ch0, ch1); | |
cb && cb(undefined, luxVal); | |
console.log(luxVal); | |
}); | |
}); | |
} | |
function noop() { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment