IoT Based Colour Sorting Machine using ESP8266 and ThingSpeak

IoT Based Colour Sorting Machine using ESP8266 and ThingSpeak

In a productive environment, sorting of products can be a very difficult process. Continuous manual sorting creates issues and takes a considerable amount of time and manpower. So in this tutorial, we are going to build an IoT-based Colour Sorting Machine using NodeMCU-ESP8266, TCS3200 Colour Sensor, and two Servo Motors, as the title says it will sort the things according to their colour. The TCS3200 Colour Sensor is responsible for sensing the colour of an object and two servo motors are used to put them into the respective predefined colour box. And as it is IoT enabled, the number of products for each colour will be displayed on the Thingspeak control panel.

 

For the demonstration purpose, we will build a simple colour sorting setup using cardboard. The boxes and the setup both will be in the fixed position and the servo motor will be used to move the sorter to put the ball in the respective colour box. And we will be using the ThingSpeak and ESP8266 to do so. We have previously used the TCS3200 Colour Sensor with NodeMCU to build an IoT Based Currency Counter, you can check that out if that peaks your interest.

 

TCS3200 Colour Sensor

TCS3200 Colour Sensor

TCS3200 is a colour sensor that can detect a wide variety of colours based on their wavelength. It uses a TAOS TCS3200 RGB sensor chip to detect colour frequency. This sensor also contains four white LEDs that light up the object in front of it. The TCS3200 chip has an 8 x 8 array of photodiodes (a total of 64 photodiodes). From these 64 photodiodes, 16 photodiodes have Red filters over them, 16 photodiodes have Green filters, 16 photodiodes have Blue filters, and the remaining 16 photodiodes are clear with No filters.

TCS3200 Colour Sensor Pinout

 

In this module, 16 photodiodes of the same colour are connected in parallel. The control pins S2 and S3 are used to select the array of photodiodes. For example, we can read the red colour photodiodes by setting the S2 and S3 to the low logic level. The complete table is given below:

S2

S3

Photodiode Type

0

0

Red

0

1

Blue

1

0

Clear

1

1

Green

 

The remaining two control pins i.e. S0 and S1 are used for scaling the output frequency. The output frequency can be scaled to three different preset values of 2%, 20%, or 100%. The pin logic for setting the output frequency is given in the below table:

S0

S1

Output Frequency

0

0

Power Down

0

1

2%

1

0

20%

1

1

100%

 

Specifications of TCS3200 RGB Colour Sensor:

Before proceeding further, let’s cover up the specification of this module. This module has a working voltage of 3V to 5V which means it can be directly interfaced with any microcontroller, and that is why it’s a perfect choice for our NodeMCU, which uses a 3.3V logic level. Other than power and ground, it has an enable pin E0, by pulling it low or high, we can disable or enable the chip. The OUT pin is used to provide the output frequency, the S0 and S1 select lines select the output frequency scaling. The S2 and S3 select lines select the photodiode type. After measuring a colour wavelength, it outputs the result as frequency, so we can directly measure the frequency and determine the colour, which reduces the intervention of an ADC. And finally, this sensor can accurately measure a test object within a distance of 1cm. If you want to learn more about its specification, you can go through the datasheet for the TCS3200 module

 

Materials Required for Colour Shorting Machine

  • NodeMCU ESP8266 (1)
  • TCS3200 Colour Sensor (1)
  • Servo Motor (2)
  • Jumper Wires
  • Cardboard
  • USB cable for power

 

Circuit Diagram for our Colour Sorting Machine

The circuit diagram for IoT Based Colour Sorting Machine is very simple and doesn’t require complex connections. The Circuit Diagram is given below:

Colour Sorting Machine Circuit Diagram

 

The colour sensor is powered with 3.3V and the servo motors are powered with 5V. PWM pins of both the motors are connected to D2 and D3 pins of NodeMCU. The connections for the colour sensor are given in the below table:

Colour Sensor Pin

NodeMCU Pin

Vcc

3.3V

GND

GND

S0

D4

S1

D5

S2

D6

S3

D7

OUT

D8

OE

GND

 

Setting up ThingSpeak to Monitor the Progress of Colour Sorting Machine

ThingSpeak is an open-source IoT analytics platform service that allows you to aggregate, visualize, and analyze live data in the cloud. It can be used to control devices, can store sensor data, and can be used to create instant visualizations of live data, and send alerts using web services like Twitter and ThingHTTP. Previously we have built many projects with ThingsSpeake like:

Solar Powered Wi-Fi Weather Station

IoT Based GPS Tracker

IoT Based Vehicle Tracker

So, do check those out if that peaks your interest. Now let’s send our data to ThingSpeak by configuring it.

 

Step 1: Sign up

