Reading your code, I see three points:
- Your constants are not assigned the values that you think.
const int RED_COLOR = (255,0,0);sets the integer constant to the value0, i.e. the last value of a comma-separated sequence, see here. Instead, enumerate your color constants, i.e. set red=1, blue=2, etc. Or define a struct with three integer components. - The variable
colorwill never be assigned the valuesORANGE_COLOR,PURPLE_COLORnorYELLOW_COLOR, because of the way you structured the expressions in the if-then-else block. Ifred > green && red > blue, the program will never even check whetherred > green && red > blue && blue > green, because it already entered the first block. AndPURPLE_COLORis not listed in the upper if-else-block at all. Also, as orange and yellow are both mixes of red and green, I would expect someCYAN_COLORsomewhere in there to cover the shades between green and blue. - What is the exact type of the color sensor? It seems strange to me that it transmits its data via the length of a pulse. If it doesn't,
pulseIn()is the wrong method to use. If it really does, you may have a race condition here: I guess that writing to the pinss2/s3triggers the sensor to start the "data pulse", in which casedigitalRead(sensorOut)may already return the "pulse state" instead of the "pre-pulse state" and therefore waits for a different pulse than it should. You'd need to first readsensorOutinto a variable, then sets2/s3, then read your data viapulseInusing the variable you set before.
But without having the datasheet of the sensor/knowing the protocol of the sensor, this is all very volatile guesswork. Please improve your question by adding the sensor type (and maybe a wiring diagram) alongside an explanation of what you mean by "it fails". How exactly does it fail? Which part works and which doesn't?
You can also glean more insight into the state of your sketch by writing measured values to the serial monitor using Serial.println.