1
votes

I am running into a problem with my Arduino. I want to be able to open up my Serial monitor on the Arduino IDE and be able to type something like hello, and have the Arduino respond with a set response for that so called command so I could create a chat bot so to speak.

Here is my code, could someone please help me?

  byte byteRead;

  void setup() 
  {
       Serial.begin(9600);


  }

  void loop() 
  {
       if (Serial.available()) {

        byteRead = Serial.read();

        if(byteRead =="hello") {
        Serial.println("hello freind");
        }
  }
2

2 Answers

0
votes

You need to treat the serial input as a string rather than a byte.

Try declaring your input variable as type String:

String stringRead;

Read the string from the serial port using readString():

stringRead = Serial.readString();

And change your comparison from:

if(byteRead == "hello") {

to:

if (stringRead == "hello") {

Rather than Serial.readString(), you could also use Serial.readStringUntil().

Also, the Arduino website provides a nice reference of its Serial functionality that you may find helpful.

0
votes

byteRead =="hello" has too little chance of becoming true. Try reading a string (not only one character!) and comparing the characters in the strings one by one.

// read one line
void read_line(char *buf, int max)
{
  int i = 0;
  while(i < len - 1) {
    int c = Serial.read();
    if (c >= 0) {
      if (c == '\r' || c == '\n') break;
      buf[i++] = c;
    }
  }
  buf[i] = '\0';
}

// compare two strings and return whether they are same
int is_same(const char *a, const char *b)
{
  while (*a != '\0' || *b != '\0') {
    if (*a++ != *b++) return 0;
  }
  return 1;
}

void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  if (Serial.available()) {
    char stringRead[128];
    read_line(stringRead, 128);
    if(is_same(stringRead, "hello")) {
        Serial.println("hello freind");
    }
  }
}