summaryrefslogtreecommitdiff
path: root/src/driver/max44009.cc
blob: bab4da517b898086a9407cf9baef965514232ce6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
 * Copyright 2020 Daniel Friesel
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */
#include "driver/max44009.h"
#if defined(MULTIPASS_ARCH_HAS_I2C) && !defined(CONFIG_driver_softi2c)
#include "driver/i2c.h"
#else
#include "driver/soft_i2c.h"
#endif

float MAX44009::getLux()
{
	unsigned char luxHigh;
	unsigned char luxLow;
	unsigned int mantissa, exponent;

	txbuf[0] = 0x03;
	txbuf[1] = 0x04;

	if (i2c.xmit(address, 2, txbuf, 2, rxbuf) != 0) {
		return -1;
	}

	luxHigh = rxbuf[0];
	luxLow = rxbuf[1];

	/*
	* The lowest 4 bit of luxLow are the lowest 4 bit of the mantissa.
	* The lowest 4 bit of luxHigh are the highest 4 bit of the mantissa.
	*/
	mantissa = (luxLow & 0x0F) + ((luxHigh & 0x0F) << 4);

	/*
	* The highest 4 bit of luxHigh are the 4 bit exponent
	*/
	exponent = (luxHigh & 0xF0) >> 4;

	/*
	* Cast base and mantissa to float to avoid calculation errors
	* because of 16bit integer overflows.
	*/
	return (float)(1 << exponent) * (float)mantissa * 0.045;
}

MAX44009 max44009(0x4a);