Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
BETTESWORTHConstruction
Arduino

IoT-Based Color Sorting Machine Using ESP8266 and ThingSpeak

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This project is a small educational color-sorting machine: an ESP8266 reads a TCS3200 color sensor, classifies an object locally, moves servo-operated gates, counts each result, and uploads cumulative totals to ThingSpeak. The ESP8266—not ThingSpeak—must handle the real-time sensing and sorting loop. ThingSpeak is used for remote logging, charts, and monitoring.

It works best with uniform, opaque objects presented at a fixed distance under controlled lighting. It is not an industrial vision system, and its thresholds, servo angles, and mechanical dimensions must be calibrated for the particular build.

As an Amazon Associate I earn from qualifying purchases.

How the machine works

The operating sequence is:

  1. An object enters a repeatable presentation position.
  2. The TCS3200 illuminates and measures the object.
  3. The sensor selects red, blue, and green photodiode filters and outputs a frequency for each measurement.
  4. The ESP8266 reads those frequencies and compares calibrated values with the configured color classes.
  5. A servo releases or presents the object, while a second servo positions the destination gate.
  6. The appropriate color counter increases.
  7. The ESP8266 periodically uploads the counters to ThingSpeak.

The reference design uses a cardboard or tabletop chute, two servos, predefined color bins, and a NodeMCU ESP8266 rather than a conveyor, camera, or pneumatic sorting system. See the original project description for the prototype arrangement and example implementation: Hackster.io project.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

System architecture

Object
  ↓
Presentation chute and release servo
  ↓
TCS3200 color sensor
  ↓
ESP8266 local classification
  ├── Presentation servo
  ├── Sorting-gate servo
  └── Wi-Fi → ThingSpeak counters and charts

This separation is important. Cloud communication is too slow and too dependent on network availability to control a moving gate. Sorting should continue if Wi-Fi or ThingSpeak is unavailable; the cloud should receive delayed or batched totals afterward.

#1 Best Overall
2 Pcs TCS34725 RGB Light Color Sensor Recognition Module for Arduino
  • 2 Pcs TCS34725 RGB Light Color Sensor Recognition Module
  • Red, Green, Blue (RGB), and White Light Sensing with IR Blocking Filter
  • Programmable Analog Gain and Integration Time
  • 3,800,000:1 Dynamic Range Input Voltage Levels Compatible with VDD or 1.8 V
  • I2C Fast Mode Compatible Interface Data Rates up to 400 kbit/s

What you need

Component Purpose Important consideration
NodeMCU ESP8266 Local controller and Wi-Fi connection Account for GPIO boot-state behavior and limited memory.
TCS3200/TCS230 module Measures filtered light as frequency Requires fixed geometry, controlled lighting, and calibration.
Two servo motors Object release and destination-gate movement Power them from a separate regulated 5 V supply.
3.3 V supply ESP8266 and sensor logic Check the voltage requirements of the particular breakout board.
5 V servo supply Servo power Size it for startup and stall current; connect grounds together.
Chute, gates, frame, and bins Controls object position and collection Mechanical repeatability directly affects classification.
Wires, breadboard, USB cable Prototyping and programming Use a more secure connection for a permanent installation.

Understanding the TCS3200

The TCS3200 contains photodiodes with red, blue, green, and clear filters. Control pins S2 and S3 select the filter. The OUT pin produces a frequency related to the measured light intensity, and S0 and S1 select the frequency scaling.

Photodiode selection

S2 S3 Filter
LOW LOW Red
LOW HIGH Blue
HIGH LOW Clear
HIGH HIGH Green

Output-frequency scaling

S0 S1 Scaling
LOW LOW Power down
LOW HIGH 2%
HIGH LOW 20%
HIGH HIGH 100%

The example project uses 100% scaling by driving S0 and S1 HIGH. Module labeling, onboard LEDs, voltage behavior, and pin arrangements can vary, so verify the board you have. A TCS3200 does not inherently know that an object is “orange” or “yellow”; the firmware defines those application-specific classes from measured data.

Representative wiring

Device pin NodeMCU connection
TCS3200 VCC 3.3 V
TCS3200 GND GND
S0 D4
S1 D5
S2 D6
S3 D7
OUT D8
OE GND
Presentation-servo signal D2
Sorting-gate signal D3

