Skip to content
Candy Sorter

Code Deep Dive: Setup

Let's break down the Candy Sorter code piece by piece. In this first part, we'll understand how the code gets ready to run.

1. The Toolbox (Libraries)

Just like you need a hammer and nails to build a birdhouse, a programmer needs "Libraries" to build code. These are pre-written packs of code that let us talk to complex hardware easily.

libraries.cpp
#include <Servo.h>
#include <Wire.h>
#include <Adafruit_TCS34725.h>
Servo.hContains all the complex math needed to control the servo motors (the robot's muscles).
Wire.hHelps the microcontroller talk to the color sensor. It's like a translator for the "I2C" language.
Adafruit_TCS34725.hA specific instruction manual for your color sensor.

2. The Nervous System (Pin Setup)

We need to tell the code exactly where we plugged the wires in. If we plug the motor into pin 14 but tell the code it's on pin 2, the arm won't move!

pins.cpp
1//I2C colour sensor pins
2#define SDA_PIN 5  //D1 - Blue
3#define SCL_PIN 4  //D2 - Green
4
5//Servo pins
6int TopServoPin = 14;   //D5 - Yellow
7int SlideServoPin = 12; //D6 - Purple

Tip

#define creates a nickname. Instead of remembering "Pin 5", we can just type SDA_PIN.

3. The ID Card Template (Color Structure)

How does a robot know what "Pink" is? We have to define it! A computer sees color as a mix of Red, Green, and Blue (RGB).

color_struct.cpp
struct Color {
  const char* name;
  uint16_t r, g, b;
  int number;
};

struct is like creating a custom ID card template. Every color gets these 5 fields:

name — The color's label (e.g., "Pink")
r — Red value (0-255)
g — Green value (0-255)
b — Blue value (0-255)
number — The servo angle for this color