// Program: 1X Ex5 Q1 Chan Tai Ming_2.ino
// Program: Ex5_Array.ino
/*
Exercise 5 Array, string, and function
Echo with some modifications
*/
char buf[100] = {0}; // this is an array
char inChar;
bool stringComplete = false;
int i = 0;
// declare the function
// char ConvertString(char);
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()
{
int num;
bool goodString = true;
while (Serial.available())
{
inChar = (char) Serial.read();
buf[i++] = inChar;
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
// inChar = ConvertString(inChar);
// buf[i++] = inChar;
}
}
if (stringComplete)
{
Serial.print(buf); // the printing of string will be stopped when zero is reached
// Define the actions
// Serial.println(i);
if ((i < 2) || (i > 3)) {
goodString = false;
} else {
for (int j = 0; j < i - 1; j++) {
if (!isDigit(buf[j])) {
goodString = false;
}
}
}
if (goodString) {
if (i == 2) {
num = buf[0] - '0';
} else {
num = (buf[0] - '0') * 10 + (buf[1] - '0');
}
// Serial.println("Good");
PrintStars(num);
} else {
Serial.println("Incorrect input");
}
Serial.println();
Serial.println("Input a number:");
stringComplete = false;
i = 0;
}
}
// 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 n) {
for (int i = 1; i <= n; i++) {
Serial.print("*");
if (!(i % 10)) {
Serial.println();
}
}
if (n % 10) {
Serial.println();
}
}