This is a representative mapping from the reference project, not a universal NodeMCU pinout. Confirm the board’s GPIO mapping before wiring. D8 corresponds to GPIO15 on many ESP8266 boards and is involved in bootstrapping, so external circuitry connected to it can prevent startup if it holds the pin in the wrong state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Power and wiring precautions

  • Do not power two servos from the NodeMCU 3.3 V output.
  • Use a regulated 5 V rail with adequate peak current capacity for the servos.
  • Connect the servo-supply ground to NodeMCU ground so signal voltages have a common reference.
  • Keep servo power wiring short and substantial, and add bulk capacitance near the servo supply if resets occur.
  • Check that the TCS3200 module’s OUT signal is safe for an ESP8266 input.
  • Keep sensor wiring away from noisy servo power wiring where practical.

Create the ThingSpeak channel

Create a channel at ThingSpeak and assign fields to cumulative counters. One practical arrangement is:

Field Meaning
Field 1 Red-class count
Field 2 Orange-class count
Field 3 Green-class count
Field 4 Yellow-class count
Status Optional machine state or last classification
Location Optional machine location

To find the channel credentials, use Channels → My Channels → select the channel → API Keys. The device needs the Write API Key to update data. A Read API Key is used for private-channel reads; public-channel reads do not require one. ThingSpeak documents channel permissions and keys at Channel Control.

Use placeholders in code:

const char* WIFI_SSID = "YOUR_WIFI_SSID";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* THINGSPEAK_WRITE_KEY = "YOUR_WRITE_API_KEY";
unsigned long THINGSPEAK_CHANNEL_ID = YOUR_CHANNEL_ID;

Never publish a real Wi-Fi password or API key. If a key has appeared in a public tutorial, repository, screenshot, or video, regenerate it. A write key can allow unauthorized data to be added to the channel.

Development environment

Install the Arduino IDE, add ESP8266 board support, and install an ESP8266-compatible servo library and the ThingSpeak library if you use its API wrapper. The official ThingSpeak ESP8266 example uses ESP8266WiFi.h and an ESP8266-compatible client; consult the current example for library compatibility rather than assuming an old library version will work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Teyleten Robot TCS34725 TCS-34725 Sensor Recognition Module RGB Sensor for Arduino (3pcs)
  • Brand new original chip
  • Module Data Rates can up to 400 kbit/s,power is low,is 2.5-uA Sleep State
  • module input Voltage Levels Compatible with VDD or 1.8 V Bus
  • module Programmable Upper and Lower Thresholds with Persistence Filter

ThingSpeak also supports direct REST and MQTT interfaces. Its documented REST endpoint is:

https://api.thingspeak.com/update.json

A request includes api_key and one or more field<X> values. A successful write returns an entry identifier; failure returns 0. Details are in the ThingSpeak write-data documentation.

Read the sensor safely

The basic method selects a filter and measures the duration of pulses on OUT. A longer pulse generally represents a lower output frequency, so use the same measurement convention consistently throughout calibration and classification.

unsigned long readColor(bool s2State, bool s3State) {
  digitalWrite(S2, s2State);
  digitalWrite(S3, s3State);
  delayMicroseconds(200); // allow the filter selection to settle

  unsigned long total = 0;
  const int samples = 5;

  for (int i = 0; i < samples; ++i) {
    unsigned long t = pulseIn(SENSOR_OUT, LOW, 30000);
    if (t == 0) return 0; // timeout: no valid reading
    total += t;
  }
  return total / samples;
}

A robust reading routine should discard timeouts, take several samples, use a mean or median, and reject unstable readings. For better repeatability, normalize readings against white and dark reference samples. Avoid treating the raw values in an example sketch as universal thresholds: they depend on sensor distance, LED intensity, object surface, background, and the particular module.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Calibrate before sorting

Calibration is the difference between a demonstration that works in one setup and a machine that can be reproduced. Fix the sensor height, object orientation, chute background, and lighting before collecting data.

  1. Build a light shield or enclosure to exclude direct sunlight and changing room light.
  2. Place one target object at the exact sensing position.
  3. Record red, green, and blue readings repeatedly through the serial monitor.
  4. Repeat for every intended color and for colors that are easily confused.
  5. Calculate the typical value and spread for each channel.
  6. Choose class boundaries with a margin between measured groups.
  7. Test ambiguous readings and define an UNKNOWN result.
  8. Recalibrate after changing the sensor height, LEDs, chute, background, or object material.

Use a classifier that produces one deliberate result rather than several independent if statements. Overlapping conditions can cause the same sample to satisfy multiple classes. A useful starting structure is:

enum ColorClass {
  RED,
  ORANGE,
  GREEN,
  YELLOW,
  UNKNOWN
};

