// Program: Ex5_Q1_3_v2.ino
// Check of goodString using an all-in-one approach
/*
Exercise 5 Q1
Extend the program of Ex5_Array to read an integer
(with at most 2 digits) from the Serial Monitor and
print out a group of stars that is equal to the integer value.
The star should be arranged in rows of ten.
*/
char buf[100] = {0}; // this is an array
char inChar;
bool stringComplete = false;
int i = 0;
bool goodString;
int Num;
// declare the function
//char ConvertString(char);
void PrintStars(int);
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
}
Serial.println("Input a number:");
}
void loop()
{
while (Serial.available())
{
inChar = (char)Serial.read();
if (inChar == '\n') // change '\n' to '~' when using Tinkercad (Change 1 of 2)
{
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
//inChar = ConvertString(inChar);
buf[i++] = inChar;
}
}
if (stringComplete)
{
goodString = true;
/*
if ((i < 2) || (i > 3))
{
goodString = false;
}
else
{
//for (int j = 0; buf[j] != '\n'; j++) // change '\n' to '~' when using Tinkercad (Change 2 of 2)
for (int j = 0; j < i - 1; j++)
{
if (!isdigit(buf[j]))
goodString = false;
}
}
*/
if (((i == 2) && isdigit(buf[0])) || ((i == 3) && isdigit(buf[0]) && (isdigit(buf[1])))) {
goodString = true;
} else {
goodString = false;
}
if (goodString)
{
if (i == 2)
{
Num = buf[0] - '0';
}
else
{
Num = (buf[0] - '0') * 10 + (buf[1] - '0');
}
Serial.println(Num);
PrintStars(Num);
}
else
{
Serial.print(buf);
Serial.println("Incorrect input");
}
//Serial.print(buf); // the printing of string will be stopped when zero is reached
stringComplete = false;
i = 0;
Serial.println();
Serial.println("Input a number:");
}
}
// body of the function
/*
char ConvertString(char x)
{
if (isUpperCase(x))
return (toLowerCase(x));
else if (isLowerCase(x))
return (toUpperCase(x));
else
return (x);
}
*/
void PrintStars(int x)
{
for (int i = 1; i <= x; i++)
{
Serial.print("*");
if (!(i % 10))
Serial.println();
}
if (x % 10)
Serial.println();
return;
}