0

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);
    }
  }
}
2
  • "it is not working like I was expecting." - so what does it actually do? Commented Sep 8, 2013 at 0:41
  • Why don't you print what characters you are actually receiving? (As a means of debugging the problem, not a permanent solution) Commented Sep 8, 2013 at 0:51

1 Answer 1

1

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 = "";    
        }   
    }   
}   
Sign up to request clarification or add additional context in comments.

3 Comments

this is useful but is there any way to do that using charAt() function?
@mafap Do you understand what was wrong with your existing code? You could use charAt() after you've appended to the string, but I'm not particularly sure why you would.
Now I understand. I wanted to use this function because I need to get the value of characters at different positions in a String. I just don't know what's the better way to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.