使用 QSerialPort 发送数据时遇到问题
我正在尝试编写一个可以与 propeller 通信的 QT 应用程序通过 USB.通读文档 QSerialPort 似乎正是我所需要的.对于一个简单的测试,我试图将数字2"发送到我的螺旋桨项目.该项目本身有自己的 OLED 屏幕,我可以在上面阅读结果.这是 QT 代码本身:
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();
}
错误报告槽是:
void serial::errorReport(QSerialPort::SerialPortError error)
{
if(error!=0)
qDebug()<<"ERROR:"<<endl<<error;
}
控制台调试语句打印:
"00000002"
"ttyUSB0"
bits set to 8
但是,当我读取螺旋桨接收到的值时,它的范围是 0xD0、0xF0 或 0xE0,而不是我期望的 0x02.代码中的波特率与芯片的波特率相匹配,我真的不确定出了什么问题.谁能指出错误?
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?
我知道螺旋桨代码不是问题,因为它在 Arduino 的 IDE 串行控制台上运行良好.
I know that the propeller code isn't the problem as it works fine with the Arduino's IDE serial console.
我终于想通了.工作代码如下:
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();
}