Python code for light sensor application

@shoeb.ahmed @rahul.singh1 @yeshwant.naik Can anyone help me with the python code for light sensor application where I want to make the LED ON as soon as the room goes dark and LED OFF as the room light is switched ON? Also, darker the room goes, brighter the LED glows kind of code with analogWrite() would be great.

When I run the below code, it continuously measures the sensor value but the LED keeps blinking instead of staying steady ON until I switch ON the room light. I want the LED to be ON until the room light is switched ON, not in a blinking fashion but steady ON.

import conf
from boltiot import Bolt
import json

threshold = 30


mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)


while True:
    print ("Reading sensor value")
    response = mybolt.analogRead('A0')
    data = json.loads(response)
    print("Sensor value is: " + str(data['value']))
    try:
        sensor_value = int(data['value'])
        if  sensor_value < threshold:
            mybolt.digitalWrite ('0', 'HIGH')
        else:
            mybolt.digitalWrite ('0', 'LOW')
    except Exception as e:
        print ("Error",e)

What error are you getting??? it looks correct. but however I would advice you to add a sleep time in the loop because your while loop will keep running and you will soon get rate limited

Also make a variable which will store how less the light intensity is from a pre defined value and then add this to the current intensity of the LED and then set that value as the intensity. should be easy to do.

Hey, @akshaykumar.kumar198

I hope you have learned z-score analysis.

Here is the program with code using z-score analysis…

Circuit Connection:

Code:
import conf, json, time, math, statistics, requests
from boltiot import Sms, Bolt
def compute_bounds(history_data,frame_size,factor):
if len(history_data)<frame_size :
return None

if len(history_data)>frame_size :
    del history_data[0:len(history_data)-frame_size]
Mn=statistics.mean(history_data)
Variance=0
for data in history_data :
    Variance += math.pow((data-Mn),2)
Zn = factor * math.sqrt(Variance / frame_size)
High_bound = history_data[frame_size-1]+Zn
Low_bound = history_data[frame_size-1]-Zn
return [High_bound,Low_bound]

mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)
history_data=[]

while True:
response = mybolt.analogRead(‘A0’)
data = json.loads(response)
if data[‘success’] != 1:
print(“There was an error while retriving the data.”)
print(“This is the error:”+data[‘value’])
time.sleep(10)
continue

print ("This is the value "+data['value'])
sensor_value=0
try:
    sensor_value = int(data['value'])
except e:
    print("There was an error while parsing the response: ",e)
    continue

bound = compute_bounds(history_data,conf.FRAME_SIZE,conf.MUL_FACTOR)
if not bound:
    required_data_count=conf.FRAME_SIZE-len(history_data)
    print("Not enough data to compute Z-score. Need ",required_data_count," more data points")
    history_data.append(int(data['value']))
    time.sleep(10)
    continue

try:
    if sensor_value > bound[0] :
        print ("The light level increased suddenly. Turning OFF the LED.")
        mybolt.digitalWrite('0', 'LOW')
        print("This is the response ",response)
    elif sensor_value < bound[1]:
        print ("The light level decreased suddenly. Turning ON the LED.")
        mybolt.digitalWrite('0', 'HIGH')
        print("This is the response ",response)
    history_data.append(sensor_value);
except Exception as e:
    print ("Error",e)
time.sleep(10)

-------END OF THE CODE-------

As you wanted, when the lights turn off; the LED will be ON & when the lights turn on; the LED will be OFF.

Still, If you have any problems you can ask.

@iamdxyo no error but LED is not glowing continuously, it is blinking. I want LED to be ON until the room is bright again. No issue for rate limit as I have Bolt cloud Pro.

@prajapatidhruv1110 No, this is not what I want. Read my post again:

Hi @akshaykumar.kumar198,

To control the intensity of the light you have to use anglogWrite function in your code. As I can see you have used the digitalWrite function.

Check the code below

status = ""
while True:
    print ("Reading sensor value")
    response = mybolt.analogRead('A0')
    data = json.loads(response)
    print("Sensor value is: " + str(data['value']))
    try:
        sensor_value = int(data['value'])
        if  sensor_value < 100:
            if status != "stage1": 
                mybolt.anglogWrite ('0', '100')
                status == "stage1"
        elif sensor_value < 200:
            if status != "stage2": 
                mybolt.anglogWrite ('0', '200')
                status == "stage2"
        elif sensor_value < 300:
            if status != "stage3": 
                mybolt.anglogWrite ('0', '300')
                status == "stage3"
    except Exception as e:
        print ("Error",e)
    time.sleep(10)

Apart from the sensor value, you have to also keep the status of the led. If the led status is already in the same stage then you don’t have to send the analogWrite command again.

Do let me know in case you need any other information.

2 Likes

Thank You so much @rahul.singh1

Also, how to write this in html/js code if I want to run this program through Bolt cloud?