/*
Serial read from serial monitor
(while using one method, comment the other one.
setup for both methods is same, however loop is different)
1st method :
Serial.read() function is used to read the message by reading one char at a time.
To convert string (char array) to int, the atoi() function is used.
2nd method :
Serial.readString() is used to directly read the entire message (string)
To convert String (object) to int, the toInt() function is used
*/
void setup(){
Serial.begin(9600);
Serial.println("hello world");
}
/* method 1 : */
void loop(){
// function to read data from serial monitor
while(Serial.available() > 0){
static char message[12];
static int msg_pos = 0;
char inByte = Serial.read();
if(inByte != '\n'){
message[msg_pos] = inByte;
msg_pos++;
}
else{
message[msg_pos] = '\0';
int num_msg = atoi(message);
if(num_msg != 0){
Serial.print("Num : ");
Serial.println(num_msg);
}
else{
Serial.print("Str : ");
Serial.println(message);
}
msg_pos = 0;
}
}
}
/* method 2: */
void loop(){
if(Serial.available() > 0){
String message = Serial.readString();
int num_msg = message.toInt();
if(num_msg != 0){
Serial.print("Num :");
Serial.println(num_msg);
}
else{
Serial.print("Str : ");
Serial.println(message);
}
}
}