繁体   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