【发布时间】:2016-12-30 09:39:18
【问题描述】:
我正在使用 Arduino 和 Visual Studio C++ 并尝试构建双向实时串行通信。 我使用的是win 10(在VMware Fusion中),32位系统,visual studio 2013,Arduino IDE 1.8.0和Arduino board Uno。
我使用了来自http://playground.arduino.cc/Interfacing/CPPWindows 的库文件,它们是两个文件:SerialClass.h 和 Serial.cpp。 我正在使用 readData() 和 WriteData() 函数在我的 main 中。
我想再运行几次,用户可以在控制台中输入,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:
...
尝试了一些解决方案后,我认为可能是缓冲区 data[] 和 command[] ,我没有在下次运行前清空它。但我已经尝试过
memset(data,0,4);
或
data[4]='\0';
但它仍然不起作用并跳过询问输入。有什么建议我该如何解决?谢谢!
【问题讨论】:
标签: c++ c visual-studio arduino serial-communication