To send data to Thingspeak, a Thingspeak account is required. To do so, navigate to the Thingspeak website.

ThingSpeak Internet of Things

 

Click on the ‘Sign up’ option in the top right corner and fill out the required details.

ThingSpeak Sign Up

After that, verify the E-mail id and click on continue.

 

Step 2: Create a Channel to Visualize Data

Now as you are logged in to your account, create a new channel by clicking the “New Channel” button.

ThingSpeak Channel

 

After clicking on “New Channel” enter the Name and Description of the data you want to upload on this channel.

 

Enter the name of data in Field1, Field2, Field3, and Field4. If you want to use more field than two, then you can check the box next to the Field option and enter the name and description of the channel.

 

After that, click on the ‘Save Channel’ button to complete the channel creation process.

 

Thingspeak usually shows data in Graph format, but it also provides an option to visualize data using different widgets. To add a widget, click on the ‘Add Widgets’ option and choose the widget you want to use. In this project, I am using the ‘Numeric Display’ widget.

 

Step 3: API Key

To send data to ThingSpeak, we need a unique API key, which we will use later in code to send the data to ThingSpeak Website.

 

Click on the “API Keys” option to get a unique API key for uploading sensor data. Now copy “Write API Key.”

ThingSpeak API Key

 

Arduino Code used to Control the Colour Sorting Machine

The complete code for IoT Based Colour Sorting Machine is given at the end of the document. Here we are explaining the complete code step by step.

IoT based Colour Sorting Machine

 

We will be using ThingSpeak with Arduino IDE, so as usual, the first step will be including all the required libraries. Thingspeak.h library can be downloaded from the link given. The Colour sensor can work without the library as we can read the colour frequency directly from the sensor pin to decide the colour.

#include <Servo.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>;
#include <ThingSpeak.h>;

 

After that, in the next lines, we define the ThingSpeak API key, channel number, Wi-Fi name, and password, which we have previously saved while making the ThingSpeak account.

Const char * myWriteAPIKey = “Enter Write Key”;
unsigned long myChannelNumber = 691885;
const char *ssid = “Wi-Fi Name”;   
const char *pass = “Password”; Password

 

Then define the servo variables. Here we are using two servo motors. The first servo motor is used to move the colour balls from the initial position to the colour sensor. The second servo motor is used to drop the colour ball into the colour bucket.

Servo pickServo;
Servo dropServo;

 

After that, define the colour sensor pins.

const int s0 = D4; 
const int s1 = D5; 
const int s2 = D6; 
const int s3 = D7; 
const int out = D8; 

 

Inside the setup() function, we initialize the Serial at 9600 baud. Then define the colour sensor pins as output pins to read the frequency values also define the pins for top and bottom servo motors.

Void setup()  
{ 
  Serial.begin(9600);
  pinMode(s0, OUTPUT); 
  pinMode(s1, OUTPUT); 
  pinMode(s2, OUTPUT); 
  pinMode(s3, OUTPUT); 
  pinMode(out, INPUT);
  pickServo.attach(D2);
  dropServo.attach(D3); 

 

Inside the loop() function, we measure the incoming frequency of Red, Green, and Blue colour and compares these frequency readings to detect colour. The control pins S2 and S3 are used to read the colour frequencies. For example, to read the frequency of red colour, set the two pins to low logic level, to read the Blue colour, set S3 pin HIGH and S2 pin LOW, and to read the Green colour, set S2 to pin HIGH and S3 pin LOW.

Void loop()
{   
  digitalWrite(s2, LOW); 
  digitalWrite(s3, LOW); 
  red = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); 
  digitalWrite(s3, HIGH); 
  blue = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); 
  digitalWrite(s2, HIGH); 
  green = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);

 

After getting the frequency values for Red, Green, and Blue colour, compare these values to detect the colours. Upon detecting a colour, first, move the drop servo with a particular angle to drops the colour ball to its respective box, then move the pick servo to pass the ball. Frequency values for each colour vary with distance and can be customized accordingly. After recognizing the colour, send the number of colour balls detected to ThingSpeak.

If(red<31 & red>25 & green<69 & green>63){
    colour = 1; // Red
    dropServo.write(85);
    delay(700);
    redcolour++;
    Serial.print(“Red”);
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 1,redcolour, myWriteAPIKey);
  }
  if(green<56 & green>52 & blue<52 &blue>47){
    colour = 2; // Orange
    dropServo.write(115);
    delay(700);
    orangecolour++;
    Serial.print(“Orange”);
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 2,orangecolour, myWriteAPIKey);
  }
  if(red<36 & red>29 & green<33 & green>26){
    dropServo.write(140);
    delay(700);
    colour = 3; // Green
    greencolour++;
    Serial.print(“Green”);
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 3,greencolour, myWriteAPIKey);
  }
  if(red<26 & red>19 & green<32 & green>24){
    dropServo.write(170);
    delay(700);
    colour = 4; // Yellow
    yellowcolour++;
    Serial.print(“Yellow”);
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 4,yellowcolour, myWriteAPIKey);
  }

 

