In: Computer Science
ARDUINO
Create a function that will ask the user to enter the values for each of the three colors (red, green and blue) between 0 and 255. The function should check that the user does not enter a number bigger than 255 or smaller than 0. If this happens, the function should keep asking for a valid number.
Please up vote .comment if any query . Thanks for question . Be safe .
Note : check attached image for output .code compiled and tested in Arduino IDE.
Program :
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //uart starts at baudrate 9600
delay(100); //delay to settle uart
getColorCode(); //function to get color code
}
void loop() {
}
void getColorCode()
{
int red=-1,green=-1,blue=-1; //assign -1 to color code integer
while(red>255 || red<0) //if red <0 or >255 keep
asking for color
{
red=serialData("red"); //function takes code for
red color and return integer value of code
}
while(green>255 || green<0) //keep asking till valid green
color code
{
green=serialData("green"); //pass color name to
get value
}
while(blue>255 || blue<0) //blue color code
{
blue=serialData("blue");
}
Serial.print("Red color code is : "); //print user input color
code
Serial.println(red); //red color code
Serial.print("Green color code is : ");
Serial.println(green); //green color
Serial.print("Blue color code is : ");
Serial.println(blue); //blue color code
}
int serialData(String colorName) //argument a string color
name
{
String color="";
Serial.println("Enter color code of "+colorName+" : "); //prompt
for color code passed by user
//when data not available serial.available return -1 else number of
data available on serial
while(!Serial.available()); //wait till did not input data on
serial
while(Serial.available()) //read serial data
{
color+=(char)Serial.read(); //read data from
serial as char and add to color
}
Serial.println("Your entered code is : "+color); //print user
input
return color.toInt(); //convert string to integer and return
}
Output :
Please comment if any changes , and up vote .