Interface color sensor with Arduino

About Color Sensor:

The color sensor is used for the detection of colors. It detects the color of an object on the RGB scale. It works by shinning a bright white light over the object which get reflected back from the object and captured by the sensor. Depending upon the reflected light captured by the sensor the color of the object is decided.    

Pinout or pin diagram of a color sensor

Features of color sensor 

  • Operating Voltage: 2.7-5 volt
  • Interface: TTL

Components Required for this project

  • Arduino UNO/Nano/Mega
  • Colour Sensor
  • Jumper Wires

Pin Connections of color sensor with Arduino

  • GND: GND
  • VCC: 5v
  • S0: 3
  • S1: 4
  • S2: 5
  • S4: 6
  • OUT: 2

Circuit Diagram of a color sensor with Arduino

Arduino code for a color sensor with Arduino

const int S0=3;
const int S1=4;
const int S2=5;
const int S3=6;
int flag=0;
int count=0;
int countRed=0;
int countGreen=0;
int countBlue=0;
 
void setup() {
  Serial.begin(9600);
  pinMode(S0,OUTPUT);
  pinMode(S1,OUTPUT); 
  pinMode(S2,OUTPUT);
  pinMode(S3,OUTPUT);
 
}
int i=0;
 
void into()
{
  count++;
}
 
void tcs()
{
  digitalWrite(S1,HIGH);
  digitalWrite(S0,LOW);
  flag=0;
  attachInterrupt(0,into, CHANGE);
  timer2();
}
void timer2(void)
{
  TCCR2A=0x00;
  TCCR2B=0x07; 
  TCNT2= 100; 
  TIMSK2 = 0x01;
}
 
ISR(TIMER2_OVF_vect)
{
  TCNT2=100;
  flag++;
 if(flag==1)
  {
   count=0;
  }
 else if(flag==2)
  {
   digitalWrite(S2,LOW);
   digitalWrite(S3,LOW); 
   countRed=count/1.051;
   Serial.print("red=");
   Serial.println(countRed,DEC);
   digitalWrite(S2,HIGH);
   digitalWrite(S3,HIGH);   
  }
 else if(flag==3)
  {
   countGreen=count/1.0157;
   Serial.print("green=");
   Serial.println(countGreen,DEC);
   digitalWrite(S2,LOW);
   digitalWrite(S3,HIGH); 
  }
 else if(flag==4)
  {
    countBlue=count/1.114;
    Serial.print("blue=");
    Serial.println(countBlue,DEC);
    digitalWrite(S2,LOW);
    digitalWrite(S3,LOW);
  }
 else
  {
    flag=0; 
    TIMSK2 = 0x00;
  }
  count=0;
  delay(2);
}
 
 
 
void loop() {
 
  delay(10);
 tcs();
 if((countRed>10)||(countGreen>10)||(countBlue>10))
  {
    if((countRed>countGreen)&&(countRed>countBlue))
      {
 
           Serial.println("RED COLOUR");
           delay(1000);
      }
    else if((countGreen>=countRed)&&(countGreen>countBlue))
      {
 
           Serial.println("GREEN COLOUR");
           delay(1000);
      } 
    else if((countBlue>countGreen)&&(countBlue>countRed))
     {
 
           Serial.print("BLUE COLOUR");
           delay(1000);
     }
  }
    else 
   {
    
      delay(1000);       
   }
  
 
}

Leave a Reply

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