zephyrproject-rtos / zephyr

Primary Git Repository for the Zephyr Project. Zephyr is a new generation, scalable, optimized, secure RTOS for multiple hardware architectures.
https://docs.zephyrproject.org
Apache License 2.0
10.99k stars 6.69k forks source link

Add a BH1750 Sample #68840

Open maxkraft7 opened 9 months ago

maxkraft7 commented 9 months ago

Is your enhancement proposal related to a problem? Please describe. I can't seem to get the BH1705 driver working. What config files need to be changed? How do I add it into the devicetree? All of that would be easy to look up if a sample code would exist.

Describe the solution you'd like A sample project on how to interface with a BH1750 via the already existing driver.

Describe alternatives you've considered Fiddling arround myself.

github-actions[bot] commented 9 months ago

Hi @maxkraft7! We appreciate you submitting your first issue for our open-source project. 🌟

Even though I'm a bot, I can assure you that the whole community is genuinely grateful for your time and effort. 🤖💙

maxkraft7 commented 9 months ago

I got it working now, can I commit this code in a PR:

/*
 * Get a device structure from a devicetree node with compatible
 * "maxim,ds18b20". (If there are multiple, just pick one.)
 */
static const struct device *get_bh1750_device(void)
{
    const struct device *const dev = DEVICE_DT_GET_ANY(rohm_bh1750);

    if (dev == NULL) {
        // No such node, or the node does not have status "okay". 
        LOG_ERR("no device found");
        return NULL;
    }

    if (!device_is_ready(dev)) {
        LOG_ERR("Device \"%s\" is not ready; "
               "check the driver initialization logs for errors.",
               dev->name);
        return NULL;
    }

    LOG_INF("Found device \"%s\", getting sensor data\n", dev->name);
    return dev;
}

static void measureLight(){
    const struct device *dev = get_bh1750_device();

    while (dev == NULL) {
        LOG_ERR("No device found");
        dev = get_bh1750_device();
        k_sleep(K_MSEC(2000));
    }

    while (1) {
        struct sensor_value light;

        LOG_INF("Fetching sensor data");

        sensor_sample_fetch(dev);

        LOG_INF("Fetching sensor data done");

        sensor_channel_get(dev, SENSOR_CHAN_ALL, &light);

        if (light.val1 == 0)
        {
            // turn on built in led
            gpio_pin_toggle_dt(&led);
        }

        printk("Light: %d.%06d\n", light.val1, light.val2);
        k_sleep(K_MSEC(2000));
    }

}
&i2c1 {

    bh1750: bh1750@23 {
        status = "okay";
        compatible = "rohm,bh1750";
        reg = <0x23>;
    };
};