#define S0 4 #define S1 5 #define S2 6 #define S3 7 #define SENSOR_OUT 8 // How long a pulse lasts through the // chosen filter (microseconds). Smaller: // more of that colour. 0: no pulse came. int readColour(int s2, int s3) { digitalWrite(S2, s2); digitalWrite(S3, s3); // Let the sensor settle on the filter delay(20); return pulseIn(SENSOR_OUT, LOW, 100000); } void setup() { pinMode(S0, OUTPUT); pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(SENSOR_OUT, INPUT); // Output scale 20%: S0 HIGH, S1 LOW digitalWrite(S0, HIGH); digitalWrite(S1, LOW); Serial.begin(9600); } void loop() { int red = readColour(LOW, LOW); int green = readColour(HIGH, HIGH); int blue = readColour(LOW, HIGH); Serial.print("R: "); Serial.print(red); Serial.print(" G: "); Serial.print(green); Serial.print(" B: "); Serial.print(blue); // The colour with the shortest pulse // is the one the object is closest to. if (red == 0 || green == 0 || blue == 0) { Serial.println(" -> ?"); } else if (red < green && red < blue) { Serial.println(" -> R"); } else if (green < red && green < blue) { Serial.println(" -> G"); } else { Serial.println(" -> B"); } delay(500); }