arduino和visual studio c ++,2路串行通信

我正在使用Arduino和Visual studio c ++并尝试构建双向实时串行通信。 我正在使用的是win 10(在VMware Fusion中),32位系统,visual studio 2013,Arduino IDE 1.8.0和Arduino板Uno。

我使用了http://playground.arduino.cc/Interfacing/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 <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: ... 

在尝试了一些解决方案后,我认为它可能是缓冲区数据[]和命令[],我没有在下次运行之前清空它。 但我试过了

 memset(data,0,4); 

要么

 data[4]='\0'; 

但它仍然不起作用,并跳过要求输入。 有什么建议我怎么解决? 谢谢!

建议发布“如何冲洗cin缓冲区?” ,问题位于你的std::cin.get(command, 2); 码。 额外的字符留在std::cin并在下次调用时直接重用。 第一个额外字符是'\n' (输入密钥), 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);