ads1115 analog-to-digital 4-channel added
[i2c-telemetry.git] / bh1750.c
1 /*
2  Sample code for the BH1750
3  */
4 #include <stdio.h>
5 #include <stdint.h>
6 #include <fcntl.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <math.h>
11 #include <linux/i2c-dev.h>
12 #include <linux/i2c.h>
13 #include <sys/ioctl.h>
14 #include "smbus.h"
15
16 #define BH1750FVI_I2C_ADDRESS 0x23 // ADDR > 0.7 VCC)
17 //#define BH1750FVI_I2C_ADDRESS  0x53 // ADDR < 0.3 VCC)
18 #define DEBUG 0
19
20 #define PowerDown    0x00
21 #define PowerOn    0x01
22 #define Reset      0x07
23 #define ContinuHigh   0x10
24 #define ContinuLow   0x13
25 #define OneTimeHigh   0x20
26 #define OneTimeLow   0x23
27
28 int main(int argc, char **argv)
29 {
30     int fd;
31     char *fileName = "/dev/i2c-0";
32     int retCode;
33     int readSize;
34     unsigned int res;
35     unsigned int lux;
36     char buf[5];
37     int i;
38
39     // Open port for reading and writing
40     if ((fd = open(fileName, O_RDWR)) < 0) {
41         printf("open error\n");
42         exit(1);
43     }
44
45     // Set the port options and set the address of the device
46     if (ioctl(fd, I2C_SLAVE, BH1750FVI_I2C_ADDRESS) < 0) {
47         printf("ioctl error\n");
48         close(fd);
49         exit(1);
50     }
51
52     retCode=i2c_smbus_write_byte(fd, PowerOn);
53 if(DEBUG)printf("Power On retCode=%d\n",retCode);
54     if (retCode < 0) {
55         printf("PowerOn error\n");
56         close(fd);
57         exit(1);
58     }
59
60     retCode=i2c_smbus_write_byte(fd, ContinuHigh);
61 if(DEBUG)printf("ContinuHigh retCode=%d\n",retCode);
62     if (retCode < 0) {
63         printf("ContinuHigh error\n");
64         close(fd);
65         exit(1);
66     }
67
68     // Set i<10 for more one check
69     for(i=0;i<1;i++) {
70         sleep(3);
71         readSize = read (fd, buf, 2);
72 if(DEBUG)printf("read readSize=%d %x %x\n",readSize,buf[0],buf[1]);
73
74         res = buf[0]*256+buf[1];
75 if(DEBUG)printf("res=%x\n",res);
76         lux = res / 1.2;
77     //    printf("Lux=%d\n",lux);
78         printf("Brightness (Lux)\t%0.1f\n", ((double)lux));
79     }
80
81     retCode=i2c_smbus_write_byte(fd, PowerDown);
82     close(fd);
83
84     exit (0);
85 }