0
votes

I've been working on the school project with Gird-Eye. I use the Arduino Uno to access the data form Grid-Eye. And now I want to implement a serial communication test program with c++. I use the library form here:

http://playground.arduino.cc/Interfacing/CPPWindows

Here is Arduino Code:

int data[64];

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    for (int i = 0; i < 64; ++i) {
        data[i] = i;
    }
}

void loop() {
    // put your main code here, to run repeatedly:
    if (Serial.available() > 0) {
        char c = Serial.read();
        if (c == 'h') { Serial.write("Hello\r\n"); }
        else if (c == 'i') {
            for (int i = 0; i < 64; ++i) 
                Serial.println(data[i]);
        }
    }
}

And Here is main.cpp code:

int main() {
    Serial* port = new Serial("COM5");

    if (port->IsConnected()) cout << "Connection established!!!" << endl;

    char data[256] = "";
    int datalength = 256;
    int readResult = 0;

    for (int i = 0; i < 256; ++i) { data[i] = 0; }

    string str;
    char command[] = "i";
    int msglen = strlen(command);
    port->WriteData(command, msglen);
    while (1) {
        while (port->ReadData(data, 256) != -1) {
            printf("%s", data);
        }
    }
    system("pause");
    return 0;
}

I can get the value successfully with this interface. However the window additional shows extra value. For Example, the program should ends like this.

....
61
62
63

But I get

...
61
62
63
50
51
52
53

I have no idea why there is extra value. Could anyone tell me why? Thanks!!!

1

1 Answers

0
votes

I believe that you need to terminate the string that you put into the data buffer in each loop iteration:

while ((n = port->ReadData(data, 256)) != -1) {
    data[n] = 0;
    printf("%s", data);
}