2

您好,提前感谢您的帮助。我有一个应用程序,它从 BeamNG Drive 读取速度、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;
    }

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

4

1 回答 1

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;
}      
于 2018-12-15T19:01:49.017 回答