YAHAL
Yet Another Hardware Abstraction Library
Loading...
Searching...
No Matches
opt3001_drv.cpp
1// ---------------------------------------------
2// This file is part of
3// _ _ __ _ _ __ __
4// ( \/ ) /__\ ( )_( ) /__\ ( )
5// \ / /(__)\ ) _ ( /(__)\ )(__
6// (__)(__)(__)(_) (_)(__)(__)(____)
7//
8// Yet Another HW Abstraction Library
9// Copyright (C) Andreas Terstegge
10// BSD Licensed (see file LICENSE)
11//
12// ---------------------------------------------
13
14#include "opt3001_drv.h"
15
16namespace OPT3001 {
17
18// Register addresses
19static const uint8_t REG_RESULT = 0x00;
20static const uint8_t REG_CONF = 0x01;
21//static const uint8_t REG_LIMIT_LOW = 0x02;
22//static const uint8_t REG_LIMIT_HIGH = 0x03;
23static const uint8_t REG_MAN_ID = 0x7E;
24static const uint8_t REG_DEV_ID = 0x7F;
25
26//static const uint16_t MASK_RESULT_EXP = 0xF000;
27static const uint16_t MASK_RESULT_MAT = 0x0FFF;
28}
29
30opt3001_drv::opt3001_drv(i2c_interface & i2c, uint8_t i2c_addr)
31: _i2c(i2c), _i2c_addr(i2c_addr) { }
32
33void opt3001_drv::start_measure(uint16_t CONF){
34 writeRegister(OPT3001::REG_CONF, CONF);
35}
36
37bool opt3001_drv::measure_ready() {
38 uint16_t val = readRegister(OPT3001::REG_CONF);
39 return val & 0x0080;
40}
41
42uint32_t opt3001_drv::get_light(){
43 uint32_t raw = readRegister(OPT3001::REG_RESULT);
44 uint16_t exp = raw >> 12;
45 raw &= OPT3001::MASK_RESULT_MAT;
46 return (raw << exp) / 100;
47}
48
49bool opt3001_drv::detect_sensor() {
50 uint16_t man = readRegister(OPT3001::REG_MAN_ID);
51 uint16_t dev = readRegister(OPT3001::REG_DEV_ID);
52 return (man == 0x5449 && dev == 0x3001);
53}
54
55
56void opt3001_drv::writeRegister(uint8_t reg, uint16_t value){
57 uint8_t txbuf[3];
58 txbuf[0] = reg;
59 txbuf[1] = value >> 8;
60 txbuf[2] = value & 0x00FF;
61 _i2c.i2cWrite(_i2c_addr, txbuf, 3);
62}
63
64uint16_t opt3001_drv::readRegister(uint8_t reg){
65 uint8_t txbuf[1];
66 uint8_t rxbuf[2];
67 uint16_t val;
68 txbuf[0] = reg;
69 _i2c.i2cWrite(_i2c_addr, txbuf, 1);
70 _i2c.i2cRead (_i2c_addr, rxbuf, 2);
71 val = (rxbuf[0] << 8) | rxbuf[1];
72 return val;
73}
74