-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbh1750.c
71 lines (52 loc) · 1.56 KB
/
bh1750.c
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* bh1750.c
*
* Created on: 21/09/2016
* Author: andru
*
* BH1750 - nRF24LE1 light sensor driver
*
*/
#define BH1750_ADDR 0x23 // device address
#define BH1750_PWR_DOWN 0x0 // No active state.
#define BH1750_CONT_HMODE 0x10 // Continuously H-Resolution Mode
#include "delay.h"
#include "w2.h"
#include "bh1750.h"
void bh1750_init(void) {
w2_configure(W2_CONFIG_OPTION_ENABLE |
W2_CONFIG_OPTION_MODE_MASTER |
W2_CONFIG_OPTION_CLOCK_FREQ_100_KHZ |
W2_CONFIG_OPTION_ALL_INTERRUPTS_ENABLE,
0
);
}
bh1750error_t bh1750_read(uint16_t *light) {
uint8_t addr, txbuf=0, rxbuf[2];
addr = BH1750_CONT_HMODE;
if (w2_master_write_to(BH1750_ADDR, &addr, 1, &txbuf, 0) == W2_NACK_VAL)
return BH1750_TIMEOUT;
delay_ms(BH1750_WAIT);
if (w2_master_cur_address_read(BH1750_ADDR, rxbuf, 2) == W2_NACK_VAL)
return BH1750_ERROR;
addr = BH1750_PWR_DOWN;
w2_master_write_to(BH1750_ADDR, &addr, 1, &txbuf, 0);
*light = (uint32_t) ((rxbuf[0] << 8) + rxbuf[1]) * 10 / 12;
return BH1750_OK;
}
bh1750error_t bh1750_ask(void) {
uint8_t addr, txbuf=0;
addr = BH1750_CONT_HMODE;
if (w2_master_write_to(BH1750_ADDR, &addr, 1, &txbuf, 0) == W2_NACK_VAL)
return BH1750_TIMEOUT;
return BH1750_OK;
}
bh1750error_t bh1750_read_nowait(uint16_t *light) {
uint8_t addr, txbuf=0, rxbuf[2];
if (w2_master_cur_address_read(BH1750_ADDR, rxbuf, 2) == W2_NACK_VAL)
return BH1750_ERROR;
addr = BH1750_PWR_DOWN;
w2_master_write_to(BH1750_ADDR, &addr, 1, &txbuf, 0);
*light = (uint32_t) ((rxbuf[0] << 8) + rxbuf[1]) * 10 / 12;
return BH1750_OK;
}