Testing the Colour Sorting Machine

Once the code and hardware are ready, make a setup for colour sorting and mount both the servo motors and colour sensor as shown in the below image:

Colour Sorting Machine using NodeMCU

 

Now upload the code to the NodeMCU-ESP8266 board and your machine is ready to short the balls of different colours. The number of products for each colour will be displayed on Thingspeak as shown in the below image:

Colour Sorting Machine Working

The complete code and working video are given below. Hope you enjoyed building this project and learned something useful. If you have any questions, leave them in the comment section.

Code

#include <Servo.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>;
#include <ThingSpeak.h>;
const char * myWriteAPIKey = "9B6ILVOYMUSVOADA";
unsigned long myChannelNumber = 691885;
const char *ssid =  "Galaxy-M20";     // Enter your WiFi Name
const char *pass =  "ac312124"; // Enter your WiFi Password
WiFiClient client;
Servo pickServo;
Servo dropServo;
const int s0 = D4;  
const int s1 = D5;  
const int s2 = D6;  
const int s3 = D7;  
const int out = D8;   
int red = 0;  
int green = 0;  
int blue = 0; 
int color=0;
int redcolor = 0;
int greencolor = 0;
int orangecolor = 0;
int yellowcolor = 0;
int CLOSE_ANGLE = 30;  // The closing angle of the servo motor arm
int OPEN_ANGLE = 10;  // The opening angle of the servo motor arm
void setup()   
{  
  Serial.begin(9600); 
  pinMode(s0, OUTPUT);  
  pinMode(s1, OUTPUT);  
  pinMode(s2, OUTPUT);  
  pinMode(s3, OUTPUT);  
  pinMode(out, INPUT);  
  digitalWrite(s0, HIGH);  
  digitalWrite(s1, HIGH);  
  pickServo.attach(D2);
  dropServo.attach(D3);
  pickServo.write(30);
  dropServo.write(73);
  ThingSpeak.begin(client);
  Serial.println("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) 
     {
            delay(550);
            Serial.print(".");
     }
      Serial.println("");
      Serial.println("WiFi connected");
}  
void loop() 
{  
  digitalWrite(s2, LOW);  
  digitalWrite(s3, LOW);  
  //count OUT, pRed, RED  
  red = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);  
  digitalWrite(s3, HIGH);  
  //count OUT, pBLUE, BLUE  
  blue = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);  
  digitalWrite(s2, HIGH);  
  //count OUT, pGreen, GREEN  
  green = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); 
  Serial.print("R Intensity:");  
  Serial.print(red, DEC);  
  Serial.print(" G Intensity: ");  
  Serial.print(green, DEC);  
  Serial.print(" B Intensity : ");  
  Serial.print(blue, DEC);  
  if(red<39 & red>29 & green<93 & green>83 &blue<78 & blue>69){
    dropServo.write(73);
    delay(700);
    redcolor++;
    Serial.print("Red");
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 1,redcolor, myWriteAPIKey);
  }
  if(green<75 & green>65 & blue<68 &blue>60){
    dropServo.write(107);
    delay(700);
    orangecolor++;
    Serial.print("Orange");
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 2,orangecolor, myWriteAPIKey);
  }
  if(red<46 & red>36 & green<46 & green>37){
    dropServo.write(132);
    delay(700);
    greencolor++;
    Serial.print("Green");
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 3,greencolor, myWriteAPIKey);
  }
  if(red<34 & red>25 & green<37 & green>28 & blue<53 & blue>43){
    dropServo.write(162);
    delay(700);
    yellowcolor++;
    Serial.print("Yellow");
    open1();
    delay(200);
    close1();
    ThingSpeak.writeField(myChannelNumber, 4,yellowcolor, myWriteAPIKey);
  } 
  Serial.println();  
 // delay(1000); 

void open1(){ 
  pickServo.write(OPEN_ANGLE);   // Send the command to the servo motor to open the trap door
}
void close1(){ 
  pickServo.write(CLOSE_ANGLE);   // Send te command to the servo motor to close the trap door
}

Video

17 Comments

Fantastic! This is a great demo. Thanks for using ThingSpeak. Are you aware of the alerts feature? You can create an alert on ThingSpeak to tell you when the cup is full!

Disculpa que te moleste pero quería saber cuál es el tiempo de trabajo de este proyecto, me gustaría saber cuántos caramelos por minutos puede surtir

