TCS3200 Sensor Issue

Hi all, I have a few questions regarding the TCS3200 sensor from DFRobot.
I am doing a project that uses the to determine the health of leaves and plants. I have done my calibration with the following code

// Define color sensor pins

#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8

// Variables for Color Pulse Width Measurements

int redPW = 0;
int greenPW = 0;
int bluePW = 0;

void setup() {

  // Set S0 - S3 as outputs
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  
  // Set Sensor output as input
  pinMode(sensorOut, INPUT);
  
  // Set Pulse Width scaling to 20%
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);
  
  // Setup Serial Monitor
  Serial.begin(9600);
}

void loop() {
  
  // Read Red Pulse Width
  redPW = getRedPW();
  // Delay to stabilize sensor
  delay(200);
  
  // Read Green Pulse Width
  greenPW = getGreenPW();
  // Delay to stabilize sensor
  delay(200);
  
  // Read Blue Pulse Width
  bluePW = getBluePW();
  // Delay to stabilize sensor
  delay(200);
  
  // Print output to Serial Monitor
  Serial.print(redPW);
  Serial.print(", ");
  Serial.print(greenPW);
  Serial.print(", ");
  Serial.print(bluePW);
  Serial.println("");
  
}



// Function to read Red Pulse Widths
int getRedPW() {

  // Set sensor to read Red only
  digitalWrite(S2,LOW);
  digitalWrite(S3,LOW);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;

}

// Function to read Green Pulse Widths
int getGreenPW() {

  // Set sensor to read Green only
  digitalWrite(S2,HIGH);
  digitalWrite(S3,HIGH);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;

}

// Function to read Blue Pulse Widths
int getBluePW() {

  // Set sensor to read Blue only
  digitalWrite(S2,LOW);
  digitalWrite(S3,HIGH);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;

}

Which is from DroneBot Workshop. The calibration is done by scanning white and black object and recording the min and max of the RGB values. Following is the updated code:

// Define color sensor pins
#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8

// Calibration Values
// Get these from Calibration Sketch
int redMin = 19;   // Red minimum value
int redMax = 255;  // Red maximum value
int greenMin = 18; // Green minimum value
int greenMax = 252; // Green maximum value
int blueMin = 11;  // Blue minimum value
int blueMax = 175; // Blue maximum value

// Variables for Color Pulse Width Measurements
int redPW = 0;
int greenPW = 0;
int bluePW = 0;

// Variables for final Color values
int redValue;
int greenValue;
int blueValue;

void setup() {
  // Set S0 - S3 as outputs
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);

  // Set Sensor output as input
  pinMode(sensorOut, INPUT);

  // Set Frequency scaling to 20%
  digitalWrite(S0, HIGH);
  digitalWrite(S1, LOW);

  // Setup Serial Monitor
  Serial.begin(9600);
}

void loop() {
  // Read Red value
  redPW = getRedPW();
  // Map to value from 0-255
  redValue = map(redPW, redMin, redMax, 255, 0);
  // Constrain the value to the 0-255 range
  redValue = constrain(redValue, 0, 255);
  // Delay to stabilize sensor
  delay(200);

  // Read Green value
  greenPW = getGreenPW();
  // Map to value from 0-255
  greenValue = map(greenPW, greenMin, greenMax, 255, 0);
  // Constrain the value to the 0-255 range
  greenValue = constrain(greenValue, 0, 255);
  // Delay to stabilize sensor
  delay(200);

  // Read Blue value
  bluePW = getBluePW();
  // Map to value from 0-255
  blueValue = map(bluePW, blueMin, blueMax, 255, 0);
  // Constrain the value to the 0-255 range
  blueValue = constrain(blueValue, 0, 255);
  // Delay to stabilize sensor
  delay(200);

  // Print output to Serial Monitor
  Serial.print(redValue);
  Serial.print(",");
  Serial.print(greenValue);
  Serial.print(",");
  Serial.println(blueValue);
}

// Function to read Red Pulse Widths
int getRedPW() {
  // Set sensor to read Red only
  digitalWrite(S2, LOW);
  digitalWrite(S3, LOW);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;
}

// Function to read Green Pulse Widths
int getGreenPW() {
  // Set sensor to read Green only
  digitalWrite(S2, HIGH);
  digitalWrite(S3, HIGH);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;
}