For a more robust design, convert readings to normalized ratios or compare them with calibrated class centroids. Require two or three consistent readings before accepting a class, and send uncertain samples to an unknown bin instead of forcing a guess.

Servo control and machine states

One servo can present or release the object while the second moves a gate to the selected bin. The gate positions must be found mechanically; example angles such as 73°, 107°, 132°, and 162° are calibration values for one arrangement, not general settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A state machine is more reliable than a long sequence of blocking delays:

IDLE
→ PRESENT_OBJECT
→ SETTLE
→ MEASURE
→ CLASSIFY
→ MOVE_GATE
→ RELEASE
→ WAIT_FOR_EXIT
→ LOG
→ IDLE

Short delays may be acceptable in a classroom demonstration, but indefinite Wi-Fi waits and long blocking pauses can stop sorting and slow recovery. Add servo travel limits, a jam timeout, and a safe recovery position. Ensure the chute is wide enough for the objects, the gate cannot bind, and bins cannot overflow.

Uploading counters to ThingSpeak

For a slow tabletop demonstration, the firmware can periodically upload all counters together:

ThingSpeak.setField(1, redCount);
ThingSpeak.setField(2, orangeCount);
ThingSpeak.setField(3, greenCount);
ThingSpeak.setField(4, yellowCount);

int result = ThingSpeak.writeFields(channelId, writeKey);

Sending all counters in one update keeps the fields time-aligned and reduces requests. It is usually better than sending a separate request for every object.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ThingSpeak’s current documentation states that free channels accept updates no faster than once every 15 seconds. Paid licensing can support faster update rates, depending on the account and license. Confirm current limits at ThingSpeak Channel Control and the licensing FAQ. A machine that sorts several objects per minute should maintain counters locally and upload periodically or in batches. A faster cloud plan still does not make ThingSpeak suitable for timing-critical servo control.

When Wi-Fi is unavailable, continue local sorting, retain counts in RAM, reconnect with bounded retries, and upload the latest totals after reconnection. If counts must survive a power loss, store them periodically in flash rather than on every object, because frequent writes can wear flash memory.

Rank #4
10pcs 4Pin RGB Module KY-016 Three Colors 3 Color RGB LED Sensor Module for Arduino
  • 10pcs 4Pin RGB Module KY-016 Three Colors 3 Color RGB LED Sensor Module For Arduino
  • RGB LED module LED is made of a plug-in full-color, by R, G, B three-pin PWM input voltage can be adjusted in three primary colors (red / blue / green) strength in order to achieve full color mixing effect.
  • Three primary colors can be mixed to get different colors by adjusting the PWM
  • Can interface with a variety of microcontrollers
  • Operating voltage: 5V LED drive mode: common cathode drive

Testing and measuring performance

Do not claim a general accuracy percentage without test data. For each intended color, test at least 20–30 objects under the same conditions and record:

  • Correct classifications.
  • False classifications by color.
  • Unknown results.
  • Duplicate counts.
  • Throughput and average cycle time.
  • Lighting, object distance, orientation, and surface finish.

A confusion matrix is more informative than saying the machine is “accurate.” A result that is reliable for matte colored balls may fail for transparent, reflective, wet, textured, multicolored, or orientation-dependent objects.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

All colors produce similar results

Check the sensor-to-object distance, filter-selection wiring, sensor LED operation, and ambient light. Add a light shield, use a consistent matte background, center the object, and repeat calibration. Copied thresholds are unlikely to work unchanged.

The sensor returns zero or times out

Check VCC, ground, OE, the OUT connection, and the selected frequency scaling. Confirm that the object is close enough and that pulseIn() has a timeout long enough for the chosen scaling. Print raw readings before attempting classification.

The ESP8266 resets when a servo moves

This is usually a power problem. Use a separate regulated 5 V servo supply, connect grounds, shorten power wiring, add bulk capacitance, and check for mechanical binding or servo stall current. Never treat the NodeMCU 3.3 V regulator as a two-servo power source.

Servos move unpredictably

Check the common ground, signal wiring, supply voltage, and mechanical end stops. Confirm that the selected GPIOs do not interfere with boot. Test each servo independently and reduce unnecessary movement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wi-Fi does not connect

Verify the SSID, password, 2.4 GHz network availability, antenna position, and board selection. Add a connection timeout instead of waiting forever; local sorting should not depend on a successful cloud connection.

