问题
I am trying to write a QT application that can communicate with a propeller over USB. Reading through the documentation QSerialPort seems to be exactly what I need. For a simple test, I am trying to send the number "2" to my propeller project. The project itself has its own OLED screen that I can read results on. Here is the QT code itself:
this->Serial=new QSerialPort(this);
this->Serial->setPortName("/dev/ttyUSB0");
this->Serial->setBaudRate(QSerialPort::Baud9600);
connect(this->Serial,SIGNAL(error(QSerialPort::SerialPortError)),this,SLOT(errorReport(QSerialPort::SerialPortError)));
if(this->Serial->open(QIODevice::ReadWrite))
{
QByteArray dayArray;
QDataStream stream(&dayArray, QIODevice::WriteOnly);
stream << 2;
qDebug()<< dayArray.toHex();
qDebug()<< this->Serial->portName();
if(this->Serial->setDataBits(QSerialPort::Data8))
{
qDebug()<<"bits set to 8";
}
this->Serial->write(dayArray.toHex());
this->Serial->waitForBytesWritten(-1);
this->Serial->close();
}
and the error report slot is:
void serial::errorReport(QSerialPort::SerialPortError error)
{
if(error!=0)
qDebug()<<"ERROR:"<<endl<<error;
}
The console debug statements print this:
"00000002"
"ttyUSB0"
bits set to 8
However when I read the values the propeller recieves, it ranges from 0xD0, 0xF0, or 0xE0, not the 0x02 I was expecting. The baud rates in the code match that of the chip and I am really not sure what is wrong. Can anyone point out the fault?
EDIT: I know that the propeller code isn't the problem as it works fine with the Arduino's IDE serial console.
回答1:
I finally figured it out. The working code is as follows:
if(this->Serial->open(QIODevice::ReadWrite))
{
this->Serial->setBaudRate(QSerialPort::Baud9600);
this->Serial->setParity(QSerialPort::NoParity);
this->Serial->setStopBits(QSerialPort::OneStop);
this->Serial->setFlowControl(QSerialPort::NoFlowControl);
this->Serial->setDataBits(QSerialPort::Data8);
QByteArray dayArray;
dayArray[0]=2;
this->Serial->write(dayArray);
this->Serial->waitForBytesWritten(-1);
this->Serial->close();
}
来源:https://stackoverflow.com/questions/18806001/trouble-sending-data-with-qserialport