// Function to read Blue Pulse Widths
int getBluePW() {
  // Set sensor to read Blue only
  digitalWrite(S2, LOW);
  digitalWrite(S3, HIGH);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;
}

After the calibration, I generated an GUI using python to display the colour of the detected object. The following is the code:

import tkinter as tk
import serial
import time
import threading

# Define a dictionary of RGB color codes and their corresponding color names
color_database = {
    "#FF0000": "Red",
    "#00FF00": "Green",
    "#0000FF": "Blue",
    "#FFFF00": "Yellow",
    "#FF00FF": "Magenta",
    "#00FFFF": "Cyan / Aqua",
    "#FFFFFF": "White",
    "#000000": "Black",
}

# Initialize serial communication with Arduino (use the correct COM port)
ser = serial.Serial('COM6', baudrate=9600)  # Replace 'COM6' with the correct port

# Function to look up and display color name and color
def lookup_color():
    try:
        # Read RGB values from Arduino via serial connection
        rgb_values = ser.readline().decode().strip().split(',')
        r, g, b = [int(val) for val in rgb_values]

        # Initialize color_code
        color_code = f"#{r:02X}{g:02X}{b:02X}"

        # Check for various color ranges
        if 0 <= r <= 15 and 0 <= g <= 15 and 0 <= b <= 15:
            color_name = "Black"
        elif 200 <= r <= 255 and 0 <= g <= 50 and 0 <= b <= 50:
            color_name = "Red"
        elif 0 <= r <= 50 and 200 <= g <= 255 and 0 <= b <= 50:
            color_name = "Green"
        elif 0 <= r <= 50 and 0 <= g <= 50 and 200 <= b <= 255:
            color_name = "Blue"
        elif 250 <= r <= 255 and 250 <= g <= 255 and 250 <= b <= 255:
            color_name = "white"
        elif 200 <= r <= 220 and 200 <= g <= 220 and 135 <= b <= 151:
            color_name = "Green - Healthy Leaf"
        elif 214 <= r <= 237 and 209 <= g <= 231 and 150 <= b <= 166:
            color_name = "Green - Healthy Leaf"
        elif 226 <= r <= 250 and 221 <= g <= 245 and 182 <= b <= 202:
            color_name = "Yellow - Senescence Leaf"
        elif 214 <= r <= 236 and 188 <= g <= 208 and 150 <= b <= 166:
            color_name = "Brown - Dead Leaf"
        elif 242 <= r <= 255 and 227 <= g <= 251 and 209 <= b <= 231:
            color_name = "Brown - Dead Leaf"



        else:
            # Look up color name in the database
            color_name = color_database.get(color_code, "Unknown")

        # Update the UI elements
        color_label.config(text=f"Color Name: {color_name}")
        rgb_label.config(text=f"RGB Value: R={r}, G={g}, B={b}")
        canvas.config(bg=color_code)
    except Exception as e:
        print(f"Error: {e}")

# Create a tkinter window
window = tk.Tk()
window.title("Color Detection and Lookup")

# Create and configure UI elements
color_label = tk.Label(window, text="Color Name: ")
color_label.pack(pady=10)

rgb_label = tk.Label(window, text="RGB Value: R=0, G=0, B=0")
rgb_label.pack(pady=10)

canvas = tk.Canvas(window, width=100, height=100)
canvas.pack()

# Set the scanning interval in seconds (e.g., 2 seconds)
scanning_interval = 0.02

# Function to continuously scan for colors
def continuous_scan():
    while True:
        lookup_color()  # Call the lookup_color function
        window.update()  # Update the tkinter window
        time.sleep(scanning_interval)  # Wait for the specified interval

# Create a separate thread for continuous scanning
scan_thread = threading.Thread(target=continuous_scan)
scan_thread.daemon = True  # Allow the thread to exit when the main program exits
scan_thread.start()  # Start the continuous scanning thread

# Start the tkinter main loop
window.mainloop()

I am able to display the colour but the RGB values will fluctuate (around 5%-10%) of values when.

I have also made a black box and mounted the sensor within it to reduce the influence of ambient lighting. But the fluctuation is still occurring. Would like to check if anyone got any solutions/advice to improve the situation.

Thank you.

Sensor value fluctuations are normal and expected. Average some number of readings to reduce that.

Keep in mind that reflected color depends extremely strongly on the light source spectrum, intensity and angle of incidence, so it will take some effort to get reproducible results.