Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Light sensor BH1750

Fri Nov 03, 2017 4:58 pm

Hello,
for my project I want a python code to control the light.
So if a input from my PIR sensor turn the light on, but check the light level and then turn the light on or not.

I have a basic script for the PIR sensor light control without any light sensor addon:

Code: Select all

import RPi.GPIO as GPIO
import time
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, GPIO.HIGH)

delay = 40 # set number of seconds delay before light turns off

while True:
    time.sleep(0.1)
    #wait for pir to trigger.
    print "waiting "
    while GPIO.input(12) == 0:
        time.sleep (0.5)

    print "turn light on here"
    GPIO.output(25, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(25, GPIO.HIGH)
    count = 0

    #start count down to turn off
    print "count down started "
    while count < delay:
        count = count + 1
        
    # here if the input goes high again we reset the counter to 0
        if GPIO.input(12) == 1:
            count = 0
        
        print "count down now ",  (delay - count)
        time.sleep(1)
        
    print "Turn light off"
    GPIO.output(25, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(25, GPIO.HIGH)
The light sensor part is only:

Code: Select all

import smbus

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)
 
def readLight(addr=0x23):
  data = smbus.SMBus(1).read_i2c_block_data(0x23,0x11)
  return convertToNumber(data)
The light level can I print with this variable:

Code: Select all

print "" + str(int(readLight())) + ""
But if I use the string " + str(int(readLight())) + " in "if " + str(int(readLight())) + " > 100:" and
"else:...." they don't switch with the tasks from " if .. > 100" to "else:...".

For Example:

Code: Select all

import smbus

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)
 
def readLight(addr=0x23):
  data = smbus.SMBus(1).read_i2c_block_data(0x23,0x11)
  return convertToNumber(data)
while True:
    if " + str(int(readLight())) + " > 100:
        print "mode 1"
        time.sleep(1)
    else:
        print "mode 2"
        time.sleep(1)  
He don't switch from mode 1 to mode 2, if I light the sensor on or make it dark.

At the end I want one code with the base on the first PIR Control code with the integration of the light sensor.

I hope you unterstand my problem
Thanks!!

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Fri Nov 03, 2017 7:01 pm

Looking at your code you look to be trying to compare a string variable against an integer number variable which wont work.

Code: Select all

  if " + str(int(readLight())) + " > 100: 
try changing to your if line to this if you want to compare the integer number value

Code: Select all

  if (int(readLight())) > 100: 
or this if you want to compare the actual float number variable

Code: Select all

  if (readLight()) > 100: 
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

User avatar
OutoftheBOTS
Posts: 711
Joined: Tue Aug 01, 2017 10:06 am

Re: Light sensor BH1750

Fri Nov 03, 2017 8:40 pm

I am not sure if the PIR sensor will detect whether the light has been turned on as it detects change in infrared light (body heat of person moving)

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Fri Nov 03, 2017 10:01 pm

If you read the post carefully the op has 2 sensors. PIR to detect person but also light level sensor to check if light is required. ie is the room dark.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Sat Nov 04, 2017 7:05 am

Yes with this arrgument work analyse for the example "mode 1" and "mode 2":

Code: Select all

if (int(readLight())) > 100: 
So now I want the integration from the light sensor in the PIR script.
But where put it in the code to turn on or not the light?

Code: Select all

import RPi.GPIO as GPIO
import time
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, GPIO.HIGH)

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)
 
def readLight(addr=0x23):
  data = smbus.SMBus(1).read_i2c_block_data(0x23,0x11)
  return convertToNumber(data)
  
delay = 40 # set number of seconds delay before light turns off

