Calibrate the temp sensor

This commit is contained in:
Zakary Timson 2024-10-30 11:16:24 -04:00
parent 85e6ab01ae
commit a9a8cf2745
2 changed files with 20 additions and 14 deletions

View File

@ -3,25 +3,30 @@ import i2c from 'i2c-bus';
export async function bme(address = 0x76) { export async function bme(address = 0x76) {
const i2cBus = await i2c.openPromisified(1); const i2cBus = await i2c.openPromisified(1);
const data = await Promise.all([ const data = await Promise.all([
i2cBus.readByte(address, 0xFA), i2cBus.readByte(address, 0xFA), // Temp MSB
i2cBus.readByte(address, 0xFB), i2cBus.readByte(address, 0xFB), // Temp LSB
i2cBus.readByte(address, 0xFC), i2cBus.readByte(address, 0xFC), // Temp XLSB
i2cBus.readByte(address, 0xF7), i2cBus.readByte(address, 0xF7), // Pressure MSB
i2cBus.readByte(address, 0xF8), i2cBus.readByte(address, 0xF8), // Pressure LSB
i2cBus.readByte(address, 0xF9), i2cBus.readByte(address, 0xF9), // Pressure XLSB
i2cBus.readByte(address, 0xFD), i2cBus.readByte(address, 0xFD), // Humidity MSB
i2cBus.readByte(address, 0xFE), i2cBus.readByte(address, 0xFE), // Humidity LSB
]); ]);
const T1 = 27504; // Calibration registers
const T2 = 26435; const CALIBRATION_LENGTH = 24;
const T3 = -1000; const calibBuffer = Buffer.alloc(CALIBRATION_LENGTH);
await i2cBus.readI2cBlock(address, 0x88, CALIBRATION_LENGTH, calibBuffer);
const T1 = calibBuffer.readUInt16LE(0);
const T2 = calibBuffer.readInt16LE(2);
const T3 = calibBuffer.readInt16LE(4);
const rawTemp = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4); const rawTemp = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
let var1 = (((rawTemp >> 3) - (T1 << 1)) * T2) / 2048; const var1 = (((rawTemp >> 3) - (T1 << 1)) * T2) / 2048;
let var2 = (((((rawTemp >> 4) - T1) * ((rawTemp >> 4) - T1)) >> 12) * T3) / 16384; const var2 = (((((rawTemp >> 4) - T1) * ((rawTemp >> 4) - T1)) >> 12) * T3) / 16384;
let temp = (var1 + var2) / 5120.0; const temp = (var1 + var2) / 5120.0;
await i2cBus.close();
return { return {
temperature: temp, temperature: temp,
pressure: ((data[3] << 12) | (data[4] << 4) | (data[5] >> 4)) / 25600, pressure: ((data[3] << 12) | (data[4] << 4) | (data[5] >> 4)) / 25600,

View File

@ -9,6 +9,7 @@ export async function bms(address = 0x57) {
i2cBus.readByte(address, 0x23), i2cBus.readByte(address, 0x23),
i2cBus.readByte(address, 0x2a), i2cBus.readByte(address, 0x2a),
]); ]);
await i2cBus.close();
return { return {
charging: !!((data[0] >> 7) & 1), charging: !!((data[0] >> 7) & 1),
percentage: data[4] / 100, percentage: data[4] / 100,