xxxxxxxxxx
class Apple { // creating a class with a polymorphical function
public:
void eating(int i) { // if eating will be entered with one variable,
if (i == 1) { // then this is gonna be the code of the function.
Serial.print(i);
Serial.println(" human is eating an apple");
}
else if (i > 1) {
Serial.print(i);
Serial.println(" people are eating an apple");
}
}
void eating(String i, int a) { // this is the code for two variables,
Serial.print(i); // if one is string, and another integral.
Serial.print(" is eating an apple with ");
if (a == 1) {
Serial.println("1 human");
}
else if (a > 1) {
Serial.print(a);
Serial.println(" people");
}
}
};
String messagestr; // variable for String message from the serial port.
int messageint; // variable for integral message.
const unsigned int MAX_MESSAGE_LENGTH = 12; // max message length of the message.
String vpih; // a variable to "remember" messagestr.
Apple object; // a class object.
void setup() {
Serial.begin(9600); // starting the Serial port
}
void loop() {
while (Serial.available() > 0) { //Recieving a message from the Serial port
// more about it's creation on https://www.youtube.com/watch?v=nSGnCT080d8&t=148s
static char message[MAX_MESSAGE_LENGTH];
static unsigned int message_pos = 0;
char inByte = Serial.read();
if (inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)) {
message[message_pos] = inByte;
message_pos++;
}
else {
message[message_pos] = '\0';
messageint = atoi(message); // if the message I receive is integral,
if (messageint == 0) { // then it is being put here.
messagestr = message; // if the message is not integral, then put it here.
}
if (messagestr != "" && messagestr != vpih) { // if the program has received a string message
vpih = messagestr; // and it's not the same it was previously,
} // then put it into this variable temporarily.
if (vpih != "" && messageint != 0) { // if the temporal variable has a message and there is an
object.eating(vpih, messageint); // integral message, then do the function with these variables.
vpih = ""; // resetting the variable after the function.
}
else if (messagestr == "" && messageint != 0) {// if there is no message received as a string and
object.eating(messageint); // there is a message received as an integral,
} // then do the function with the number.
messagestr = ""; // reset all the variables
messageint = 0;
message_pos = 0;
}
}
}