我开始使用Visual C ++,我正在尝试编写一个使用Arduino发送和接收某些数据的程序。但是,它似乎没有正常工作。例如,当使用Compare :: String时,即使我从Arduino发送完全相同的单词,它也会返回1而不是0。
可视化C ++代码如下:
private: System::Void backgroundWorker1_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
while (true)
{
try {
String^ tempVal = Arduino->ReadLine();
this->SetText(tempVal); //Calls the secure method for analyse the incoming data
Arduino->DiscardInBuffer();
}
catch (TimeoutException^) {
}
}
}
delegate void SetTextDelegate(String^ text);
private: String^ IDemitter;
private: String^ Subred;
private: String^ Data;
private: String^ Options;
private: int Memoria;
private: void SetText(String^ texto)
{
if (this->textReceive->InvokeRequired)
{
SetTextDelegate^ d = gcnew SetTextDelegate(this, &MyForm::SetText);
this->Invoke(d, gcnew array<Object^> { texto });
}
else
{
if (String::Compare(texto, "DATA") == 1) { //Theoretically it should be 0, but it returns 1
this->Arduino->WriteLine("OK");
this->textReceive->Text = "OK";
Memoria = 1;
texto = "0";
}
else if ((Memoria == 1) && (String::Compare(texto, "0") != 0)) { //It never reaches this stage...
IDemitter = texto;
this->Arduino->WriteLine("OKID");
this->textReceive->Text = "OKID";
Memoria = 2;
texto = "0";
}
else if ((Memoria == 2) && (String::Compare(texto, "0") != 0)) {
Subred = texto;
this->Arduino->WriteLine("OKSUB");
Memoria = 3;
texto = "0";
}
else if ((Memoria == 3) && (String::Compare(texto, "0") != 0)) {
Options = texto;
this->textReceive->Text = "OKOPT";
this->Arduino->WriteLine("OKOPT");
Memoria = 4;
texto = "0";
if (Options != "9") {
this->ProcessData(IDemitter, Subred, Options);
}
}
else if ((Memoria == 4) && (String::Compare(texto, "0") != 0) && (Options=="9")) {
Data = texto;
this->Arduino->WriteLine("OKDATA");
this->textReceive->Text = "OKDATA";
Memoria = 5;
texto = "0";
this->ProcessData(IDemitter, Subred, Options, Data);
}
}
}
简化的Arduino代码如下。
String confirmation;
void setup () {
Serial.begin(9600);
while(!Serial) { ; }
}
void loop () {
while(confirmation!="OK"){
Serial.println("DATA");
delay(5000);
confirmation=Serial.readString();
}
Serial.print("3"); //IDemitter
while(confirmation!="OKID"){
confirmation=Serial.readString();
}
Serial.print("2"); //Subred
while(confirmation!="OKSUB"){
confirmation=Serial.readString();
}
Serial.print("7"); // Options
while(confirmation!="OKOPT"){
confirmation=Serial.readString();
}
我的想法是在收到所有参数后在ProcessData()中运行,但我认为它应该更加困难。 任何帮助将非常感激。
答案 0 :(得分:0)
在Arduino程序发送的“DATA”字符串中附加换行符。然后,PC的readline应该可以正常工作。