使用vs2008建立qt工程,编写一个简单的串口程序,但是运行后只能发送数据,无法接受。
主要代码如下:
//初始化设置
TestSerial::TestSerial(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
m_SerialPort=NULL;
ui.portcbx->addItems(PortName);
ui.baudcbx->addItems(BaudRate);
ui.datacbx->addItems(DataBits);
ui.paritycbx->addItems(Parity);
ui.stopcbx->addItems(StopBits);
ui.datacbx->setCurrentIndex(3);
readcount=0;
writecount=0;
ui.sendlet->setText(QString::number(writecount));
ui.receivelet->setText(QString::number(readcount));
connect(m_SerialPort,SIGNAL(readyRead()),this,SLOT(readSerialPort()));
}
//发送函数
void TestSerial::on_sendbtn_clicked()
{
if(m_SerialPort==NULL || !m_SerialPort->isOpen())
{
QMessageBox::information(this,"Error","Port Closed!");
return;
}
int count=ui.sendText->toPlainText().length();
writecount+=count;
ui.sendlet->setText(QString::number(writecount));
m_SerialPort->write(ui.sendText->toPlainText().toAscii());
}
//接收函数
void TestSerial::readSerialPort()
{
QMessageBox::information(this,"serial","serial test!");
QByteArray temp=m_SerialPort->readAll();
int count=m_SerialPort->bytesAvailable();
ui.receiveText->insertPlainText(QString(temp));
readcount+=count;
ui.receivelet->setText(QString::number(readcount));
}
通过实验发现readSerialPort()槽函数根本没有响应,但是可以发送数据!
------解决方案--------------------
请把 m_SerialPort 的Declaration发一下
------解决方案--------------------
ip 端口什么正确么 又没接听?
------解决方案--------------------
m_SerialPort=NULL;你的串口对象是NULL啊,肯定链接不上啊,你怎么对串口对象实例化初始化的?