Skip to content

Instantly share code, notes, and snippets.

@uyorum
Created September 2, 2017 01:57
Show Gist options
  • Save uyorum/f988ab4bd4ae90fb5dd7c6950e6c7110 to your computer and use it in GitHub Desktop.
Save uyorum/f988ab4bd4ae90fb5dd7c6950e6c7110 to your computer and use it in GitHub Desktop.
TSL2561 on Mongoose OS
load('api_config.js');
load('api_mqtt.js');
load('api_net.js');
load('api_sys.js');
load('api_timer.js');
load('api_i2c.js');
let address = 0x39;
let bus = I2C.get();
// Enable device
I2C.writeRegB(bus, address, 0x80, 0x03);
// Set gain (0x10: 16x, 0x00: 1x(default))
// Set integration time (0x00: 13.7ms, 0x01: 101ms, 0x02: 402ms(default))
I2C.writeRegB(bus, address, 0x81, 0x00 | 0x02);
let get_lux = function() {
let scale = 16.0;
//let scale = 1.0;
//let scale = 29.34;
//let scale = 1.0;
// Get raw data
let vl_data = I2C.readRegW(bus, 0x39, 0xAC);
let ir_data = I2C.readRegW(bus, 0x39, 0xAE);
let vl_data_upper = vl_data & 0xFF;
let vl_data_lower = vl_data >> 8;
let vl_raw = vl_data_upper << 8 | vl_data_lower;
let ir_data_upper = ir_data & 0xFF;
let ir_data_lower = ir_data >> 8;
let ir_raw = ir_data_upper << 8 | ir_data_lower;
// Calcurate lux
let ch0 = vl_raw * scale;
let ch1 = ir_raw * scale;
let ratio = 0;
if (ch0 === 0) {
ratio = 99;
} else {
ratio = ch1 / ch0;
}
let lux = 0;
if (0 < ratio && ratio <= 0.52) {
lux = (0.0315 * ch0) - (0.0593 * ch0 * Math.pow(ratio, 1.4));
} else if (0.52 < ratio && ratio <= 0.65) {
lux = (0.0229 * ch0) - (0.0291 * ch1);
} else if (0.65 < ratio && ratio <= 0.8) {
lux = (0.0157 * ch0) - (0.018 * ch1);
} else if (0.8 < ratio && ratio <= 1.3) {
lux = (0.00338 * ch0) - (0.0026 * ch1);
} else {
lux = 0;
}
return lux;
};
Timer.set(1000 * 60 /* 1 min */, true /* repeat */, function() {
let lux = Math.round(get_lux() * 10) / 10;
MQTT.pub('home/livingroom/brightness', JSON.stringify(lux), 0);
}, null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment