将Arduino串行输入分为多个字符串

时间:2018-12-15 17:34:09

标签: arduino

您好,谢谢您的帮助。 我有一个应用程序,可以从BeamNG驱动器读取速度,rpm和齿轮值,然后将它们打印到COM端口。它循环运行,使用结束字节分隔值。

RPM_END_BYTE = '+'; 
SPEED_END_BYTE = '='; 
GEAR_END_BYTE = '!'; 

使用这些结束字节,我想知道如何在arduino中将输入分成三个字符串。我可以将它们直接转换为整数,也可以使用string.toInt();进行转换。这就是程序的串行输出的一个循环的样子:

02500+120=6!

我已经在PC上设置了一个虚拟COM端口,以检查该软件是否正常运行,但是我似乎无法弄清楚如何将输入分开。

我还使用了以下代码,当我通过串行监视器输入数字并以'+'结尾时,该代码可以工作,但不适用于我的软件。

const byte numChars = 32;
char receivedChars[numChars];   // an array to store the received data
#include <LiquidCrystal.h>
boolean newData = false;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
void setup() {
    Serial.begin(9600);

    lcd.begin(16, 2);
}

void loop() {
    recvWithEndMarker();
    showNewData();
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '+';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '+'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        lcd.setCursor(0, 1);
        lcd.clear();
        lcd.print(receivedChars);
        newData = false;
    }

非常感谢任何可以提供帮助的人。抱歉,如果您已经提出过类似的问题,但我找不到。

1 个答案:

答案 0 :(得分:0)

解决方案的一个例子:我已经使用3个endMarkers修改了可以使用'+'的程序

char endMarker[3] = {'+', '=', '!'};

while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();
    int returnvalue = testifendMarker(rc);
    if (returnvalue < 0 {
        receivedChars[ndx] = rc;
        ndx++;
        if (ndx >= numChars) {
            ndx = numChars - 1;
        }
    }
    else {
            if (returnvalue == 0){
                 // terminate the string with + do your stuff
                 // maybe use lcd.setCursor(Col, Row) to set the cursor position
                 receivedChars[ndx] = '+';
            }else if (returnvalue == 1){
                 // terminate the string with = do your stuff
                 // maybe use lcd.setCursor(Col, Row) to set the cursor 
                 receivedChars[ndx] = '=';
            }else {
                 // terminate the string with ! do your stuff
                 // maybe use lcd.setCursor(Col, Row) to set the cursor 
                 receivedChars[ndx] = '!';
            }
            //display the result on lcd
            lcd.print(receivedChars);// you just display 
            ndx = 0;
            // newdata = true; put this boolean to true terminate the loop while
    }
}   

int testifendMarker(char c) {
    for (int i=0; i < 3; i++){
            if (endMarker[i] == c){
                return i;
            }
    }

    return -1;
}