/** * File: ColorSensor-KnownColors.ino * Description: * In this code we change the emitting colors and measure the intensity * of the reflected light. * In fact this measure is so quick, that out eyes see white color * (as a mixture of red, green and blue) lights. * Detected color is printed to the serial output with 115200bps. * * Author: Balazs Kelemen * Contact: prampec+arduino@gmail.com * Copyright: 2016 Balazs Kelemen * Copying permission statement: ColorSensor-KnownColors is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #define RED A3 #define GREEN 2 #define BLUE 3 #define S1 A0 #define S2 A2 #define DELAY_MS 400 #define PRINT_FREQ_MS 10 #define COLOR_TRESHOLD 5 int black = 630; unsigned long lastPrint = 0; int red = 0; int green = 0; int blue = 0; void setup() { Serial.begin(115200); pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); // TODO: make some calibration } void loop() { testColor(); } void testColor() { unsigned long now = millis(); writeColor(HIGH, LOW, LOW); delay(1); int s1 = analogRead(S1); // int s2 = analogRead(S2); if(s1 < (black - COLOR_TRESHOLD)) { red = 1; } else { red = 0; } writeColor(LOW, HIGH, LOW); delay(1); s1 = analogRead(S1); // int s2 = analogRead(S2); if(s1 < (black - COLOR_TRESHOLD)) { green = 1; } else { green = 0; } writeColor(LOW, LOW, HIGH); delay(1); s1 = analogRead(S1); // int s2 = analogRead(S2); if(s1 < (black - COLOR_TRESHOLD)) { blue = 1; } else { blue = 0; } if(((lastPrint + PRINT_FREQ_MS) < now) || (now < lastPrint)) { if((red == 1) && (green == 1) && (blue == 1)) { Serial.println("White"); } else if((red == 1) && (green == 0) && (blue == 0)) { Serial.println("Red"); } else if((red == 0) && (green == 1) && (blue == 0)) { Serial.println("Green"); } else if((red == 0) && (green == 0) && (blue == 1)) { Serial.println("Blue"); } else if((red == 0) && (green == 0) && (blue == 0)) { Serial.println("Black"); } else { Serial.println("Unnamed color"); } lastPrint = now; } } void writeColor(boolean red, boolean green, boolean blue) { digitalWrite(RED, red); digitalWrite(GREEN, green); digitalWrite(BLUE, blue); }