我正试图将1/0发送到我的ARDUINO板&尝试从板接收一些数据作为响应,为此我使用了QextSerialPort (Qt ),但是我无法将任何数据写入板&也无法接收任何数据。
QextSerialPort
qDebug() <<“send.size():”<< send.size() <<“data =”<< send.data() <<“<< =”< time (send,send.size());此打印: send.size():1 data =1书面=0//意味着每次写入0字节
我的密码有问题吗?
void MainWindow::ledOnOff(bool on)
{
if(port == 0)
{
port = new QextSerialPort("COM6", QextSerialPort::EventDriven); //QextSerialPort* port is class member
port->setBaudRate(BAUD9600);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_2);
connect(port, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
if(port->open(QIODevice::ReadWrite) == true)
{
qDebug() << "Port open success";
}
else
{
qDebug() << "Port open success";
}
}
else
{
port->close();
}
quint8 writeByte = 0;
if(on)
{
writeByte = 1;
}
if(port->isOpen() || port->open(QIODevice::ReadWrite) == true)
{
QByteArray send;
send.resize(writeByte );
send = QByteArray::number(writeByte);
port->flush();
qDebug() << "send.size() : " << send.size() << " data = " << send.data()
<<" Writtend = " << port->write(send, send.size());
}
else
{
qDebug() << "device failed to open:" << port->errorString();
}
}
void MainWindow::onReadyRead()
{
QByteArray bytes;
quint8 a = port->bytesAvailable();
bytes.resize(a);
port->read(bytes.data(), bytes.size());
qDebug() << bytes.constData();
}我的Arduino代码是:
uint8_t chosen = 0;
void setup()
{
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
switch(Serial.read())
{
case '1':
chosen = 1;
break;
case '2':
chosen = 2;
break;
default:
Serial.println("Bad Choice.");
chosen = 0;
}
Serial.println(chosen, DEC);
switch(chosen)
{
case 1:
digitalWrite(13, HIGH);
break;
case 2:
digitalWrite(13, LOW);
break;
default:
;
}
}
}解决:
在Qt5.5中,我转到了QSerialPort类,它确实工作得很好。
&我的奥尔迪诺代码也有问题(复制粘贴效果)
switch(Serial.read())
{
case 1: //It should be 1 not '1'
chosen = 1;
break;
case 2: //It should be 2 not '2'
chosen = 2;
break;
default:
Serial.println("Bad Choice.");
chosen = 0;
}发布于 2016-04-25 07:57:39
由于您处于事件驱动模式,您还应该连接信号bytesWritten(qint64 bytes) (例如:
connect(port, SIGNAL(bytesWritten()), this, SLOT(onBytesWritten()));然后实现一个插槽:
onBytesWritten(qint64 bytes)
{
qDebug() << "Bytes written " << bytes << std::endl;
}在事件驱动模式下,我不完全确定port->write(...)是否会返回最终写入的字节数,因为它在另一个线程中这样做.至少它没有用-1作出响应,这是一个错误。先试试这个。
另一件事是QSerialPort在linux / windows上工作得很好,而且很容易使用.但是我还没有在ARDUINO上试过,你在运行什么操作系统?
https://stackoverflow.com/questions/36826569
复制相似问题