我試圖發送1/0給我的ARDUINO板&試圖從板上接收一些數據作爲響應,我正在使用QextSerialPort(Qt lib)但我不是能夠將任何數據寫入板&也無法接收任何數據。使用QextSerialPort寫入數據總是寫入0字節
qDebug()< < 「send.size():」 < < send.size()< < 「數據=」 < < send.data()< < 「書面=」 < < 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:
;
}
}
}
解決:
我切換到QSerialPort類Qt5.5,它沒有工作馬麗娟。
&有問題,我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;
}
謝謝但我沒有嘗試這個,會試一試。相反,我在Qt5中切換到QSerialPort類,它爲我工作。 – NDestiny