This article is supported by the video below, please watch this in conjunction with reading this article for the full information on this project.
Introduction
Sensors are available that can detect colour, these can be helpful in situations where things needed to be sorted by colour type. Here’s a picture of one,
The sensitive area is the small black square in the very middle. It is surrounded by 4 bright white LED’s to try and give a consistent light level.
How do they work?
Human eye sight works by having around 7 million light sensitive cells called cone cells,of which there are three types, one sensitive to red light, one to blue and one to green. All the colours we see are based on different mixtures and intensities of these three types of light that come through our eyes. So any detector that needs to make sense of a world as perceived by humans needs something similar. So this device has in it’s centre a 64 light sensitive cells arranged in a square grid (the small black centre square in the picture above). 16 are covered with a red filter, 16 with a green and 16 with a blue filter. The remaining 16 have no filter and measure the overall intensity of the total light falling. Our eyes have a similar arrangement as they also have rod cells that are only sensitive to light itself and not a particular colour – these help with out night/ low light vision. The four white LEDs are to give the subject colour good illumination.
How so filters help?
A red filter only lets through red light, green filter green light, blue filter blue light. In this way the sensor can measure the different amounts of colour in a sample and return the result. In software you would then need to interpret this colour in some way.
Required Components
The following circuit uses just two components to investigate the properties of this sensor.
- TCS230 /TCS 3200 Colour sensor
- Arduino Nano
Plus a breadboard and some wires.
All communication with the Arduino and the sensor is performed over the serial bus using the serial monitor. Here’s the circuit you’ll need followed by my breadboard implementation.
As you can see the circuit is really simple.
Improving the Sensor
The sensor (and indeed any type of this sensor, expensive or cheap) works best when it is presented with only the colour you wish to sample. This means removing any external sources of light. As you can see from the picture (and if you own one) they are exposed to light on all sides, so we need to isolate the sensor area so that it only “sees” the sample in question. To do this we make a shroud to house the sensor. Here’s the one I made both off and on the sensor. Simple matt black card and some sticky tape were all that was required.
The above will ensure that only the objects colour should be hitting the sensitive area and make our results more consistent.
Installing required libraries
Using the Arduino Libraries Manager (Sketch->Include Library->Manage Libraries…) type “md_tcs230” into the search bar and install the md_tcs230 library. This library handles all the nitty gritty of reading the various colour values from the sensor. Next type in “FreqCount” and install this library. This particular library is required by the previous one to help it interpret the data returned by the sensor.
Detecting Skittles Colours
Most projects involving this sensor usually sort a programmers/hardware designers favourite sweetie (or candy if your not from the UK), the skittle. A quick search of the internet will reveal several designs, and so that XTronical Towers is not to be left out there will be a hardware design for doing this in an up-coming article. But for now here is some code to get your sensor to recognise the different skittles colours.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 |
// TCS230 sensor and colour calibration // // Input and output using the Serial console. // #include <MD_TCS230.h> // colour sensor library #include <FreqCount.h> // used by above library #include <EEPROM.h> // Ensure data is still valid after power offs // Pin definitions // Note The "OUT" pin is not defined as the library defines it, we cannot change. // S0 and S1 are hard wired to VCC and GND respectivly as they select a certain scaling // factor to the output. This can be set to different values so that the sensor works // well with different microcontrollers. With Arduino we the connections suggested set a // scaling factor of 20% which seems to work well with this microcontroller #define S2 12 #define S3 13 #define OE 8 // LOW = ENABLED, some modules don't use #define MAX_COLOURS 10 // Max colours allowed to store, 10 takes up 140 bytes #define MAX_COLOUR_NAME_CHARS 10 // Max chars allowed in name of colour #define TOLERANCE 35 // How far out the red,green or blue can be to match typedef struct { char Name[MAX_COLOUR_NAME_CHARS+1]; // Name for Colour, plus 1 extra for terminator '0' uint8_t Red,Green,Blue; // The colour values }SingleColour; SingleColour Colours[MAX_COLOURS]; // Our array of colours to match against uint8_t NumColours=0; // Current Number of colours MD_TCS230 CS(S2, S3, OE); void setup() { Serial.begin(115200); CS.begin(); // Check if we have some calibration data ReadCalibrations(); ReadColours(); } void loop() { static char Choice; Choice=MainMenu(); switch(Choice) { case '1': CalibrateSensor(); break; case '2': CalibrateColour(); break; case '3': DisplayColours(true); break; case '4': DeleteColour(); break; case '5': ClearEEPROMColours(); break; case '6': ClearCalibration(); case '7': ScanColour(); break; } } void ClearCalibration() { uint8_t DataIdx; EEPROM.put(DataIdx," "); DataIdx=3+sizeof(sensorData); EEPROM.put(DataIdx," "); Serial.println("\nSensor calibration cleared"); } void ClearEEPROMColours() { // Just reset number of colours to 0 uint16_t DataIdx; DataIdx=9+(2*sizeof(sensorData)); // Move past black and white calibration settings EEPROM.put(DataIdx,0); Serial.println("\nEEPROM colours cleared"); // Now reset the array of colours by seeting number of colours to 0 NumColours=0; } void WriteColoursToEEPROM() { uint16_t DataIdx; DataIdx=6+(2*sizeof(sensorData)); // Move past black and white calibration settings EEPROM.put(DataIdx,"COL"); // Identifier DataIdx+=3; EEPROM.put(DataIdx,NumColours); DataIdx++; for(uint8_t i=0;i<NumColours;i++) { EEPROM.put(DataIdx,Colours[i]); DataIdx+=sizeof(SingleColour); } Serial.println("\nColours written to EEPROM\n"); } void WriteColourToEEPROM(uint8_t ColIdx) { uint16_t DataIdx; // index into data DataIdx=6+(2*sizeof(sensorData)); // Move past black and white calibration settings // Check if any colours written at all, if not then set it up if(((EEPROM.read(DataIdx)=='C')&(EEPROM.read(DataIdx+1)=='O')&(EEPROM.read(DataIdx+2)=='L'))==false) EEPROM.put(DataIdx,"COL"); // Identifier // Store the colour DataIdx=ColourEEPROMStartAddress(ColIdx); EEPROM.put(DataIdx,Colours[ColIdx]); } uint16_t ColourEEPROMStartAddress(uint8_t ColIdx) { // return address for this particular colour in the EEPROM // Broken down into steps so you can see how things are stored uint16_t DataIdx=0; DataIdx+=3; // Black calibration Identifier 'BLK' DataIdx+=sizeof(sensorData); //Black sensor data DataIdx+=3; // White calibration Identifier 'WHT' DataIdx+=sizeof(sensorData); //White sensor data DataIdx+=3; // 'COL' identifier to show valid colour data DataIdx+=1; // NUmber of colours // We are now at the start of the colours and this would be the first colour, simply multiply // the size of the colour data by the colidx DataIdx+=(ColIdx * sizeof(SingleColour)); return DataIdx; } void DeleteColour() { char ColourName[MAX_COLOUR_NAME_CHARS]; // Store of name int8_t ColIdx; Serial.print(F("\nEnter name for the colour to delete [Max ")); Serial.print(MAX_COLOUR_NAME_CHARS); Serial.print(" chars] followed RETURN\n\n"); GetColourName(ColourName); ColIdx=ColourIndex(ColourName); if(ColIdx==-1) { Serial.print(ColourName); Serial.print(F(" could not be found, returning to main menu\n")); return; } // To remove colour we just shuffle the colours around and reduce the count by 1 ShuffleColoursDown(ColIdx); Serial.print(F("\nThe colour ")); Serial.print(ColourName); Serial.print(F(" has been removed\n")); WriteColoursToEEPROM(); } void ShuffleColoursDown(uint8_t ColIdx) { // All colours above ColIdx are move down one position, effectivly removing the colour at ColIdx for(uint8_t i=ColIdx+1;i<NumColours;i++) { strcpy(Colours[i-1].Name,Colours[i].Name); Colours[i-1].Red=Colours[i].Red; Colours[i-1].Green=Colours[i].Green; Colours[i-1].Blue=Colours[i].Blue; } NumColours--; // one less colour } char MainMenu() { char Choice; Serial.print(F("\nCalibration Menu (Choose option and press RETURN)\n")); Serial.print(F("1 Calibrate sensor\n")); Serial.print(F("2 Add/Update colour\n")); Serial.print(F("3 Display colours\n")); Serial.print(F("4 Delete colour\n")); Serial.print(F("5 Delete all colours\n")); Serial.print(F("6 Clear sensor calibration settings\n")); Serial.print(F("7 Scan Colour\n")); return getChar(); } void ScanColour() { // Scan and find a colour on the sensor colorData rgb; CS.read(); while(CS.available()==0); // wait for read to complete CS.getRGB(&rgb); int8_t ColIdx=MatchColour(&rgb); Serial.print(F("\nScanning for RGB[")); Serial.print(rgb.value[TCS230_RGB_R]); Serial.print(F(",")); Serial.print(rgb.value[TCS230_RGB_G]); Serial.print(F(",")); Serial.print(rgb.value[TCS230_RGB_B]); Serial.print(F("]\n")); if(ColIdx==-1) Serial.println("\nNo match found"); else { Serial.print("\nThat colour is "); Serial.print(Colours[ColIdx].Name); Serial.print(" ["); Serial.print(Colours[ColIdx].Red); Serial.print(F(",")); Serial.print(Colours[ColIdx].Green); Serial.print(F(",")); Serial.print(Colours[ColIdx].Blue); Serial.println("]"); } } int8_t MatchColour(colorData *rgb) { // Look through colours looking for a match uint8_t Idx=0; bool Found=false; while((Idx<NumColours)&(Found==false)) { if((CheckColour(rgb->value[TCS230_RGB_R],Colours[Idx].Red)) &(CheckColour(rgb->value[TCS230_RGB_G],Colours[Idx].Green))&(CheckColour(rgb->value[TCS230_RGB_B],Colours[Idx].Blue))) Found=true; Idx++; } if(Found) return Idx-1; else return -1; } bool CheckColour(uint8_t ScanCol, uint8_t StoredCol) { // returns true if matched on this single colour else false int16_t StoreColLow,StoreColHigh; StoreColLow=StoredCol-TOLERANCE; StoreColHigh=StoredCol+TOLERANCE; if(StoreColLow<0) StoreColLow=0; if(StoreColHigh>255) StoreColHigh=255; return ((ScanCol>=StoreColLow)&(ScanCol<=StoreColHigh)); } void DisplayColours(bool ShowTitle) { // List all the current colours (not nessasarily saved back to EEPROM yet char ColStr[4]; //Temp store for the integer colour value to a string for formatted printing if(NumColours==0) { Serial.print("\nNo current colours stored in memory\n"); return; } if(ShowTitle) Serial.print("\nCurrent colours stored in memory\n"); Serial.println("Name Red Green Blue"); for(uint8_t i=0;i<NumColours;i++) { OutputPadded(Colours[i].Name,MAX_COLOUR_NAME_CHARS); Serial.print(" "); itoa(Colours[i].Red,ColStr,10); OutputPadded(ColStr,3); Serial.print(" "); itoa(Colours[i].Green,ColStr,10); OutputPadded(ColStr,3); Serial.print(" "); itoa(Colours[i].Blue,ColStr,10); OutputPadded(ColStr,3); Serial.println(); } } void ReadColours() { // Read in any colour data uint16_t DataIdx; // index into data DataIdx=6+(2*sizeof(sensorData)); // Move past black and white calibration settings if((EEPROM.read(DataIdx)=='C')&(EEPROM.read(DataIdx+1)=='O')&(EEPROM.read(DataIdx+2)=='L')) { // Valid colour data DataIdx+=3; // How many colours stored EEPROM.get(DataIdx,NumColours); if(NumColours==0) { Serial.println("No colours stored in EEPROM\n"); return; } if(NumColours>MAX_COLOURS) { Serial.print(F("Number of colours (")); Serial.print(NumColours); Serial.print(F(") exceeds maximum of ")); Serial.print(MAX_COLOURS); Serial.print(F(",only first ")); Serial.print(MAX_COLOURS); Serial.print(F(",will be read in.")); NumColours=MAX_COLOURS; } DataIdx++; for(uint8_t i=0;i<NumColours;i++) { EEPROM.get(DataIdx,Colours[i]); DataIdx+=sizeof(SingleColour); } Serial.println("Colours read in from EEPROM\n"); DisplayColours(false); } else Serial.println(F("No Colour data stored")); } void ReadCalibrations() { uint16_t DataIdx; sensorData sd; // If we find some calibration data then calibrate sensor if((EEPROM.read(0)=='B')&(EEPROM.read(1)=='L')&(EEPROM.read(2)=='K')) { // Black Calibration data present EEPROM.get(3, sd); CS.setDarkCal(&sd); Serial.print("Black Calibration read in, "); } else Serial.print("No black calibration data, "); DataIdx=3+sizeof(sensorData); if((EEPROM.read(DataIdx)=='W')&(EEPROM.read(DataIdx+1)=='H')&(EEPROM.read(DataIdx+2)=='T')) { // white Calibration data present EEPROM.get(DataIdx+3, sd); CS.setWhiteCal(&sd); Serial.println("White Calibration read in."); } else Serial.println("No white calibration data"); } void CalibrateSensor() { uint16_t DataIdx; sensorData sd; Serial.print(F("\n****** Calibrate sensor ******\n")); Serial.print(F("Put black matt object over sensor, then press any key followed by RETURN\n")); getChar(); CS.read(); while(CS.available()==0); // wait for read to complete CS.getRaw(&sd); CS.setDarkCal(&sd); // Store this sensor black data EEPROM.write(0,'B');EEPROM.write(1,'L');EEPROM.write(2,'K'); // This acts as as simple indicator EEPROM.put(3,sd); Serial.print(F("Put white object over sensor, then press any key followed by RETURN\n")); getChar(); CS.read(); while(CS.available()==0); // wait for read to complete CS.getRaw(&sd); CS.setWhiteCal(&sd); DataIdx=3+sizeof(sensorData); // Store white data after black data EEPROM.write(DataIdx,'W');EEPROM.write(DataIdx+1,'H');EEPROM.write(DataIdx+2,'T'); // This acts as as simple indicator EEPROM.put(DataIdx+3,sd); Serial.print(F("Calibration of sensor complete.\n\n")); } void CalibrateColour() { colorData rgb; uint16_t DataIdx; char ColourName[MAX_COLOUR_NAME_CHARS]; // Store of name int8_t ColIdx; char Choice; // Serial.print(F("\nPlace your colour under the sensor, then enter name for colour [Max ")); Serial.print(MAX_COLOUR_NAME_CHARS); Serial.print(" chars] followed RETURN\n"); GetColourName(ColourName); ColIdx=ColourIndex(ColourName); if(ColIdx>=0) { Serial.print(F("\nWARNING: The colour ")); Serial.print(ColourName); Serial.print(F(" already exists, overwrite (Y/N)\n")); if(toupper(getChar())!='Y') { Serial.print(F("\nColour calibration abandoned\n")); return; } } if(ColIdx==-1) { // Check if can add a new colour if(NumColours==MAX_COLOURS) { Serial.print(F("\nWARNING: There is no room left for new colours, you have reached the maximum of ")); Serial.print(NumColours); Serial.print(F(" colours\n\n")); Serial.print(F("You will need to delete a colour first to make room.\n\n")); return; } } Serial.print(F("Reading Color '")); Serial.print(ColourName); Serial.print("'"); CS.read(); while(CS.available()==0); // wait for read to complete CS.getRGB(&rgb); Serial.print(F("\nRGB is [")); Serial.print(rgb.value[TCS230_RGB_R]); Serial.print(F(",")); Serial.print(rgb.value[TCS230_RGB_G]); Serial.print(F(",")); Serial.print(rgb.value[TCS230_RGB_B]); Serial.print(F("]\n")); if(ColIdx==-1) ColIdx=NumColours; // If not already stored set to next available colour slot strcpy(Colours[ColIdx].Name,ColourName); Colours[ColIdx].Red=rgb.value[TCS230_RGB_R]; Colours[ColIdx].Green=rgb.value[TCS230_RGB_G]; Colours[ColIdx].Blue=rgb.value[TCS230_RGB_B]; if(ColIdx==NumColours) // If same then added a new colour, increase the numcount { NumColours++; DataIdx=9+(2*sizeof(sensorData)); // Move past black and white calibration settings and 'COL' marker EEPROM.put(DataIdx,NumColours); // Write new total to EEPROM } WriteColourToEEPROM(ColIdx); } int8_t ColourIndex(char *ColourName) { // Looks through the colours to see if this colour already exists, if so returns it's index pos in the array // else returns -1 int8_t Idx=0; bool Found=false; if(NumColours==0) return -1; while((Idx<NumColours)&(Found==false)) { if(strcasecmp(Colours[Idx].Name,ColourName)==0) Found=true; else Idx++; } if(Found) return Idx; else return -1; } void GetColourName(char *ColourName) { uint8_t NameLength=0; while (Serial.available() == 0); // Wait for some chars NameLength=Serial.readBytes(ColourName,MAX_COLOUR_NAME_CHARS); // Read them in ColourName[NameLength]=0; // terminate string //scan for any new line or carriage return and remove uint8_t i=0; while(i<NameLength) { if((ColourName[i]==13)|(ColourName[i]==10)) { ColourName[i]=0; return; } i++; } } char getChar() { char FirstChar; // Wait for user to return a char over serial connection, returns uppercase version of any alpha char while (Serial.available() == 0); FirstChar=toupper(Serial.read()); delay(1); // small delay (1/1000s) to allow any CR or newline to come through while(Serial.available() > 0) { char t = Serial.read(); } return FirstChar; } void OutputPadded(char *Str,uint8_t AmountToPad) { // outputs the colour name post padded with spaces so that it will be a maximum of MAX_COLOUR_NAME_CHARS chars in total // This is used to create a more pleasant tidy display when listing colours uint8_t Amount=AmountToPad-strlen(Str); Serial.print(Str); while(Amount>0) { Serial.print(" "); Amount--; } } |
Once uploaded open the serial monitor from the Arduino IDE and you will be presented with a menu of options. Put your cursor into the input area of the serial monitor to choose options from the menu. If your not sure what to do then watch the video mentioned at the top of the post.
And that’s it, I hope this has been helpful and perhaps inspired you to create a skittles sorting machine! More on mine in a later article.