while True:
    time.sleep(0.1)
    #wait for pir to trigger.
    print "waiting "
    while GPIO.input(12) == 0:
        time.sleep (0.5)

    print "turn light on here"
    GPIO.output(25, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(25, GPIO.HIGH)
    count = 0

    #start count down to turn off
    print "count down started "
    while count < delay:
        count = count + 1
        
    # here if the input goes high again we reset the counter to 0
        if GPIO.input(12) == 1:
            count = 0
        
        print "count down now ",  (delay - count)
        time.sleep(1)
        
    print "Turn light off"
    GPIO.output(25, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(25, GPIO.HIGH)
And the light sensor is outside and the PIR Sensor is inside an his light level is not right, so I must use the external light sensor from outside.

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Sat Nov 04, 2017 9:53 am

looking at your code there is an error in the turn light on and off parts.
As you have it you will only turn your light on for 0.5 seconds

Code: Select all

    print "turn light on here"
    GPIO.output(25, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(25, GPIO.HIGH)
    
and the turn light off part is exactly the same ?

So editing your code and assuming your relay is active low I have changed to on / off parts of your code and added the test for the light level.
Now I have put the check after the pir trigger part of the program but you could also put it before the pir trigger part of the program so it prevents the triggering if its not dark, will leave it up to you to experiment.

Code: Select all

import RPi.GPIO as GPIO
import time
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, GPIO.HIGH)

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)
 
def readLight(addr=0x23):
  data = smbus.SMBus(1).read_i2c_block_data(0x23,0x11)
  return convertToNumber(data)
  
delay = 40 # set number of seconds delay before light turns off

while True:
    time.sleep(0.1)
    #wait for pir to trigger.
    print "waiting "
    while GPIO.input(12) == 0:
        time.sleep (0.5)

    print "check light level"
    
    if (int(readLight())) > 100: 
        print "its dark turn light on "
        GPIO.output(25, GPIO.LOW)
    else:
        print "its not dark dont turn light on"
    count = 0

    #start count down to turn off
    print "count down started "
    while count < delay:
        count = count + 1
        
    # here if the input goes high again we reset the counter to 0
        if GPIO.input(12) == 1:
            count = 0
        
        print "count down now ",  (delay - count)
        time.sleep(1)
        
    print "Turn light off"

    GPIO.output(25, GPIO.HIGH)
    
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Sat Nov 04, 2017 11:23 am

Ok thanks for the idea, but it isn't wrong with the 0.5 seconds, because my control gear from the lights is using only tast pulses for turn on or off the light.
Last edited by Sbs-ula on Sat Nov 04, 2017 11:59 am, edited 1 time in total.

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Sat Nov 04, 2017 11:27 am

Sbs-ula wrote:
Sat Nov 04, 2017 11:23 am
Ok thanks for the idea, but it isn't wrong with the 0.5 seconds, because mit control gear from the lights is using only tast pulses for turn on or off the light.
OK was not aware you were using control gear to control your lights, that's the sort of information you need to include in your posts so people know what you are working with.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Sun Nov 12, 2017 4:52 pm

Now the script works in the right order.
But I reboot my pi every day on 12 pm with a crontab job, it works so far.

The light control script starts up with the reboot by the rc.local.
My problem now is, that the pi after round about 10 or 11 hours don't turn on the lights. I tested manually without rc.local autostart in a terminal window. He print at motion the normal text, so it is nothing different:

Code: Select all

 
.... 
waiting 
check light level
its dark turn light on
count down started 
..(count down hidden)..
Turn light off
waiting
.... 
The relais don't work, so the pi don't switch the states of the GPIOs, but in the frist few hours works it fine.
Where is the problem?

Here is my current script:

Code: Select all

import RPi.GPIO as GPIO
import time
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, GPIO.HIGH)

delay = 10 # set number of seconds delay before light turns off

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)
 
def readLight(addr=0x23):
  data = smbus.SMBus(1).read_i2c_block_data(0x23,0x10)
  return convertToNumber(data)


while True:
   time.sleep(0.1)
    #wait for pir to trigger.
   print "waiting "
   while GPIO.input(12) == 0:
        time.sleep (0.3)

   count = 0
   print "check light level"        
   if (int(readLight())) <= 3: 
      print "its dark turn light on "
      GPIO.output(25, GPIO.LOW)
      time.sleep(0.5)
      GPIO.output(25, GPIO.HIGH)
      on = 1
      
   else:
      print "its not dark dont turn light on"
      time.sleep(5)
      on = 0

    #start count down to turn off
   print "count down started"
   while count < delay:
      count = count + 1
        
    # here if the input goes high again we reset the counter to 0
      if GPIO.input(12) == 1:
         count = 0
        
      print "count down now ",  (delay - count)
      time.sleep(1)

   if on == 1:
      print "Turn light off"
      GPIO.output(25, GPIO.LOW)
      time.sleep(0.5)
      GPIO.output(25, GPIO.HIGH)
And yes I forgot the information with the control gear, sorry!

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Sun Nov 12, 2017 6:35 pm

I can't see anything that would make your script not activate the relay.

may be you could call it like this

Code: Select all


python call >> /home/pi/light.log >2>&1 &

then look at the log file produce to see if there are any errors being returned after the relay fails to operate.

if this produces no answers try add print statements to your program so you can see what the variables are at critical points in your program.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Sun Nov 12, 2017 7:13 pm

Okay, so I try it out, but the console say:

Code: Select all

