From Lux to Logic: Integrating the BH1750 Light Sensor with ASI Biont’s AI Agent for Smarter Automation

Introduction

Light is one of the most fundamental environmental variables — and measuring it accurately opens the door to countless automation possibilities. The BH1750, a digital ambient light sensor based on the I2C protocol, outputs illuminance directly in lux, with a range of 1 to 65535 lx and a resolution as fine as 1 lx. It’s cheap (under $2), widely available, and used in everything from smart lighting systems to greenhouse control.

But a sensor alone is just a piece of hardware. What if you could connect it to an AI agent that not only reads the lux values but also makes intelligent decisions — adjusting blinds, switching lights, logging trends, or even alerting you when light levels drop below a threshold? That’s exactly what ASI Biont’s AI agent does. In this guide, we’ll show you how to integrate a BH1750 (connected to an ESP32 via I2C) with ASI Biont using MQTT, and let the AI handle the rest.

No dashboards, no hardcoded logic — just a conversation with the AI that sets up everything in seconds.

Why Connect a Light Sensor to an AI Agent?

A standalone BH1750 can send lux values to a microcontroller, but an AI agent adds context and adaptability:

  • Context-aware decisions: The AI can combine light readings with time of day, weather API data, or occupancy sensors to decide whether to dim lights or close curtains.
  • Proactive alerts: If light levels in a greenhouse drop too low for plant growth, the AI can send a Telegram notification or trigger supplementary LEDs.
  • Trend analysis: The AI logs data over time, detects patterns (e.g., “the room gets dark at 4 PM in winter”), and adjusts schedules automatically.
  • Multi-device orchestration: The same AI can control a smart plug, an MQTT-enabled light, and a motorized blind — all based on the BH1750 input.

Connection Method: ESP32 + BH1750 → MQTT → ASI Biont

We chose MQTT as the bridge because:
- The ESP32 has built-in Wi-Fi and can run MicroPython or Arduino code to publish sensor data to an MQTT broker.
- ASI Biont’s AI agent can subscribe to the same topic using a Python script with the paho-mqtt library, executed in the execute_python sandbox.
- MQTT is lightweight, reliable, and perfect for IoT sensor data.

Hardware Setup

Component Pin (ESP32) Notes
BH1750 VCC 3.3V Power supply
BH1750 GND GND Common ground
BH1750 SDA GPIO21 I2C data line
BH1750 SCL GPIO22 I2C clock line
ESP32 - Any ESP32 development board

Wiring diagram:

ESP32         BH1750
3.3V  ──────  VCC
GND   ──────  GND
GPIO21 ────── SDA
GPIO22 ────── SCL

MicroPython Code for ESP32 (Publishing to MQTT)

This code runs on the ESP32. It reads the BH1750 every 10 seconds and publishes the lux value to the topic sensor/light/bh1750.

import network
import time
import ujson
from machine import Pin, I2C
from umqtt.simple import MQTTClient

# I2C setup (SDA=GPIO21, SCL=GPIO22)
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)

# BH1750 address: 0x23 (ADDR pin low)
BH1750_ADDR = 0x23

def read_light():
    # Send measurement command (continuous high-res mode)
    i2c.writeto(BH1750_ADDR, bytes([0x10]))
    time.sleep_ms(120)  # wait for measurement
    data = i2c.readfrom(BH1750_ADDR, 2)
    lux = (data[0] << 8 | data[1]) / 1.2
    return round(lux, 1)

# Wi-Fi credentials
WIFI_SSID = "YourWiFiSSID"
WIFI_PASS = "YourWiFiPassword"

# MQTT broker settings
MQTT_BROKER = "192.168.1.100"  # or broker.hivemq.com
MQTT_TOPIC = b"sensor/light/bh1750"

# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
    time.sleep(1)
print("Wi-Fi connected")

# Connect to MQTT
client = MQTTClient("esp32_bh1750", MQTT_BROKER)
client.connect()
print("MQTT connected")

while True:
    lux = read_light()
    payload = ujson.dumps({"lux": lux, "device": "esp32_bh1750"})
    client.publish(MQTT_TOPIC, payload)
    print("Published:", payload)
    time.sleep(10)

