Reading serial input from terminal

Hi,

I am trying to read serial input from my Ubuntu terminal but I am running into in issue. Can someone please help me understand why is it happening. I pretty new with Arduino and I am trying to learn more.

Below is the sketch

int LedPin = 13;
char val = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LedPin, OUTPUT);
}

// Read Value from serial and set a led high or low
void loop () {
  if (Serial.available() > 0) {
    String s = Serial.readStringUntil('\n');
    s.trim();
    Serial.println(s);
    
    if (s.equals("low")) {
      Serial.println("low");
      digitalWrite(LedPin,LOW);
    }
  
    if (s.equals("high")) {
      Serial.println("High");
      digitalWrite(LedPin,HIGH);
    }       
  }
}

Below is the output of my terminal which I am using as a serial monitor.

raghav@raghav-Latitude-5590:~$ stty -F /dev/ttyACM0 raw 115200
raghav@raghav-Latitude-5590:~$ cat /dev/ttyACM0
low
low
low^M^Jlow^M^J
low^M^Jlow^M^J^M
low^M^Jlow^M^J^M^
low^M^Jlow^M^J^M^high
low^M^Jlow^M^J^M^
low^M^Jlow^M^J^M^
low^M^Jlow^M^J^M^
low^M^Jlow^M^J^M^
^C

I cannot pass any other input after this.

Following is the command to send input to the serial. echo low > /dev/ttyACM0

It works absolutely fine when I run everything from the serial monitor.

Thanks, Any help is appreciated.

The ^M is a Carriage Return and the ^J is a Newline which you are sending from the terminal

But then why is it printing out the remaining text when I entered the command only once? and why can I not enter another command after that?

I don't know, but then I am not a user of Strings so have little experience of them

What happens if you either don't send the extra characters or detect them in the sketch and ignore them ?

Better still, use C style strings instead of Strings, which is the usual advice here

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.