Thanks so much for providing individuals with an extremely brilliant chance to read in detail from this web site. It can be very fantastic and as well , stuffed with a lot of fun for me and my office colleagues to search your web site on the least 3 times per week to learn the newest stuff you have got. Of course, I am always motivated with the unbelievable techniques you serve. Selected 4 ideas in this post are completely the simplest we have all had.

Hello just wanted to give you a brief heads up and let you know a few of the images aren't loading correctly. I'm not sure why but I think its a linking issue. I've tried it in two different web browsers and both show the same outcome.

I want to express my gratitude for your kind-heartedness supporting individuals who really want help on your niche. Your very own commitment to passing the solution all through became certainly advantageous and has in most cases empowered men and women just like me to achieve their goals. Your new invaluable tutorial signifies a whole lot to me and especially to my peers. Best wishes; from all of us.

I simply needed to appreciate you yet again. I do not know what I would have gone through without the actual strategies discussed by you about this theme. This has been a very troublesome dilemma for me, nevertheless coming across this expert technique you processed the issue forced me to weep for delight. I'm just grateful for your information and as well , trust you find out what a great job you were getting into instructing people with the aid of your webblog. Most likely you have never come across all of us.

My wife and i have been relieved when Peter managed to carry out his investigations through your precious recommendations he had out of the web pages. It is now and again perplexing to simply choose to be offering concepts that many many others might have been selling. And now we fully understand we've got you to thank for that. The entire explanations you have made, the easy site navigation, the friendships you can make it possible to create - it's got mostly excellent, and it is letting our son in addition to our family do think the theme is entertaining, and that's especially pressing. Many thanks for all the pieces!

I would like to show my affection for your kind-heartedness giving support to those people that absolutely need assistance with this particular niche. Your very own dedication to getting the solution all through appeared to be amazingly significant and have really empowered associates just like me to reach their dreams. Your new warm and friendly help and advice indicates a lot to me and much more to my colleagues. Thanks a ton; from all of us.

I must point out my admiration for your kindness for those individuals that really want help on this important niche. Your real dedication to passing the message throughout was rather advantageous and has regularly made many people just like me to achieve their endeavors. Your entire important guideline indicates a great deal a person like me and additionally to my office colleagues. Thanks a ton; from everyone of us.

Thanks for all your valuable hard work on this website. Gloria loves making time for investigation and it's really easy to see why. Almost all hear all concerning the dynamic way you give functional information by means of this blog and therefore inspire contribution from other individuals on the concept so our own girl is without a doubt learning a whole lot. Enjoy the remaining portion of the year. Your performing a brilliant job.

Thanks so much for providing individuals with an extremely nice chance to read articles and blog posts from this web site. It is often so ideal and also stuffed with amusement for me and my office friends to search your website more than 3 times a week to find out the latest secrets you will have. Of course, I am actually satisfied for the fantastic principles you give. Certain two tips in this article are without a doubt the finest I have ever had.

I simply wished to thank you very much once again. I'm not certain what I would have taken care of in the absence of the hints shown by you on such question. Completely was an absolute frustrating crisis in my position, nevertheless seeing the expert fashion you handled the issue took me to weep over gladness. Now i am grateful for the advice and in addition trust you comprehend what a powerful job you happen to be putting in instructing some other people using your blog. Most probably you have never got to know any of us.

I simply needed to appreciate you all over again. I'm not certain the things that I would've gone through in the absence of the recommendations shown by you about such concern. Completely was a fearsome case in my position, but considering this well-written approach you managed it made me to cry over happiness. I am just thankful for this work and in addition pray you really know what an amazing job you are always getting into instructing the mediocre ones through your websites. Most likely you have never encountered any of us.

Thanks so much for giving everyone such a terrific chance to read from this site. It is often so enjoyable and also full of a great time for me and my office acquaintances to visit your web site a minimum of thrice weekly to learn the latest stuff you have got. And indeed, I am also certainly fascinated with all the excellent tips you give. Certain 1 tips on this page are essentially the finest I have had.

I enjoy you because of your own effort on this site. Debby really likes conducting internet research and it is simple to grasp why. My spouse and i hear all regarding the compelling form you deliver very helpful secrets on the blog and welcome contribution from visitors on this issue then my princess has been studying a whole lot. Take pleasure in the rest of the new year. You're the one carrying out a superb job.

A lot of thanks for all of your work on this website. My mom take interest in getting into internet research and it is easy to see why. Most of us notice all about the dynamic manner you produce rewarding solutions by means of this web site and even recommend contribution from website visitors on that area then our girl is now understanding a great deal. Enjoy the remaining portion of the new year. You are always performing a very good job.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.