Skip to content
Candy Sorter

Code Deep Dive: Data & Math

Now let's look at the data the robot uses to identify colors and the clever math that makes it work.

4. The Reference Chart (Color Values)

This is the robot's cheat sheet. When it sees a gem, it compares the detected RGB values to this list and finds the closest match:

colors_array.cpp
1Color colors[] = {
2  { "Pink", 255, 148, 145, 145 },
3  { "Blue", 144, 237, 255, 126 },
4  { "Red", 255, 82, 72, 72 },
5  { "Orange", 255, 145, 72, 90 },
6  { "Green", 130, 255, 150, 108 },
7  { "Blank", 255, 171, 125, -1 }
8};
ColorRGBSlide
Pink
255148145145°
Blue
144237255126°
Red
255827272°
Orange
2551457290°
Green
130255150108°
Blank
255171125STOP

Key Insight

The last number (like 145 for Pink) is the angle the slide servo moves to. "Blank" has -1 which tells the robot to stop.

5. Fine Tuning (Calibration)

Robots aren't perfect out of the box. Sometimes a motor is slightly crooked, or we need it to move slower.

calibration.cpp
1short int TopServoOffset = 0;
2short int SlideServoOffset = 0;
3
4int collectDelay = 800;
5int moveDelay = 1000;
6int topDelay = 500;

Offsets

If the motor looks crooked at 0°, change the offset to +5 or -5 to fix it without rewriting all your code.

Delays

In milliseconds (1000 ms = 1 second). Gives the physical parts time to finish moving.

6. The Math (Color Distance)

This is the smartest part of the code! How does the robot know if the color it sees is closer to "Red" or "Pink"? It uses 3D geometry!

math.cpp
float calculateDistance(uint16_t r1, uint16_t g1, uint16_t b1, 
                        uint16_t r2, uint16_t g2, uint16_t b2) {
  return sqrt(pow(r2 - r1, 2) + pow(g2 - g1, 2) + pow(b2 - b1, 2));
}

Imagine a 3D Color Cube

Picture a 3D graph where X is Red, Y is Green, and Z is Blue. Every color is a point in that 3D space.

This formula calculates the straight-line distance between the color the sensor sees and each color in memory. The smallest distance wins!

Try It Yourself

Use the sliders below to "detect" a color and watch how the robot calculates the distance to each stored color. The closest match determines where the slide moves!

color_matcher.exe

Sensor Detects

Input
R: 200
G: 100
B: 120
R
200
G
100
B
120

Nearest stored colour: Purple

Check Memory (Distance)

Pink
119.7
Blue
186.1
Red
102.1
Orange
105.0
Green
170.9
Yellow
149.7
PurpleMATCH
102.0

3D Color Space

Drag to Orbit
RGB102Pink (R:255, G:180, B:190)PinkBlue (R:100, G:180, B:255)BlueRed (R:255, G:50, B:50)RedOrange (R:255, G:140, B:40)OrangeGreen (R:80, G:220, B:100)GreenYellow (R:255, G:230, B:70)YellowPurple (R:180, G:100, B:220)Purple
Detected (You)
Stored (Memory)
Distance Formula (3D Euclidean)
distance = √((r₁ - r₂)² + (g₁ - g₂)² + (b₁ - b₂)²)