I am trying to send 1/0 to my ARDUINO Board & trying to receive some data from board as a response , I am using QextSerialPort (Qt lib) for this But I am not able to write any data to the board & not able to receive any data also.
qDebug() << "send.size() : " << send.size() << " data = " << send.data() <<" Written = " << port->write(send, send.size()); This printing : send.size() : 1 data = 1 Written = 0 //Means I am writing 0 bytes every time
Is there a problem with my code ??
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();
}
My Arduino code is:
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:
;
}
}
}
solved:
I switched to QSerialPort class in Qt5.5, It did worked greate.
& there is problem in my aurdino code also (copy paste effect)
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;
}
Since you are in event driven mode you also should connect the signal
bytesWritten(qint64 bytes)eg:Then implement a slot:
In event driven mode, I am not entirly sure if
port->write(...)will return the number of bytes that are eventually written since it does this in another thread.... at least it has not responded with-1which is an error. Try this out first.The other thing is QSerialPort works just fine on linux / windows and is easy to use... but I have not tried it on ARDUINO, what OS are you running?