簡體   English   中英

arduino和Visual Studio C ++,2路串行通信

[英]arduino and visual studio c++, 2 way serial communication

我正在使用Arduino和Visual Studio c ++,並試圖建立雙向實時串行通信。 我正在使用的是win 10(在VMware Fusion中),32位系統,Visual Studio 2013,Arduino IDE 1.8.0和Arduino開發板Uno。

我使用了來自http://playground.arduino.cc/Interface/CPPWindows的庫文件,它們是兩個文件: SerialClass.hSerial.cpp。 我在主程序中使用readData()WriteData()函數。

我想再運行幾次,用戶可以在控制台中輸入,而Arduino將相應地生成輸出。 但是,當我添加while循環時,它無法正常工作。

下面是我的main.cpp :(在注釋行中帶有while循環)

int main() {
    Serial* port = new Serial("COM3");
    if (port->IsConnected()) cout << "Connected!" << endl;

    char data[4] = "";
    char command[2] = "";
    int datalength = 4;  //length of the data,
    int readResult = 0;
    int n;

        for (int i = 0; i < 4; ++i) { data[i] = 0; } //initial the data array

        //read from user input 
        //this is where I added while loop 
      // while(1){
        std::cout << "Enter your command: ";
        std::cin.get(command, 2);     //input command 
        int msglen = strlen(command);
        if (port->WriteData(command, msglen));   //write to arduino
        printf("\n(writing success)\n");

        //delay
        Sleep(10);

        //read from arduino output
        n = port->ReadData(data, 4);
        if (n != -1){
            data[n] = 0;
            cout <<"arduino: " data << endl;
        }
     // } 

    system("pause");
    return 0;
}

和我的arduino代碼:

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    }


void loop() {
    // put your main code here, to run repeatedly:
    if (Serial.available() > 0) {
        char c = Serial.read();
        if (c == '1') 
          Serial.write("10");
        else if (c == '2') 
          Serial.write("20");
        else if (c == '3') 
          Serial.write("30");
        else
        Serial.write("Invalid");
    }

}

如果我在不使用while循環的情況下運行代碼,則可以得到想要的結果:

Connection established!!!
Enter your command: 1
arduino: 10

但是當添加while循環時,它會跳過要求輸入的內容,而我的輸出將變成:

Enter your command: 1
arduino: 10
Enter your command: arduino:
Enter your command: arduino:
Enter your command: arduino:
Enter your command: arduino:
...

在嘗試了一些解決方案后,我認為它可能是buffer data []和command [],在下一次運行之前我沒有將其清空。 但是我嘗試過

memset(data,0,4); 

要么

data[4]='\0';

但是它仍然不起作用,並跳過要求輸入的內容。 有什么建議可以解決嗎? 謝謝!

正如建議“如何沖洗cin緩沖液?” ,問題出在您的std::cin.get(command, 2); 碼。 多余的字符保留在std::cin並在下一次調用時直接重用。 第一個額外的字符是'\\n' (Enter鍵),並且std::cin.get()將返回0。

最好的解決方案是在獲取命令后忽略多余的字符。

std::cout << "Enter your command: ";
std::cin.get(command, 2);     //input command
std::cin.clear(); // to reset the stream state
std::cin.ignore(INT_MAX,'\n'); // to read and ignore all characters except 'EOF' 
int msglen = strlen(command);

代替

std::cout << "Enter your command: ";
std::cin.get(command, 2);     //input command 
int msglen = strlen(command);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM