Reputation: 83
I am using a Arduino Uno for an embedded systems course. My assignment is that I have to write a function that implements these specifications. Take an input from the user (‘R’, ‘G’, ‘B’) and display Red, Green or Blue. The function name must be dispColor(), the input must be char a and their is no return. My code is below, however whenever I type in an input I receive no output. Where is the error in my code?
String dispColor(char){
char a = Serial.read();
if (a == "R")
Serial.print("Red");
else if (a == "G")
Serial.print("Green");
else if (a == "B")
Serial.print("Blue");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
String dispColor();
}
void loop() {
// put your main code here, to run repeatedly:
}
My Updated code
void dispColor(char a){
if(Serial.available()){
a = Serial.read();
if(a == 'R')
Serial.print("Red");
else if(a == 'G')
Serial.print("Green");
else if(a == 'B')
Serial.print("Blue");
}
}
void setup() {
Serial.begin(9600);
Serial.println("Please type in R, G, or B.");
dispColor();
}
void loop() {
}
Upvotes: 0
Views: 247
Reputation: 83
I figured it out!
My new code
void setup()
{
Serial.begin(9600);
Serial.println("Please type in R, G, or B.");
}
void dispColor(char a)
{
while(!Serial.available());
a = Serial.read();
if(a == 'R')
Serial.println("Red");
else if(a == 'G')
Serial.println("Green");
else if(a == 'B')
Serial.println("Blue");
Serial.print('\n');
}
void loop() {
char a;
dispColor(a);
}
Upvotes: 0
Reputation: 312
As says the comment in setup
("// put your setup code here, to run once:", that code will be executed only once, so when you're ready to "type an input", there will not be any code running to read it.
Thus, one thing you'll definitely need to do is move dispColor
to loop
.
There are a few more mistakes:
dispColor
, not reading from within itdispColor
if there's input available.Have a look at https://www.arduino.cc/reference/en/language/functions/communication/serial/read/ to get started!
Upvotes: 1