Recently I built a color sensor and thanks to @
and @ i got the code to work. so i thought i would share it with you.
Parts i used:
(1) Arduino Mega
(1) 10K ohm resister
(4) 220 ohm resister
(1) Red LED
(1) Green LED
(1) Blue LED
(1) White LED
(1) Light sensitive resister
And the schematic:
Finely the code:
int sensorPin = A0;
int red = 0;
int green = 0;
int blue = 0;
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 8;
int val1 = -12;//Use this to ajost the red value
int val2 = -4;//Use this to ajost the green value
int val3 = -18;//Use this to ajost the blue value
int sensorValue = 0;
void setup() {
pinMode(led1, OUTPUT); //Red LED
pinMode(led2, OUTPUT); //Green LED
pinMode(led3, OUTPUT); //Blue LED
pinMode(led4, OUTPUT); //Detecshin LED
Serial.begin(9600);
}
void loop() {
digitalWrite(led1, HIGH);
sensorValue = analogRead(sensorPin);
red = (sensorValue / 10) + val1;
// Serial.print("red =");
// Serial.println(red);
delay(50);
digitalWrite(led1, LOW);
/////////////////////////////////
digitalWrite(led2, HIGH);
sensorValue = analogRead(sensorPin);
green = (sensorValue / 10) + val2;
// Serial.print("green =");
// Serial.println(green);
delay(50);
digitalWrite(led2, LOW);
/////////////////////////////////
digitalWrite(led3, HIGH);
sensorValue = analogRead(sensorPin);
blue = (sensorValue / 10) + val3;
// Serial.print("blue =");
// Serial.println(blue);
delay(50);
digitalWrite(led3, LOW);
if(blue > 13 and blue < 17 and green > 13 and green < 17 and red > 13 and red < 17){
Serial.println("whight");
digitalWrite(led4, HIGH);
delay(1000);
}
else{
digitalWrite(led4, LOW);
}
}
This code turns on the detection LED wen a green object is held over the sensor.
Top Comments