// Program: 1C Ex5 Q1 Lau Ngai Chun.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;
void setup()
{
// Initialize serial and wait for port to open
Serial.begin(115200);
}
// ** IMPORTANT **
// MUST use buf[]
// CAN'T use functions like Serial.parseInt, Serial.readString
void loop()
{
int num;
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
{
// buf[i++] = inChar;
}
}
if (stringComplete)
{
Serial.print(buf); // the printing of string will be stopped when zero is reached
// Serial.println(i);
// Serial.println();
if ((i == 2) && isDigit(buf[0])) {
num = buf[0] - '0';
PrintStars(num);
}
// Serial.println(num);
// Code to handle 2 digits
// if ((i == 3) && ...
if ((i == 3) && isDigit(buf[0]) && isDigit(buf[1]) ) {
num = (buf[0] - '0') * 10 + (buf[1] - '0' );
PrintStars(num);
}
// Code for UI (User Interface) including
// message for incorrect input
// Format the output nicely, refer to the example on the worksheet
PrintStars(0);
stringComplete = false;
i = 0;
// num = 0;
}
}
void PrintStars(int n) {
// Other than for, we can also use while or do-while
// Initial value of j equals to 0 or n
for (int j = 1; j <= n; j++) {
Serial.print("*");
if (j % 10 == 0) {
Serial.println();
}
// Add code such that 10 stars are printed on a row
// Hint: use % (remainder/mod operator) so that a new line
// is produced when j is a multiple of 10
}
Serial.println();
}