mafap
mafap

Reputation: 391

Unexpected output on Arduino

I'm using Leonardo and I want to print a message when I type ">" and "<". Something like >my_message<.

I have the following code but it is not working like I was expecting (nothing happens). How can I fix this or is there a better way to do this?

String txtMsg = ""; // a string for incoming text

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect. Needed for Leonardo only
}

void loop() {
  // add any incoming characters to the String:
  while (Serial.available() > 0) {
    char inChar = Serial.read();
    txtMsg += inChar;

    char StartDelimiter = txtMsg.charAt(0);
    int endDel = txtMsg.length() - 1;
    char EndDelimiter = txtMsg.charAt(endDel);

    if (StartDelimiter == '>' && EndDelimiter == '<') {
      Serial.println(txtMsg);
    }
  }
}

Upvotes: 0

Views: 133

Answers (1)

Macattack
Macattack

Reputation: 1990

The problem was that your code looking for '>' always looked at character 0 and you were appending to your string, so after getting a first non '>' character you could never get to a condition in which you would print.

String txtMsg = ""; // a string for incoming text

void setup() {
    Serial.begin(9600);
    while (!Serial); // wait for serial port to connect. Needed for Leonardo only
}

void loop() {
    // add any incoming characters to the String:
    int got_start = 0;
    while (Serial.available() > 0) {
        char inChar = Serial.read();
        if (inChar == '>' && !got_start) {
            got_start = 1;
        }
        if (got_start) {
            txtMsg += inChar;
        }   
        if (inChar == '<' && got_start) {
            got_start = 0; 
            Serial.println(txtMsg);
            txtMsg = "";    
        }   
    }   
}   

Upvotes: 1

Related Questions