How to read a string value with a delimiter on Arduino?

后端 未结 7 912
小鲜肉
小鲜肉 2020-12-10 03:34

I have to manage servos from a computer.

So I have to send manage messages from computer to Arduino. I need manage the number of servo and the corner. I\'m thinking

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 04:09

    Most of the other answers are either very verbose or very general, so I thought I'd give an example of how it can be done with your specific example using the Arduino libraries:

    You can use the method Serial.readStringUntil to read until your delimiter from the Serial port.

    And then use toInt to convert the string to an integer.

    So for a full example:

    void loop() 
    {
        if (Serial.available() > 0)
        {
            // First read the string until the ';' in your example
            // "1;130" this would read the "1" as a String
            String servo_str = Serial.readStringUntil(';');
    
            // But since we want it as an integer we parse it.
            int servo = servo_str.toInt();
    
            // We now have "130\n" left in the Serial buffer, so we read that.
            // The end of line character '\n' or '\r\n' is sent over the serial
            // terminal to signify the end of line, so we can read the
            // remaining buffer until we find that.
            String corner_str = Serial.readStringUntil('\n');
    
            // And again parse that as an int.
            int corner = corner_str.toInt();
    
            // Do something awesome!
        }
    }
    

    Of course we can simplify this a bit:

    void loop() 
    {
        if (Serial.available() > 0)
        {
            int servo = Serial.readStringUntil(';').toInt();
            int corner = Serial.readStringUntil('\n').toInt();
    
            // Do something awesome!
        }
    }
    

提交回复
热议问题