Simple test

Ensure your device works with this simple test.

examples/opt4048_simpletest.py
 1# SPDX-FileCopyrightText: Copyright (c) 2025 Tim C for Adafruit Industries
 2# SPDX-License-Identifier: MIT
 3"""
 4A basic demo for using the OPT4048 tristimulus XYZ color sensor
 5
 6This example reads the sensor values from all four channels (X, Y, Z, W),
 7demonstrates setting and getting threshold values, and displays the results.
 8"""
 9
10import time
11from time import sleep
12
13import board
14
15from adafruit_opt4048 import OPT4048, ConversionTime, Mode, Range
16
17i2c = board.I2C()  # uses board.SCL and board.SDA
18# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
19sensor = OPT4048(i2c)
20
21sensor.range = Range.AUTO
22sensor.conversion_time = ConversionTime.TIME_100MS
23sensor.mode = Mode.CONTINUOUS
24while True:
25    try:
26        x, y, lux = sensor.cie
27        print(f"CIE x:{x}, y:{y}, lux: {lux}", end=" ")
28        print(f"K: {sensor.calculate_color_temperature(x, y)}")
29        time.sleep(1)
30    except RuntimeError:
31        # CRC check failed while reading data
32        pass

Webserial example

Output color data over serial for use with webserial page

examples/opt4048_webserial.py
 1# SPDX-FileCopyrightText: Copyright (c) 2025 Tim C for Adafruit Industries
 2# SPDX-License-Identifier: MIT
 3"""
 4This example reads color data from the OPT4048 sensor and outputs it
 5in a format suitable for displaying on a web page using Web Serial API.
 6
 7It continuously measures CIE x,y coordinates, lux, and color temperature.
 8
 9This example works with the web interface in the /webserial directory of the
10gh-pages branch of the Arduino driver repo: https://github.com/adafruit/Adafruit_OPT4048/tree/gh-pages,
11which can be accessed at: https://adafruit.github.io/Adafruit_OPT4048/webserial/
12"""
13
14import time
15from time import sleep
16
17import board
18
19from adafruit_opt4048 import OPT4048, ConversionTime, Mode, Range
20
21READ_INTERVAL = 0.1  # seconds
22
23i2c = board.I2C()  # uses board.SCL and board.SDA
24# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
25sensor = OPT4048(i2c)
26
27sensor.range = Range.AUTO
28sensor.conversion_time = ConversionTime.TIME_100MS
29sensor.mode = Mode.CONTINUOUS
30
31last_read_time = 0
32while True:
33    if time.monotonic() > last_read_time + READ_INTERVAL:
34        try:
35            last_read_time = time.monotonic()
36            x, y, lux = sensor.cie
37            print("---CIE Data---")
38            print(f"CIE x: {x}")
39            print(f"CIE y: {y}")
40            print(f"Lux: {lux}")
41            print(f"Color Temperature: {sensor.calculate_color_temperature(x, y)} K")
42            print("-------------")
43        except RuntimeError:
44            # CRC check failed while reading data
45            pass

Interrupt Pin example

Wait for the interrupt pin to be triggered, then read data.

examples/opt4048_interruptpin.py
 1# SPDX-FileCopyrightText: Copyright (c) 2025 Tim C for Adafruit Industries
 2# SPDX-License-Identifier: MIT
 3"""
 4A basic interrupt pin demo for using the OPT4048 tristimulus XYZ color sensor
 5
 6This example waits for the interrupt pin to be triggered,
 7then reads and displays the sensor values.
 8"""
 9
10import time
11
12import board
13import countio
14from digitalio import Pull
15
16from adafruit_opt4048 import (
17    OPT4048,
18    ConversionTime,
19    Mode,
20    Range,
21)
22
23i2c = board.I2C()  # uses board.SCL and board.SDA
24# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
25sensor = OPT4048(i2c)
26
27sensor.range = Range.AUTO
28sensor.conversion_time = ConversionTime.TIME_100MS
29sensor.mode = Mode.CONTINUOUS
30
31# counter that will track the pulses on the interrupt pin
32pin_counter = countio.Counter(board.D5, edge=countio.Edge.RISE, pull=Pull.UP)
33
34last_read_time = 0
35while True:
36    try:
37        if pin_counter.count > 0:
38            pin_counter.reset()
39            x, y, lux = sensor.cie
40            print(f"CIE x:{x}, y:{y}, lux: {lux}", end=" ")
41            print(f"K: {sensor.calculate_color_temperature(x, y)}", end=" ")
42            print(f"Read Delay: {time.monotonic() - last_read_time} sec")
43            last_read_time = time.monotonic()
44
45    except RuntimeError:
46        # error reading data
47        pass

Full test

Comprehensive test of features