Best Value
Sale
D-FLIFE 2pcs TCS-34725 TCS34725 RGB Light Color Sensor Colour Recognition Module RGB Color Sensor with IR Filter and White LED for Arduino
  • Strong point: Input Voltage Levels Compatible with VDD or 1.8 V Bus
  • Low Power: 2.5-uA Sleep State
  • Characteristic: Programmable Upper and Lower Thresholds with Persistence Filter
  • Feature: I2C Fast Mode Compatible Interface
  • Advantage: Data Rates up to 400 kbit/s

ThingSpeak returns zero or rejects updates

Check the channel ID, write key, network connection, TLS/client compatibility, account limits, and update interval. A free channel must respect the 15-second interval. Log the library return value and, when using REST, inspect the HTTP response.

The same object is counted repeatedly

Add an object-present and object-left state. Wait until the object clears the sensor before starting another cycle, add a cooldown, or use an IR break-beam sensor for entry and exit confirmation.

The machine jams

Check object diameter against chute width, gate friction, servo travel, object spacing, and bin capacity. Add a jam timeout and a manual recovery position rather than allowing a stalled servo to remain powered indefinitely.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Advantages and limitations

The ESP8266 is inexpensive, includes Wi-Fi, and has enough capability for one frequency-output sensor and a few servos. The TCS3200 is simple to interface because it provides a digital frequency output rather than requiring an analog-to-digital converter. ThingSpeak provides a convenient dashboard without requiring a separate web server.

The limitations are equally important. ESP8266 memory is limited, GPIO bootstrapping can complicate wiring, servo noise can cause resets, and TLS libraries consume resources. The TCS3200 is sensitive to distance, ambient light, gloss, shadows, and orientation. ThingSpeak dashboards show reported counts but do not prove that the physical sorting was correct.

Possible improvements

  • Add a break-beam or IR object sensor so each object has a defined entry and exit.
  • Use a controlled enclosure and fixed LED illumination.
  • Use normalized RGB values or a nearest-centroid classifier instead of copied raw thresholds.
  • Store a local event log or add a display for offline diagnosis.
  • Use an ESP32 when additional processing, memory, or peripherals are needed.
  • Use MQTT or a local dashboard when lower-latency telemetry is required.
  • Use a camera and computer vision for complex shapes, mixed colors, or multicolored objects.
  • Use industrial optical sensors, guarded mechanics, jam detection, emergency stopping, and formal validation for production work.

Is this suitable for production?

No—not without substantial redesign and validation. This build is appropriate for education, a tabletop demonstration, and counting relatively uniform objects under controlled conditions. It is not suitable by itself for high-speed conveyor sorting, outdoor operation, safety-critical decisions, or production-critical classification.

A production system would need controlled optics and lighting, repeatable material handling, protection from jams, safety guarding, emergency-stop provisions, secure credentials, offline operation, measured throughput, and documented classification performance. ThingSpeak may remain useful for monitoring, but it should remain outside the real-time control loop. For commercial use, review the current ThingSpeak license terms rather than assuming the free option applies.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

Bestseller No. 1
2 Pcs TCS34725 RGB Light Color Sensor Recognition Module for Arduino
2 Pcs TCS34725 RGB Light Color Sensor Recognition Module for Arduino
2 Pcs TCS34725 RGB Light Color Sensor Recognition Module; Red, Green, Blue (RGB), and White Light Sensing with IR Blocking Filter
$9.29
Bestseller No. 2
Teyleten Robot TCS34725 TCS-34725 Sensor Recognition Module RGB Sensor for Arduino (3pcs)
Teyleten Robot TCS34725 TCS-34725 Sensor Recognition Module RGB Sensor for Arduino (3pcs)
Brand new original chip; Module Data Rates can up to 400 kbit/s,power is low,is 2.5-uA Sleep State
$18.99
Bestseller No. 4
10pcs 4Pin RGB Module KY-016 Three Colors 3 Color RGB LED Sensor Module for Arduino
10pcs 4Pin RGB Module KY-016 Three Colors 3 Color RGB LED Sensor Module for Arduino
10pcs 4Pin RGB Module KY-016 Three Colors 3 Color RGB LED Sensor Module For Arduino; Three primary colors can be mixed to get different colors by adjusting the PWM
$9.88
SaleBestseller No. 5
D-FLIFE 2pcs TCS-34725 TCS34725 RGB Light Color Sensor Colour Recognition Module RGB Color Sensor with IR Filter and White LED for Arduino
D-FLIFE 2pcs TCS-34725 TCS34725 RGB Light Color Sensor Colour Recognition Module RGB Color Sensor with IR Filter and White LED for Arduino
Strong point: Input Voltage Levels Compatible with VDD or 1.8 V Bus; Low Power: 2.5-uA Sleep State
$9.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.