我正在尝试将 1/0 发送到我的 ARDUINO 板并尝试从板上接收一些数据作为响应,我为此使用 QextSerialPort (Qt lib) 但我无法将任何数据写入板并且无法也接收任何数据。
qDebug() << "send.size() : " << send.size() << " data = " << send.data() <<" Written = " << port->write(send, send.尺寸()); 此打印: 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;
}