Files
Smart-granary-code/components/bh1750/bh1750_use.c

58 lines
1.5 KiB
C

#include <stdio.h>
#include "esp_log.h"
#include "driver/i2c_master.h"
#include "bh1750.h"
#include "bh1750_use.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
static const char *TAG = "BH1750_USE";
static i2c_master_bus_handle_t s_i2c_bus_handle = NULL;
static bh1750_handle_t s_bh1750_handle = NULL;
i2c_master_bus_handle_t bh1750_get_i2c_bus_handle(void)
{
return s_i2c_bus_handle;
}
esp_err_t bh1750_user_init(void)
{
if (s_i2c_bus_handle == NULL) {
i2c_master_bus_config_t bus_config = {
.clk_source = I2C_CLK_SRC_DEFAULT,
.i2c_port = I2C_NUM_0,
.scl_io_num = (gpio_num_t)BH1750_I2C_SCL_IO,
.sda_io_num = (gpio_num_t)BH1750_I2C_SDA_IO,
.glitch_ignore_cnt = 7,
};
ESP_ERROR_CHECK(i2c_new_master_bus(&bus_config, &s_i2c_bus_handle));
}
esp_err_t ret = bh1750_create(s_i2c_bus_handle, BH1750_I2C_ADDRESS_DEFAULT, &s_bh1750_handle);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "BH1750 设备创建失败");
return ret;
}
return bh1750_power_on(s_bh1750_handle);
}
esp_err_t bh1750_user_read(float *lux)
{
if (s_bh1750_handle == NULL) return ESP_ERR_INVALID_STATE;
bh1750_power_on(s_bh1750_handle);
bh1750_set_measure_mode(s_bh1750_handle, BH1750_ONETIME_1LX_RES);
vTaskDelay(pdMS_TO_TICKS(180));
return bh1750_get_data(s_bh1750_handle, lux);
}
void bh1750_user_deinit(void)
{
if (s_bh1750_handle) {
bh1750_delete(s_bh1750_handle);
s_bh1750_handle = NULL;
}
}