|
yafeilinux 发表于 2015-1-7 10:50
用什么通信,串口还是udp、tcp
udp通信。我将固定格式的数据报发送给485模块,它收到这个数据报后,将对应传感器的温度和湿度信息(9个字节的16进制数据)返回。现在的问题是,我将数据包成功发送了,可是接收不到!这是代码:- #include<QNetworkInterface>
- #include<QMessageBox>
- #include<QHostInfo>
- #include"networkinformation.h"
- NetworkInformation::NetworkInformation(QWidget *parent)
- :QWidget(parent)
- {
- hostLabel=new QLabel(tr("tem:"));
- LineEditLocalHostName=new QLineEdit;
- ipLabel=new QLabel(tr("hum:"));
- LineEditAddress=new QLineEdit;
- detailBtn=new QPushButton(tr("send"));
- mainLayout=new QGridLayout(this);
- mainLayout->addWidget(hostLabel,0,0);
- mainLayout->addWidget(LineEditLocalHostName,0,1);
- mainLayout->addWidget(ipLabel,1,0);
- mainLayout->addWidget(LineEditAddress,1,1);
- mainLayout->addWidget(detailBtn,2,0,1,2);
- setWindowTitle("Network");
- connect(detailBtn,SIGNAL(clicked()),this,SLOT(slotDetail()));
-
- //port=8000;
- udpsocket=new QUdpSocket(this);
- receiver=new QUdpSocket(this);
- //receiver->bind(8000,QUdpSocket::ShareAddress);
- connect(receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
- }
- void NetworkInformation::slotDetail() //发送信息
- {
- //char str[128]={0x01,0x04,0x00,0x00,0x00,0x02,0x71,0xcb};
- QByteArray ba;
- ba.resize(8);
- ba[0]=0x01;
- ba[1]=0x04;
- ba[2]=0x00;
- ba[3]=0x00;
- ba[4]=0x00;
- ba[5]=0x02;
- ba[6]=0x71;
- ba[7]=0xcb;
- qint64 len;
- QHostAddress adr=QHostAddress("192.168.1.33");
- //len=udpsocket->writeDatagram(str,32,adr,port);
- len=udpsocket->writeDatagram(ba,adr,8000);
- if(len==-1)
- {
- QMessageBox::information(this,tr("error"),tr("writedatagram failed!"));
- return;
- }
- qDebug()<<"yes"<<len;
- }
- void NetworkInformation::processPendingDatagram() //接收信息
- {
- while(receiver->hasPendingDatagrams())
- {
- qDebug()<<"hasPendingDatagrams";
- QByteArray datagram;
- qint64 rlen;
- datagram.resize(receiver->pendingDatagramSize());
- rlen=receiver->readDatagram(datagram.data(),datagram.size());
- if(rlen==-1)
- {
- QMessageBox::information(this,tr("error"),tr("readdatagram failed!"));
- return;
- }
- }
- }
复制代码 |
|