diff --git a/drivers/sensor/apds9253/apds9253.c b/drivers/sensor/apds9253/apds9253.c index b20507e9da9..d717b27aa2a 100644 --- a/drivers/sensor/apds9253/apds9253.c +++ b/drivers/sensor/apds9253/apds9253.c @@ -121,9 +121,55 @@ static int apds9253_channel_get(const struct device *dev, enum sensor_channel ch return 0; } +static int apds9253_attr_set_gain(const struct device *dev, uint8_t gain) +{ + const struct apds9253_config *config = dev->config; + struct apds9253_data *drv_data = dev->data; + uint8_t value; + + if (drv_data->gain == gain) { + return 0; + } + + static uint8_t value_map[] = { + APDS9253_LS_GAIN_RANGE_1, APDS9253_LS_GAIN_RANGE_3, APDS9253_LS_GAIN_RANGE_6, + APDS9253_LS_GAIN_RANGE_9, APDS9253_LS_GAIN_RANGE_18, + }; + + if (gain < APDS9253_LS_GAIN_RANGE_1 || gain > APDS9253_LS_GAIN_RANGE_18) { + return -EINVAL; + } + value = value_map[gain]; + + if (i2c_reg_update_byte_dt(&config->i2c, APDS9253_LS_GAIN_REG, APDS9253_LS_GAIN_MASK, + (value & APDS9253_LS_GAIN_MASK))) { + LOG_ERR("Not able to set light, sensor gain is not set"); + return -EIO; + } + + drv_data->gain = gain; + + return 0; +} + +static int apds9253_attr_set(const struct device *dev, enum sensor_channel chan, + enum sensor_attribute attr, const struct sensor_value *val) +{ + switch (attr) { + case SENSOR_ATTR_GAIN: + return apds9253_attr_set_gain(dev, val->val1); + default: + LOG_DBG("Sensor attribute not supported."); + return -ENOTSUP; + } + + return 0; +} + static int apds9253_sensor_setup(const struct device *dev) { const struct apds9253_config *config = dev->config; + struct apds9253_data *drv_data = dev->data; uint8_t chip_id; if (i2c_reg_read_byte_dt(&config->i2c, APDS9253_PART_ID, &chip_id)) { @@ -162,6 +208,8 @@ static int apds9253_sensor_setup(const struct device *dev) return -EIO; } + drv_data->gain = config->ls_gain; + return 0; } @@ -229,6 +277,7 @@ static int apds9253_init(const struct device *dev) static DEVICE_API(sensor, apds9253_driver_api) = { .sample_fetch = &apds9253_sample_fetch, .channel_get = &apds9253_channel_get, + .attr_set = &apds9253_attr_set, }; #define APDS9253_INIT(n) \ diff --git a/drivers/sensor/apds9253/apds9253.h b/drivers/sensor/apds9253/apds9253.h index 9fbe4a43bc3..a2201076c04 100644 --- a/drivers/sensor/apds9253/apds9253.h +++ b/drivers/sensor/apds9253/apds9253.h @@ -100,6 +100,7 @@ struct apds9253_data { const struct device *dev; uint32_t sample_crgb[4]; uint8_t pdata; + uint8_t gain; struct k_sem data_sem; };