使用Qt的串行端口的扩展行为 [英] extrange behavior of serial port using Qt
问题描述
我正在使用QT执行一个应用程序,以通过rs-232与8位微控制器进行PC通信.我正在使用QtSerialPort库,并且通讯正常,但是每次我从PC向微型计算机写东西并且收到响应时,我都必须关闭并打开串行端口,否则我将无法继续通讯.配置为:10500 bps,8位,1个停止,无奇偶校验,无流量控制.
I am performing an app with QT for communicate my PC with an 8 bits microcontroller through rs-232. I am using the QtSerialPort library and the communication is working fine, but each time I write something from the PC to the micro and I receive the response, I have to close and open the serial port or I can't continue communicating.. My configuration is: 10500 bps, 8 bits, 1 stop, no parity, no flow control.
下一个用于配置和端口的演讲/写作的代码:
The code used for the configuration and the lecture/writting of the port is the next:
bool DriverS::configure(int port, int baudRate)
{
if(port!=22)
return false;
serialPort->setPortName("COM22");
if (serialPort->open(QIODevice::ReadWrite)==true){
if (!serialPort->setBaudRate(baudRate)) {
return false ;
}
if (!serialPort->setDataBits(QSerialPort::Data8)) {
return false ;
}
if (!serialPort->setParity(QSerialPort::NoParity)) {
return false;
}
if (!serialPort->setStopBits(QSerialPort::OneStop)) {
return false;
}
if (!serialPort->setFlowControl(QSerialPort::NoFlowControl)){
return false;
}
};
return true;
}
bool DriverS::read(QByteArray & rxData, int * size)
{
Sleep(200);
*size = 0;
if (serialPort->waitForReadyRead(TIMEOUT_SERIAL)) {
rxData = serialPort->readAll();
*size = rxData.size() ;
if (!this->checkCRC(rxData))
{
qDebug()<< "Rx Checksum Error";
return false;
}
return true;
}
qDebug()<< "Rx Timeout";
return false;
}
bool DriverS::write(QByteArray txData)
{
unsigned int chk = 0;
int ret ;
for(int i = 0;i<txData.size();i++)
{
chk+=txData.at(i);
}
txData.append(chk);
ret = serialPort->write(txData);
return (txData.size()==ret);
}
推荐答案
我解决了两个问题(尽管我不确定这些方法).
I fixed my two problems (despite I am not sure about the methods).
对于第1个问题(每次我想进行通信时都要打开和关闭端口),我只是在我的write方法中添加了一个waitFoBytesWritten().
For problem num 1 (open and close the port each time I wanted to communicate) I just added a waitFoBytesWritten() in my write method.
对于问题2(我只能使用port22),我已经修改了配置,现在我首先检测到availablePorts()可用的端口,而不是强制使用我要使用的端口.现在,我可以将设备连接到任何可用端口,并且可以使用.
For my problem num 2, (I only was able to work with port22), I have modified the configuration and now I first detect wich ports are available with availablePorts() instead to force the port I want to use. Now I can connect my device to any free port and it works..
这篇关于使用Qt的串行端口的扩展行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!