LEGO MINDSTORMS Robot Inventor
Music Scale Player
This model uses the color sensor to play a musical scale when you slide the colored stick back and forth.
Two programs are provided, a simple one that plays 7 different notes using the sensor data in the simplest way, and a more advanced one that plays 8-note major and minor scales and with much better accuracy.
More a more advanced model using this idea, see the Bass Guitar.
In addition to the added features, the more complex Music Scales program uses various logic techniques to address several problems with the simpler program above, including:
Blue and teal are easily confused by the sensor when the color is first coming into view, which can cause the "wrong" event to be sent. The improved program looks at changing color values in a loop to help get around this.
Since similar colors can still be confused, the improved program uses a "heuristic" trick of assuming that the scale must be played in sequence (up or down) to help predict the correct note to play.
The improved program also uses the note order heuristic to distinguish between high C and low C. High C must come after B in the scale. This heuristic is not perfect, and you can confuse it if you try.
Stray "no color" readings are common when colors are changing, and very common with red in particular in this setup. The improved program filters these out.
Instead of using "no color" to detect when the color stick has been removed, a timer is used, to hold the last note for 1/2 second, which also sounds nice.