Search code examples
pythontimeraspberry-pifrequencysampling

Python: How to increase sampling rate of TCS34725 Color Sensor on RaspberryPi


I am trying to measure the LED lighting flickering rate through an Adafruit sensor: TCS34725 on Raspberry Pi4. I am either reading the internally calculated lux value or raw data(RGB).

According to the TCS34725 library documentation, the minimum sampling rate for the sensor is 2.4ms (~400Hz). The sensor itself has a clock frequency of 400kHz. Python TCS34725 library

However, when I run a test script, the time cycles for each sampling are at ~0.0155769 seconds (~60 Hz), for both raw values or calculated lux value.

sensor.lux # takes abt 0.0167 s  for script below
sensor.color_raw # takes abt 0.0155 s for script below

Why I can't achieve a higher sampling rate nearer to 400 Hz? Is my script delaying the timing?

Test Script:

import board
import busio
import adafruit_tcs34725
import time
import numpy as np

i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_tcs34725.TCS34725(i2c)

"""
integration_time - The integration time of the sensor in milliseconds.  Must be a value between 2.4 and 614.4.
gain - The gain of the sensor, must be a value of 1, 4, 16, 60.
"""

sensor.integration_time = 2.4 #lowest possible of 2.4ms
sensor.gain = 1

lx = []
tm = []

loop_delay = time.time() + 60


while time.time() < loop_delay:
    t = time.time()
    k = sensor.lux
    lx.append(k)
    tm.append(t)

t_0 = tm[0]
t_norm = [i-t_0 for i in tm]

Z = np.column_stack((t_norm,lx))
np.savetxt('/home/pi/share/py/flicker/test.csv', Z, delimiter=",", fmt='%1.7f')


print('end')

Similarly, using another library driver, by setting the delay (line #139) between consequent measurements to zero (False), also produces the same ~60Hz. Python drivers for the TCS34725 light color sensor by Dexter Industries

Any insights/suggestions on how to obtain a near 400 Hz sampling rate?


Solution

  • If you peek into the library's code at what happens when you access .lux, you'll find that all of this code gets executed.

    It involves (at least)

    • one I2C write+read for ATIME
    • one I2C write+read for .gain
    • four I2C write+reads for the raw color
    • all that calculation

    If you need to squeeze out more performance, I would recommend accessing those manually, then doing the computations later "offline" once you've captured your data.