我正在尝试将1/0发送到我的ARDUINO Board&试图从板上接收一些数据作为响应,我正在使用QextSerialPort(Qt lib)但是我无法将任何数据写入电路板和电路板。也无法接收任何数据。
qDebug()<< “send.size():”<< send.size()<< “data =”<< send.data()<<“Written =”<< port-> write(send,send.size()); 此打印:send.size():1 data = 1 Written = 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类,它确实很有效。
&安培;我的aurdino代码也有问题(复制粘贴效果)
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;
}
答案 0 :(得分:0)
由于您处于事件驱动模式,您还应该连接信号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上试过它,你在运行什么操作系统?