/*     Arduino Color Sensing Tutorial
 *      
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *  
 */
 
#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8
int rFrequency = 0;
int bFrequency = 0;
int gFrequency = 0;
void setup() {
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);
  
  // Setting frequency-scaling to 20%
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);
  
  Serial.begin(9600);
}
void loop() {
  // Setting red filtered photodiodes to be read
  digitalWrite(S2,LOW);
  digitalWrite(S3,LOW);
  // Reading the output frequency
  rFrequency = pulseIn(sensorOut, LOW);
  // Printing the value on the serial monitor
  //Serial.print("R= ");//printing name
  //Serial.print(rFrequency);//printing RED color frequency
  //Serial.print("  ");
  delay(100);
  // Setting Green filtered photodiodes to be read
  digitalWrite(S2,HIGH);
  digitalWrite(S3,HIGH);
  // Reading the output frequency
  gFrequency = pulseIn(sensorOut, LOW);
  // Printing the value on the serial monitor
  //Serial.print("G= ");//printing name
  //Serial.print(gFrequency);//printing RED color frequency
  //Serial.print("  ");
  delay(100);
  // Setting Blue filtered photodiodes to be read
  digitalWrite(S2,LOW);
  digitalWrite(S3,HIGH);
  // Reading the output frequency
  bFrequency = pulseIn(sensorOut, LOW);
  // Printing the value on the serial monitor
  //Serial.print("B= ");//printing name
  //Serial.print(bFrequency);//printing RED color frequency
  //Serial.println("  ");
  
  if (rFrequency > 1000 && gFrequency > 1000 && bFrequency > 100)
    {
      if (rFrequency < 1600 && gFrequency < 1550 && bFrequency < 450)
        {
        Serial.println("blue"); 
        }
    }
  if (rFrequency > 800 && gFrequency > 450 && bFrequency > 100)
    {
      if(rFrequency < 1050 && gFrequency < 650 && bFrequency < 250)
        {
        Serial.println("green"); 
        }
    } 
  if (rFrequency > 200 && gFrequency > 900 && bFrequency > 100) 
    {
     if(rFrequency < 350 && gFrequency < 1050 && bFrequency < 250) 
       {    
       Serial.println("red");
       }
     }
  else
  {
    //Serial.println("Color Undefined");
  }
  delay(100);
}
