Use the Sensortek STK31862 ambient light sensor in Elixir.
The STK31862 is an integrated ambient-light-to-digital converter with an I²C interface. It pairs a human-eye-response photodiode (the "ALS" channel) with an unfiltered clear photodiode (the "C" channel) and reports both as 16-bit values. This library talks to it over Circuits.I2C and converts the ALS reading to lux.
The sensor's fixed 7-bit I²C address is 0x45.
Usage
iex> {:ok, als} = STK31862.start_link(bus_name: "i2c-1")
{:ok, #PID<0.2190.0>}
iex> STK31862.get_config(als)
{:ok, %{gain: :gain_1x, integration_time: :it_100ms, persistence: :persistence_1, c_gain: :gain_1x}}
iex> STK31862.set_config(als, gain: :gain_16x, integration_time: :it_200ms)
{:ok, %{gain: :gain_16x, integration_time: :it_200ms, persistence: :persistence_1, c_gain: :gain_1x}}
iex> STK31862.measure(als)
{:ok,
%STK31862.Measurement{
light_lux: 412.5,
als_raw: 47142,
c_raw: 11203,
saturated?: false,
timestamp_ms: -576460731
}}Configuration values
:gainand:c_gain—:gain_1x,:gain_4x,:gain_16x,:gain_64x,:gain_128x:integration_time—:it_3_125ms,:it_6_25ms,:it_12_5ms,:it_25ms,:it_50ms,:it_100ms,:it_200ms,:it_400ms:persistence—:persistence_1,:persistence_2,:persistence_4,:persistence_8
Invalid values are rejected with an error such as {:error, {:invalid_gain, :nope}}.
Larger gain and longer integration time give finer resolution (more lux per
count) but saturate sooner in bright light. Pick a combination that keeps
als_raw comfortably below full scale (65535) for your expected light level.
When saturated? is true the reading is invalid — lower the gain or shorten
the integration time.
Lux accuracy note
The datasheet only specifies lux-per-count at the special 128× gain, and the ALS-channel table in datasheet rev 0.9.4 is internally inconsistent for integration times of 25 ms and longer (each entry is half of the value implied by the geometric pattern that the C channel follows). This library reproduces the datasheet values verbatim. For accurate absolute lux you should calibrate against a reference light source for your chosen gain/integration-time settings.
For details, see the API reference.
Installation
The package can be installed by adding stk31862 to your list of dependencies
in mix.exs:
def deps do
[
{:stk31862, "~> 0.1.0"}
]
endAI Usage Disclosure
The initial implementation of this library was authored largely by Claude Opus 4.8.