Let’s make a piano out of our color predictor! In this example, we will use 4 colors to make a simple color piano. Once our piano is finished, we will be able to make music with our drone!
From our last example we also learned that we need to load our calibrated color classifier. We will also need to do that here!
drone.load_color_data("color_data")
Next, we will create an infinite while loop so that our drone can continuously look for colors. Inside of this while loop, we will also need to get our current color data and have the CoDrone EDU predict what color it is seeing like in our previous color prediction example.
while True:
color_data = drone.get_color_data()
color = drone.predict_colors(color_data)
The color
variable that we created is actually a list! color[0]
holds our front color sensor’s prediction while color[1]
holds the back sensor’s prediction. For this example, we will use color[0]
to check for our predicted color. If our color is green, then we will play a B4 note for 1 second.
if color[0] == "green":
drone.drone_buzzer(Note.B4, 1000)
Our main logic is finished, all we need to do now is add more sounds and colors. We will add an else statement that uses the buzzer but doesn’t make any sounds. Just in case!
elif color[0] == "red":
drone.drone_buzzer(Note.A4, 1000)
elif color[0] == "yellow":
drone.drone_buzzer(Note.C4, 1000)
elif color[0] == "black":
drone.drone_buzzer(Note.G4, 1000)
else:
drone.drone_buzzer(0, 0)
Lastly, we will add a print so that we can see what color is being predicted, as well as a sleep so we don’t send too many signals to the color sensor at once.
print(color[0])
time.sleep(0.2)
That’s all for the color piano! Here is the completed code:
from codrone_edu.drone import *
import time
drone = Drone()
drone.pair()
drone.load_color_data("color_data")
while True:
color_data = drone.get_color_data()
color = drone.predict_colors(color_data)
if color[0] == "green":
drone.drone_buzzer(Note.B4, 1000)
elif color[0] == "red":
drone.drone_buzzer(Note.A4, 1000)
elif color[0] == "yellow":
drone.drone_buzzer(Note.C4, 1000)
elif color[0] == "black":
drone.drone_buzzer(Note.G4, 1000)
else:
drone.drone_buzzer(0, 0)
print(color[0])
time.sleep(0.2)