[英]Visual C++: Unsuccessful communication through serial port with Arduino
我从Visual C ++开始,正在尝试编写一个使用Arduino发送和接收某些数据的程序。 但是,它似乎无法正常工作。 例如,即使当我从Arduino发送完全相同的单词时,使用Compare :: String时,它也会返回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()中进行操作,但是我认为应该更困难。 任何帮助将非常感激。
在从Arduino程序发送的“ DATA”字符串后添加换行符。 然后,来自PC的读取线应正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.