简体   繁体   中英

Communication error between Arduino and Qt using Xbee PRO S1

I've been trying to do a Lights GUI with an Arduino Mega 2560 with its Xbee Shield and two Xbee Pro S1, one connected to the Arduino and the other one to the PC. My problem is: however I can send data from Qt to my arduino and read it, i can't do the same in the other way. When trying to send a String as "Confirmado\\r\\n", it arrives to my Qt label wrong, sometimes I get the full String, other ones I receive half of it.

My arduino code is

char buffer[50];
String trama, dir, com, data;
int indexdir, indexcom, indexdata;

void setup(){
  Serial.begin(9600);
}

void loop(){

   trama= "Confirmado\r\n";
   const char *bf = trama.c_str();

   if(Serial.available() > 0)
   {
       Serial.readBytesUntil('/', buffer,500);
       Serial.print(bf);
       Serial.flush();
   }
}

My Qt QSerialPort config is

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serial = new QSerialPort(this);
    serial->setPortName("COM3"); //COM-port your Arduino is connected to
    serial->open(QIODevice::ReadWrite);
    serial->setBaudRate(QSerialPort::Baud9600);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived()));
}

And I send and read data like this

void MainWindow::serialReceived()
{
  QByteArray  readData = serial->readAll();
    //while (serial->waitForReadyRead(500))
        // readData.append(serial->readAll());
    ui->label->setText(readData);
}

void MainWindow::writeData(const QByteArray &data)
{
    serial->write(data);
    serial->flush();
    serial->waitForBytesWritten(500);
}

The toogle lines means I've tried both options...

I've noticed, doing Debug, that if I place a breakpoint in ui->label->setText(readData); ; if it doesnt arrive well (the full "Confirmado\\r\\n" string), this breakpoint gets twice in this line, the first one readData equals the second half of the string (ie "mado\\r\\n") and the other one it values the rest of the string (ie "Confir").

I've also tried to set a higher baudrate, 57600, but I cant send or receive any data, though I've set the baudrate in the XCTU app before.

Does anyone know a way to receive the full string from Arduino? Or at leats how to setup properly Arduino's and PC's Xbee to work with higher baudrates?

Thanks for the answers, and sorry for my writing skills...

尝试使用serial->readLine()而不是serial->readall() ,例如,您可以在serial->canReadLine()返回true之后循环等待,然后确保收到的数据是完整字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM