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:
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};| Color | R | G | B | Slide |
|---|---|---|---|---|
| Pink | 255 | 148 | 145 | 145° |
| Blue | 144 | 237 | 255 | 126° |
| Red | 255 | 82 | 72 | 72° |
| Orange | 255 | 145 | 72 | 90° |
| Green | 130 | 255 | 150 | 108° |
| Blank | 255 | 171 | 125 | STOP |
Key Insight
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.
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!
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!
Sensor Detects
Nearest stored colour: Purple
Check Memory (Distance)
3D Color Space
distance = √((r₁ - r₂)² + (g₁ - g₂)² + (b₁ - b₂)²)