examples/opt4048_fulltest.py
  1# SPDX-FileCopyrightText: Copyright (c) 2025 Tim C for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3"""
  4A comprehensive demo for using the OPT4048 tristimulus XYZ color sensor,
  5showing all capabilities.
  6
  7This example reads the sensor values from all four channels (X, Y, Z, W),
  8demonstrates setting and getting threshold values, and displays the results.
  9"""
 10
 11import time
 12
 13import board
 14
 15from adafruit_opt4048 import (
 16    OPT4048,
 17    OPT4048_FLAG_CONVERSION_READY,
 18    OPT4048_FLAG_H,
 19    OPT4048_FLAG_L,
 20    OPT4048_FLAG_OVERLOAD,
 21    ConversionTime,
 22    FaultCount,
 23    IntConfig,
 24    Mode,
 25    Range,
 26)
 27
 28READ_INTERVAL = 0.1  # seconds
 29
 30print("Adafruit OPT4048 Tristimulus XYZ Color Sensor Test")
 31
 32# Initialize the sensor
 33i2c = board.I2C()  # uses board.SCL and board.SDA
 34# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
 35sensor = OPT4048(i2c)
 36print("OPT4048 sensor found!")
 37
 38# Set low and high thresholds for interrupts
 39low_threshold_val = 1000
 40print(f"Setting low threshold to: {low_threshold_val}")
 41sensor.threshold_low = low_threshold_val
 42
 43high_threshold_val = 10000
 44print(f"Setting high threshold to: {high_threshold_val}")
 45sensor.threshold_high = high_threshold_val
 46
 47# Read back the thresholds to verify
 48print(f"Read back low threshold: {sensor.threshold_low}")
 49print(f"Read back high threshold: {sensor.threshold_high}")
 50
 51# Enable Quick Wake feature
 52print("\nEnabling Quick Wake feature...")
 53sensor.qick_wake = True
 54
 55# Read back Quick Wake status
 56print(f"Quick Wake status: {sensor.quick_wake}")
 57
 58# Set range to auto
 59print("\nSetting range to Auto...")
 60sensor.range = Range.AUTO
 61time.sleep(0.1)
 62# Read back range setting
 63print(f"Current range setting value: {sensor.range} name: {Range.get_name(sensor.range)}")
 64
 65# Set conversion time to 100ms
 66print("\nSetting conversion time to 100ms...")
 67sensor.conversion_time = ConversionTime.TIME_100MS
 68
 69# Read back conversion time setting
 70print(
 71    f"Current conversion time setting value: {sensor.conversion_time} "
 72    + f"name: {ConversionTime.get_name(sensor.conversion_time)}"
 73)
 74
 75# Set operating mode to continuous
 76print(f"\nSetting operating mode to Continuous...")
 77sensor.mode = Mode.CONTINUOUS
 78print(f"Current operating mode value: {sensor.mode} name: {Mode.get_name(sensor.mode)}")
 79
 80# Configure interrupt settings
 81print("\nConfiguring interrupt settings...")
 82sensor.interrupt_latch = True
 83sensor.interrupt_polarity = True
 84
 85# Read back interrupt settings
 86print(f"Interrupt latch mode: {'Latched' if sensor.interrupt_latch else 'Transparent'}")
 87print(f"Interrupt polarity: {'Active-high' if sensor.interrupt_polarity else 'Active-low'}")
 88
 89# Configure fault count
 90print("\nSetting fault count to 4 consecutive faults...")
 91sensor.fault_count = FaultCount.COUNT_4
 92# Read back fault count setting
 93print(
 94    f"Fault count setting value: {sensor.fault_count} "
 95    + f"name: {FaultCount.get_name(sensor.fault_count)}"
 96)
 97
 98# Configure threshold channel
 99print("\nSetting threshold channel to Channel 1 (Y)...")
100sensor.threshold_channel = 1
101channels = {
102    0: "(X)",
103    1: "(Y)",
104    2: "(Z)",
105    3: "(W)",
106}
107# Read back threshold channel setting
108print(f"Threshold channel setting: Channel {channels[sensor.threshold_channel]}")
109
110# Configure interrupt configuration
111print("\nSetting interrupt configuration to data ready for all channels...")
112sensor.interrupt_config = IntConfig.DATA_READY_ALL
113
114# Read back interrupt configuration setting
115print(
116    f"Interrupt configuration value: {sensor.interrupt_config} "
117    + f"name: {IntConfig.get_name(sensor.interrupt_config)}"
118)
119
120while True:
121    try:
122        # Read all four channels from the sensor (raw ADC values)
123        x, y, z, w = sensor.all_channels
124
125        print("Channel readings (raw values):")
126        print(f"X (CH0): {x}")
127        print(f"Y (CH1): {y}")
128        print(f"Z (CH2): {z}")
129        print(f"W (CH3): {w}")
130
131        # Calculate and display CIE chromaticity coordinates and lux
132        CIEx, CIEy, lux = sensor.cie
133        print("\nCIE Coordinates:")
134        print(f"CIE x: {CIEx}")
135        print(f"CIE y: {CIEy}")
136        print(f"Lux: {lux}")
137
138        # Calculate and display color temperature
139        color_temp = sensor.calculate_color_temperature(CIEx, CIEy)
140        print(f"Color Temperature: {color_temp} K")
141
142        # Read and print status flags
143        flags = sensor.flags
144        print("\nStatus Flags:")
145        if flags & OPT4048_FLAG_L:
146            print("- Measurement below low threshold")
147        if flags & OPT4048_FLAG_H:
148            print("- Measurement above high threshold")
149        if flags & OPT4048_FLAG_CONVERSION_READY:
150            print("- Conversion complete")
151        if flags & OPT4048_FLAG_OVERLOAD:
152            print("- Overflow condition detected")
153        if flags == 0:
154            print("- No flags set")
155
156    except RuntimeError:
157        print("Error reading sensor data")
158
159    time.sleep(1)  # read once per second