Topic: Code BH1750FVI

BH1750FVI

http://pi.gids.nl:81/temp/img/BH1750FVI.png

Some good code was provided by the community thanks:

C code.....:

/*
 Sample code for the BH1750 Light sensor for Raspberry Pi
 Connection:
 VCC-5v (Raspberry pin 1)
 GND-GND(Raspberry pin 6)
 SCL-SCL(Raspberry pin 5)
 SDA-SDA(Raspberry pin 3)
 ADD-NC or GND
 * 
 * gcc -o bh1750fvi bh1750fvi.c 
 * 
 */
#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <linux/i2c-dev.h>
// #include <linux/i2c.h>
#include <sys/ioctl.h>
// #include "smbus.h"

# You need to play with the <linux/i2c-dev.h> & smbus.h I got errors loading them ....!!

#define BH1750FVI_I2C_ADDRESS 0x23 // ADDR > 0.7 VCC)
//#define BH1750FVI_I2C_ADDRESS  0x53 // ADDR < 0.3 VCC)
#define DEBUG 0

#define PowerDown    0x00
#define PowerOn    0x01
#define Reset      0x07
#define ContinuHigh   0x10
#define ContinuLow   0x13
#define OneTimeHigh   0x20
#define OneTimeLow   0x23

int main(int argc, char **argv)
{
    int fd;
    char *fileName = "/dev/i2c-1";
    int retCode;
    int readSize;
    unsigned int res;
    unsigned int lux;
    char buf[5];
    int i;

    // Open port for reading and writing
    if ((fd = open(fileName, O_RDWR)) < 0) {
        printf("open error\n");
        exit(1);
    }
   
    // Set the port options and set the address of the device
    if (ioctl(fd, I2C_SLAVE, BH1750FVI_I2C_ADDRESS) < 0) {
        printf("ioctl error\n");
        close(fd);
        exit(1);
    }

    retCode=i2c_smbus_write_byte(fd, PowerOn);
if(DEBUG)printf("Power On retCode=%d\n",retCode);
    if (retCode < 0) {
        printf("PowerOn error\n");
        close(fd);
        exit(1);
    }
   
    retCode=i2c_smbus_write_byte(fd, ContinuHigh);
if(DEBUG)printf("ContinuHigh retCode=%d\n",retCode);
    if (retCode < 0) {
        printf("ContinuHigh error\n");
        close(fd);
        exit(1);
    }

    for(i=0;i<20;i++) {
//        sleep(1);
        readSize = read (fd, buf, 2);
if(DEBUG)printf("read readSize=%d %x %x\n",readSize,buf[0],buf[1]);

        res = buf[0]*256+buf[1];
if(DEBUG)printf("res=%x\n",res);
        lux = res / 1.2;
        printf("Lux=%d\n",lux);
    }

    retCode=i2c_smbus_write_byte(fd, PowerDown);
    close(fd);

    exit (0);
}

And a quite simple Python code:

#!/usr/bin/python
# -*- encoding: utf-8 -*-

import time
import smbus
import decimal

# bus = smbus.SMBus(0) #(256MB)
bus = smbus.SMBus(1) #(512MB)

addr = 0x23 # i2c adress

# while True:
count = 0
while (count < 10):
    data = bus.read_i2c_block_data(addr,0x11)
#  lux1 = "Luminosity " + str((data[1] + (256 * data[0])) / 1.2) + " lx"
    lux2 = str((data[1] + (256 * data[0])) / 1.2)
    lux  = decimal.Decimal(lux2).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP)
    outlux = str(lux)
    print "Luminosity " + outlux + " lx"
    time.sleep(0.25)
    count = count + 1

Let us know your setup.

Chrs