AI Agent Integration: How ASI Biont Reads and Acts on the Data

Once the ESP32 is publishing to the MQTT broker, you simply tell the AI agent in natural language what you want to do. For example:

“Connect to MQTT broker at 192.168.1.100, subscribe to sensor/light/bh1750, and if lux drops below 200, publish a command to turn on the smart light via MQTT topic home/livingroom/light with payload ‘ON’.”

The AI agent then writes and executes a Python script inside its sandbox (execute_python) using the paho-mqtt library.

Example: AI-Generated Python Script (Runs in ASI Biont Sandbox)

import paho.mqtt.client as mqtt
import time

LIGHT_THRESHOLD = 200  # lux

def on_message(client, userdata, msg):
    import json
    try:
        data = json.loads(msg.payload)
        lux = data.get("lux", 0)
        print(f"Received lux: {lux}")
        if lux < LIGHT_THRESHOLD:
            # Publish command to smart light
            client.publish("home/livingroom/light", "ON")
            print("Light turned ON due to low illuminance")
    except Exception as e:
        print(f"Error: {e}")

# Set up MQTT client
client = mqtt.Client()
client.on_message = on_message
client.connect("192.168.1.100", 1883, 60)
client.subscribe("sensor/light/bh1750")
client.loop_start()

# Keep listening (sandbox timeout is 30 seconds, so we use a short loop)
time.sleep(25)  # listen for 25 seconds
client.loop_stop()
print("Session ended")

Note: The sandbox has a 30-second timeout, so the AI typically runs a polling loop with time.sleep() or uses paho-mqtt’s loop(timeout=...) within that limit. For persistent automation, the AI can instead use the industrial_command tool with the MQTT protocol to subscribe continuously.

Real-World Scenarios

1. Smart Office: Automatic Blinds

  • Setup: BH1750 on each window, ESP32 publishes to MQTT.
  • AI task: If lux > 10000 (direct sunlight), publish to blinds/office/close. If lux < 300, publish blinds/office/open.
  • Benefit: Energy savings, reduced glare, improved comfort.

2. Greenhouse: Growth Light Control

  • Setup: BH1750 inside greenhouse, connected to ESP32 with relay for supplemental LEDs.
  • AI task: Maintain lux between 5000 and 8000. If below, turn on LEDs via MQTT relay topic. Log daily light integral (DLI) to a PostgreSQL database.
  • Benefit: Optimized plant growth, reduced electricity waste.

3. Home Theater: Dynamic Lighting

  • Setup: BH1750 near screen, smart bulbs on MQTT.
  • AI task: When movie starts (detected via HDMI CEC or manual trigger), dim lights based on ambient light — brighter if it’s daytime, dimmer at night.
  • Benefit: Immersive experience without manual adjustment.

Why This Integration Matters

With ASI Biont, you don’t need to write custom firmware or build a full dashboard. The AI agent does the heavy lifting:
- You describe the device and connection method in plain English.
- The AI generates the integration code (MicroPython for ESP32, Python for MQTT subscription) and executes it.
- You can modify the logic on the fly — just ask the AI to “change the threshold to 500 lux” or “log data to a CSV file”.

And because the AI can use any of the supported protocols (MQTT, Modbus, COM port via bridge, HTTP API, SSH), you can connect virtually any sensor or actuator — not just the BH1750.

Conclusion

The BH1750 is a small, precise light sensor. When paired with an ESP32 and MQTT, it becomes a data source. When connected to ASI Biont’s AI agent, it becomes part of an intelligent system that adapts to your needs in real time.

Whether you’re automating your home, optimizing a greenhouse, or building a smart office, the AI agent handles the integration — you just tell it what to do.

Ready to make your light sensor smart? Go to asibiont.com, start a chat with the AI agent, and describe your BH1750 setup. The AI will write the code and connect everything in seconds.


Have a different sensor? The same workflow works for any I2C, UART, SPI, or analog device — just ask the AI.

← All posts

Comments