Reputation: 1976
I am writing a C++ program using Qt that reads data from the serial line. The "producer" of the data is an Arduino UNO board.
The Arduino code is very simple. Currently, it just generates a random number and sends it over the serial line. Here is the code:
long randNumber;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
randNumber = random(300);
Serial.write(randNumber);
delay(10);
}
I have used the Arduino's "serial monitor" to verify that data is coming across the serial line.
On the Qt side of things, I have a worker thread that is supposed to read the serial data and update a plot on the UI accordingly. The worker thread is definitely running, and this code is getting executed (I've checked). I only have one device in my "port list" that shows up, and it is the Arduino, so currently I connect right to it. Here is the code:
void doWork ()
{
QList<QSerialPortInfo> port_list = QSerialPortInfo::availablePorts();
QSerialPort serialPort;
serialPort.setPort(port_list[0]);
serialPort.setBaudRate(QSerialPort::Baud9600);
if (!serialPort.open(QIODevice::ReadWrite))
{
cout << QObject::tr("Failed to open port COM3, error: %1").arg(serialPort.errorString()).toStdString() << endl;
}
while(!abort_thread)
{
int bytes_available = serialPort.bytesAvailable();
if (bytes_available >= 4)
{
QByteArray byte_array = serialPort.read(4);
int data = byte_array.toInt();
emit signalDataReady(data);
}
}
serialPort.close();
}
Unfortunately, there are never any bytes available. It opens the serial port successfully, but no bytes come through. What am I doing wrong here? Any ideas? Thanks!
Upvotes: 3
Views: 1438
Reputation: 527
You are forgot to add waitForReadyRead() before bytesAvailable().
Upvotes: 1
Reputation: 15151
From https://www.arduino.cc/en/Serial/Write:
Serial.write(val)
val: a value to send as a single byte
If you write a number Arduino only sends one byte, if you want to send a long then you must decompose it as an array and send the array (or get a pointer to the long's address and send each one of the bytes).
As your Qt code expects to read four bytes the if is never executed.
Upvotes: 0