//Student Name: Ho Kwok Fai
//Class: EG524403-1A
//Student Number: 230311289
char buf[100] = {0}; // this is an array
char inChar;
bool stringComplete = false;
int i = 0;
// declare the function
void Printstar(int starNum);
void setup()
{
// Initialize serial and wait for port to open
Serial.begin(115200);
while (!Serial)
{
// Wait for serial port to connect, needed for native USB port only
}
}
void loop()
{
while (Serial.available())
{
inChar = (char)Serial.read();
if (inChar == '\n') // change '\n' to '~' when using Tinkercad
{
buf[i++] = inChar; // last character is newline
buf[i] = 0; // string array should be terminated with a zero
stringComplete = true;
}
else
{
// some actions after received
buf[i++] = inChar;
}
}
if (stringComplete)
{
Serial.print(buf); // the printing of string will be stopped when zero is reached
// Check if the input is a valid integer between 1 and 99
if(isdigit(buf[0]) == true && buf[1] == '\n') // Convert the input string to an integer and pass it to the Printstar function
{
Printstar(buf[0]-'0');// Let the ASCII value of buf[0] change to Character
}
else if (isdigit(buf[0]) == true && isdigit(buf[1]) == true && (buf[2]) == '\n') // Convert the two-digit input string to an integer and pass it to the Printstar function
{
Printstar((buf[0]-'0')*10+(buf[1]-'0')); // Let the ASCII value of buf[0]&[1] change to Character
}
else
{
Serial.println("Incorrect input");
}
stringComplete = false;
i = 0;
}
}
// body of the function
void Printstar(int starNum) // Function to print stars based on the given number
{
for(int j=1; j<=starNum; j++)
{
Serial.print('*');
if(j%10 == 0 )
Serial.print('\n'); // Print a newline character after every 10 stars
}
Serial.print('\n'); // Print an extra newline character at the end
}