bash: syntax error unexpected word `2 '
And the path must be the same path as the python script, only with log at the end?

EDIT:
So without the first ">" makes me an log file with the content:

Code: Select all

python: can't open file 'call': [Errno 2] No such file or directory

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Sun Nov 12, 2017 7:22 pm

opps type crept in there sorry.

Code: Select all

existing python call >> /home/pi/light.log 2>&1 &

you must specify the full path to the light.log file but it can be any name you want eg error.log, log.txt, report.txt

I only suggested /home/pi as it should exist on every version of raspbian and is were you end up if you sign in via ssh or open the file browser from the desktop, so its easy to find your file.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Sun Nov 12, 2017 7:28 pm

So with "existing" is in the .log file:

Code: Select all

bash: existing: command not found 
and without "existing":

Code: Select all

python: can't open file 'call': [Errno 2] No such file or directory

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Sun Nov 12, 2017 7:31 pm

please post the line that calls your python program in the rc.local file, so I can see what you have.

and what you originally had before you edited it and the program was working.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Sun Nov 12, 2017 7:36 pm

the line in the rc.local is:

Code: Select all

python /home/pi/light/backup/light.py &
It works always with the bug, that he don't switch the GPIOs after hours. So I don't change anything, so not in the program or in the rc.local

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Sun Nov 12, 2017 7:45 pm

Right you obviously miss understood what I was trying to tell you to do.

So we are going to make it so that all output from your program including any error will be written to a log file so that you can review it after 12 hours to see if there are any clues as to why your program fails.

so change your rc.local entry so it looks like this.

Code: Select all

python /home/pi/light/backup/light.py >>/home/pi/light.log 2>&1 &
now when your program runs all output from it should go to the file light.log which you will find in the directory /home/pi
so in 12 hours time or after your relay has failed to turn on if you look in the file you might find an error message which will tell you why it failed.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Sun Nov 12, 2017 8:15 pm

So I understand it.
I change the line in the rc.local and the reboot at 12pm make the log file.

I will you write with the result of the log file.

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Mon Nov 13, 2017 5:43 pm

So it has happened again with the bug.
This is the content of the log file:

Code: Select all

Python 2.7.9 (default, Sep 17 2016, 20:26:04) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
And nothing more.
I switch off the autostart from the crontab and the pi was on from 8 pm yesterday to now.

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Mon Nov 13, 2017 8:18 pm

Sorry but that does not make sense that is the sort of response you get if you type python at the command prompt.

I have run may python programs so they start with the pi and have never seen an entry like this in a log file generated using that method.

so I have just done a test using this code

Code: Select all

import time
print (time.strftime("%H:%M:%S"))
print "this is a test file"
print " generated using print "
print " in a program run from rc.local"
and called it using rc.local

Code: Select all

python /home/pi/t1.py >>/home/pi/light.log 2>&1 &
after 2 reboots the light.log file contained this

Code: Select all

20:28:11
this is a test file
 generated using print 
 in a program run from rc.local
20:28:38
this is a test file
 generated using print 
 in a program run from rc.local
exactly what I was expecting your log file should have contained the same sort of output every print statement contained within your program should have appeared in the log file.

you have done some thing wrong start by posting a copy of your rc.local file.
Last edited by pcmanbob on Mon Nov 13, 2017 8:33 pm, edited 1 time in total.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Mon Nov 13, 2017 8:30 pm

Yes I also don't understand it, but here is the output from the command python:

Code: Select all

Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
It is the same like you already said.
But whats wrong?

Edit:

So here is my full rc.local you can compare:

Code: Select all

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi

python /home/pi/nfc/nfc.py &
python /home/pi/Light/backup/light.py
>>/home/pi/light.log 2>&1 &
exit 0
So what do you mean with I did something wrong with start posting a copy of the rc.local?
Last edited by Sbs-ula on Mon Nov 13, 2017 8:46 pm, edited 1 time in total.

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Mon Nov 13, 2017 8:41 pm

Sbs-ula wrote:
Mon Nov 13, 2017 8:30 pm
Yes I also don't understand it, but here is the output from the command python:

Code: Select all

Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
It is the same like you already said.
But whats wrong?
as I said start by posting a copy of your rc.local file please.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Mon Nov 13, 2017 9:00 pm

Here is the full copy of the rc.local:

Code: Select all

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.                                                                         #
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi

python /home/pi/nfc/nfc.py &
python /home/pi/light/backup/light.py >>/home/pi/light.log 2>&1 &
exit 0

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Mon Nov 13, 2017 9:07 pm

That looks OK to me.

Are your sure the file light.py exists in that directory and actually contains the program you think it does?
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Sbs-ula
Posts: 24
Joined: Mon Oct 23, 2017 11:22 am

Re: Light sensor BH1750

Mon Nov 13, 2017 9:14 pm

Yes, if I start with the command:

Code: Select all

python /home/pi/light/backup/light.py
Then is the output:

Code: Select all

waiting
So that's right.

And if I type with the command nano, then it is the right file with the program code from the top of this thread.

pcmanbob
Posts: 9612
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Light sensor BH1750

Mon Nov 13, 2017 9:18 pm

OK.

then try starting it with this line python /home/pi/light/backup/light.py >>/home/pi/light.log 2>&1 the same as you would when running it from rc.local

you should not get waiting printed on the screen but if you go to the log file you should find it in there.
if you then activate it so it does a timed loop you should see all the output in the log file to not forgetting you will have to refresh the file view to see the changes.

EDIT......

you may need to delete the light.log file first as it will have been created as root and you wont be able to write to it as the pi user when running the above line from the command line.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Return to “Python”