Skip to content

TSL2591 lux property can return negative values at low light — should clamp to 0 #33

@KevinAndani

Description

@KevinAndani

Summary
The lux property in the CircuitPython TSL2591 driver can return small negative lux values (e.g. -3.51) in low-light/night conditions. Lux is a physical quantity that should not be negative; at minimum it should be clamped to 0. I encountered negative values while reading the sensor at night.

Repository / File
Repository: Adafruit_CircuitPython_TSL2591
File: adafruit_tsl2591.py
Context: the lux calculation computes two candidate lux values (lux1, lux2) and currently returns max(lux1, lux2) which can be negative if both candidates are negative due to noise / IR-dominant readings.

Actual behavior
lux can be negative (e.g. -3.51) under low-light conditions.

Expected behavior
lux should never be negative. When the computed lux candidates are negative (due to noise, IR-dominant conditions, or small counts), the method should return 0.0 (or otherwise clamp to a non-negative value).

Suggested fix
Clamp the returned lux to be non-negative. For example, replace:

lux1 = (channel_0 - (_TSL2591_LUX_COEFB * channel_1)) / cpl
lux2 = ((_TSL2591_LUX_COEFC * channel_0) - (_TSL2591_LUX_COEFD * channel_1)) / cpl
return max(lux1, lux2)

with:

# ensure lux is never negative
return max(0.0, lux1, lux2)

This is a minimal, backwards-compatible change that avoids reporting non-physical negative lux values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions