Now, let's not just send messages to the microcontroller; let's also learn how to receive information from it so we can have even more control over components like the RGB LED!
In this part of the sketch, we’re going to add a new variable of type ‘String’ called colorinput. You’ll also see we’ve changed the pin variables. This helps when troubleshooting.
To print data to the serial monitor, use Serial.print("What color do you want?");. But it will repeat on the same line, so instead we’ll use Serial.println("What color do you want?"); to print each message on a new line.
Next, we use while (Serial.available() == 0) {} to make the program wait for input. This line prevents the sketch from moving on until we type something in the serial monitor.
Finally, we add two lines to help us see what’s going on. Serial.print("Received color input: ") displays a message, and Serial.println(colorinput) shows us what we typed.
// Lesson 5, part 2
// Variables
// Serial monitor must be set to "NO LINE ENDING"
int redPin = 3;
int greenPin = 5;
int bluePin = 6;
int dtGreen = 500;
int dtBlue = 1000;
int dtRed = 1500;
String colorInput;
void setup() {
// put your setup code here, to run once:
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(9600);
}
void loop() {
//put your main code here, to run repeatedly:
Serial.println("What colour do you want?");
while (Serial.available() == 0) {
}
colorInput = Serial.readString();
Serial.println("Received color input: ");
Serial.println(colorInput);
if (colorInput == "red") {
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
}
if (colorInput == "green") {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, LOW);
}
if (colorInput == "blue") {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, HIGH);
}
}