I am trying to rig up some basic serial communications in QT
I am getting the port COM19 from QSerialPortInfo, and I speaking successfully to the port via Arduino. However, I cannot get anything back via QT.
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QTextStream>
#include <QFile>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
qDebug() << "Name :" << info.portName();
qDebug() << "Description :" << info.description();
qDebug() << "Manufactuer :" << info.manufacturer();
QSerialPort serial;
serial.setPort(info);
if(serial.open(QIODevice::ReadWrite))
qDebug() << serial.errorString();
serial.write("M114 \n");
qDebug() << serial.readAll();
serial.close();
// Now we need to send and receive commands
serial.setPortName("COM19");
serial.setBaudRate(QSerialPort::Baud57600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
if(serial.open(QIODevice::ReadWrite)){
qDebug() << "opened";
}else{
qDebug() << "Not opened";
}
qDebug() << serial.errorString();
serial.write("M114 \n");
qDebug() << serial.readAll();
serial.close();
}
MainWindow w;
w.show();
return a.exec();
}
As you can see, I am trying a simple connection along the lines of the documentation, and one where I write out all the baud rate information. They throw two different errors.
Like I said, I am connecting via arduino to this same port and having success. Any ideas what's wrong?
Name : "COM19"
Description : "USB Serial (Communication Class, Abstract Control Model)"
Manufactuer : "PJRC.COM, LLC."
"Unknown error"
""
opened
"The handle is invalid."
""
Any ideas for what I am doing wrong?
My idea is to send commands to the device, and read them back to the console.
the code looks a bit confuse. You open all port available and then you try to do something wrong.
NOTE: You use a GUI application like a shell application. It is wrong.
Try:
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QTextStream>
#include <QFile>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSerialPort serial;
serial.setPortName("COM19");
if(serial.open(QIODevice::ReadWrite)){
//Now the serial port is open try to set configuration
if(!serial.setBaudRate(QSerialPort::Baud57600))
qDebug()<<serial.errorString();
if(!serial.setDataBits(QSerialPort::Data8))
qDebug()<<serial.errorString();
if(!serial.setParity(QSerialPort::NoParity))
qDebug()<<serial.errorString();
if(!serial.setStopBits(QSerialPort::OneStop))
qDebug()<<serial.errorString();
if(!serial.setFlowControl(QSerialPort::NoFlowControl))
qDebug()<<serial.errorString();
//If any error was returned the serial il corrctly configured
serial.write("M114 \n");
//the serial must remain opened
if(serial.waitForReadyRead(100)){
//Data was returned
qDebug()<<"Response: "<<serial.readAll();
}else{
//No data
qDebug()<<"Time out";
}
//I have finish alla operation
serial.close();
}else{
qDebug()<<"Serial COM19 not opened. Error: "<<serial.errorString();
}
MainWindow w;
w.show();
return a.exec();
}
Starting with the tenth port, his name will be \\.\COM10
You can reassign the port to a different number in Device Manager
Related
My program alerts the user when something has happened. To get his attention, a alert sound plays. It stops when the user enter something to confirm receipt.
But the QTextStream input blocks the sound !
When I remove it, the sound plays perfectly.
Besides, the "alert" QSound object doesn't work. The only way to play is to use the static function QSound::play("file.wav"). But it can't be stopped.
Here is my code :
#include <QCoreApplication>
#include <QSound>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
/*
QSound alert("../SoundAlerte/alert.wav");
alert.setLoops(QSound::Infinite);
alert.play();
*/
QSound::play("../SoundAlerte/alert.wav");
qDebug() << "ALERT";
qDebug() << "Enter Something to confirm receipt" ;
QTextStream s(stdin);
QString value = s.readLine();
qDebug() << "Received !";
//alert.stop();
qDebug() << "Sound stopped";
return a.exec();
}
It seems like it can't play a sound and wait for input at the same time !
Do you have have an idea on how to proceed ?
Thanks
QSound::play is asynchron, but
QString value = s.readLine();
contains a do-while and will block the audio file. See scan function called by readLine()
A working example would be QtConcurrent, but you can't stop the audio file, so you might want to switch to a real QThread approach.
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFuture<void> future = QtConcurrent::run([]() {
QSoundEffect effect;
QEventLoop loop;
effect.setSource(QUrl::fromLocalFile("C:\\piano2.wav"));
effect.setVolume(0.25f);
effect.play();
QObject::connect(&effect, &QSoundEffect::playingChanged, [&loop]() { qDebug() << "finished"; loop.exit(); });
loop.exec();
});
QTextStream s(stdin);
QString value = s.readLine();
return a.exec();
}
I've been trying for more than a week to communicate from raspberry pi (QT C++) to Arduino (Arduino IDE c++) through a serial port but i keep failing.
I did some searching on google, read the example... and still i didn't succeeded. Ok so the basic thing is that i need to communicate continuously the serial port sent command from Raspberry pi to Arduino. I tried to keep the code as simple as possible.
Initially I'm sending "J" char from raspberry pi (QT C++) to Arduino (Arduino IDE c++) and waiting on that J, to make the LED blink on Arduino. But it doesn't work.. Even I didn't get any sample for interfacing & communicating & sending data raspberry pi (QT C++) to Arduino (Arduino IDE c++). I don't know what is the problem exactly. Kindly help me to solve the issue.
In monitor, 9600 baudrate
I have attached program what I have tried on both side.
main.cpp
#include <iostream>
#include <QIODevice>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QString>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
QSerialPort serialPort;
serialPort.setBaudRate(QSerialPort::Baud9600);
QSerialPortInfo info("ttyUSB0");
qDebug() << "Name : " << info.portName();
qDebug() << "Description : " << info.description();
qDebug() << "Busy:" << info.isBusy();
QSerialPort serial;
serial.setPortName("ttyUSB0");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
serial.open(QSerialPort::ReadWrite);
cout<<"Readable :"<<serial.isReadable()<<endl;
cout<<"Writable :"<<serial.isWritable()<<endl<<endl;
if (serial.isOpen() && serial.isWritable())
{
qDebug() << "Is open : " << serial.isOpen() << endl;
qDebug() << "Is writable : " << serial.isWritable() << endl;
qDebug() << "Ready..." << endl;
serial.write("J");
QByteArray ba("J\n");
serial.write(ba);
{
QByteArray ba("J");
serial.write(ba);
serial.flush();
qDebug() << "data has been send" << endl;
serial.close();
}
if (serial.bytesToWrite() > 0)
{
serial.flush();
if(serial.waitForBytesWritten(1000))
{
qDebug() << "data has been send" << endl;
}
}
if(serial.flush())
{
qDebug() << "ok" << endl;
}
qDebug() <<"value sent "<< endl;
serial.close();
}
else
{
qDebug() << "An error occured" << endl;
}
return a.exec();
}
Arduino code:
int led = 13, avlb = 0;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
Serial.println("started");
}
void loop()
{
if (Serial.available() > 0)
{
Serial.println("available");
Serial.println(Serial.available());
delay(2000);
digitalWrite(led, HIGH);
delay(5000);
if(Serial.read() == 'J')
{
Serial.println("read");
Serial.println(Serial.read());
delay(2000);
digitalWrite(led, LOW);
delay(1000);
}
}
else
{
Serial.println("not available");
delay(1000);
}
}
Output Displayed:
Raspberry qt creator ide o/p:
Name : "ttyUSB0"
Description : "FT232R USB UART"
Busy: false
Readable :1
Writable :1
Is open : true
Is writable : true
Ready...
data has been send
bool QSerialPort::flush(): device not open
value sent
Arduino Ide Output displayed:
started
not available
not available
not available
not available
not available
not available
not available
not available
not available
I would suggest you to read about how Qt event system works. All Qt IODevice derived classes work asynchronously. You need to use QApplication in order to host its object system. After that, you need to change your code so that it's not blocking io thread of QSerialPort.
I usually use readyRead singal or I use waitForBytesWritten and waitForReadReady combination.You should take a look at the QtSerialPort examples. You'll find there several possible implementations depending on your application needs.
You can try this, it will work fine.
#include <QCoreApplication>
#include <iostream>
#include <QSerialPort>
#include <QDebug>
#include <Windows.h>
#include <QElapsedTimer>
using namespace std;
QSerialPort serial;
QElapsedTimer timer;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
serial.setPortName("ttyUSB0");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
while(!serial.isOpen()) serial.open(QIODevice::ReadWrite);
if (serial.isOpen() && serial.isWritable())
{
qDebug() << "Serial is open";
QByteArray output;
QByteArray input;
while(true)
{
output = "a";
serial.write(output);
serial.flush();
timer.start();
// Sleep(80);
qDebug() << timer.elapsed();
serial.waitForBytesWritten(100);
serial.waitForReadyRead(100);
if(serial.bytesAvailable()>=18)
input = serial.read(18);
qDebug()<<input;
}
}
return a.exec();
}
The answer to your question is in the following code:
QByteArray ba("J");
serial.write(ba);
serial.flush();
qDebug() << "data has been send" << endl;
serial.close();
After you make serial.flush (), you immediately close the port. It is necessary to wait until the data is really sent. For example, using bool QSerialPort :: waitForBytesWritten (int msecs).
****UPDATED: I noticed that I get the segfault only on Windows, on Linux it's fine. On Windows I use QT 5.5 and MinGW32. I still want to know why.
**** Initial Question:
Nothing tricky here, I create a basic Console Application. I have a QNetworkAccessManager sending a Post() request. When I close the console, there is a segfault.
Note that the request is sent and received successfully, my question is only about that segfault.
If no Post() request are sent, no crash on closing the console. There is not much help from the stack.
Stack
0 ntdll!RtlFreeHeap 0x77b5e041
1 ucrtbase!free 0x5e4c5eab
2 LIBEAY32!CRYPTO_free 0x5e5a123e
Main.cpp
#include <QCoreApplication>
#include "CNetworkHandleTest.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CNetworkHandleTest net;
net.start();
return a.exec();
}
CNetworkHandleTest.cpp
#include "CNetworkHandleTest.h"
CNetworkHandleTest::CNetworkHandleTest()
{
m_Manager = new QNetworkAccessManager(this);
// Connect the network manager so we can handle the reply
connect(m_Manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
m_nTotalBytes = 0;
}
CNetworkHandleTest::~CNetworkHandleTest()
{
disconnect();
m_Manager->deleteLater();
}
void CNetworkHandleTest::onFinished(QNetworkReply* reply)
{
// Look at reply error
// Called when all the data is receivedqDebug() << "Error code:" << reply->error();
qDebug() << "Error string:" << reply->errorString();
reply->close();
reply->deleteLater();
}
void CNetworkHandleTest::start()
{
// Configure the URL string and then set the URL
QString sUrl(BASE_URL);
sUrl.append("/console/5555/upload");
m_Url.setUrl(sUrl);
// Make the request object based on our URL
QNetworkRequest request(m_Url);
// Set request header (not sure how or why this works, but it works)
// \todo investigate
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlenconded");
// Make file object associated with our DB file
QFile file("/tx_database.db");
if(!file.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open file";
}
// Read the entire file as a binary blob
QByteArray data(file.readAll());
// Set our request to our request object
// Note: there should probably be a flag so that when start is called it does not do
// any processing in case we are already in the middle of processing a request
m_Request = request;
// Send it
m_Reply = m_Manager->post(m_Request, data);
// Need to connect the signals and slots to the new reply object (manager makes a new
// reply object every post; may need to investigate if memory should be freed when
// done processing a response)
connect(m_Reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(m_Manager, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
this, SLOT(onAuthenticationRequired(QNetworkReply*, QAuthenticator*)));
}
void CNetworkHandleTest::onReadyRead()
{
// Whenever data becomes available, this slot is called. It is called every time data
// is available, not when all the data has been received. It is our responsibility to
// keep track of how much we have received if we want to show progress or whatever
// but we do not need to keep track if we have received all the data. The slot
// OnFinished will be called when the all the data has been received.
qDebug() << "Bytes available:" << m_Reply->bytesAvailable();
m_nTotalBytes += m_Reply->bytesAvailable();
qDebug() << "Bytes thus far:" << m_nTotalBytes;
QByteArray responseData = m_Reply->readAll();
qDebug() << "Response" << responseData;
m_Reply->size();
}
void CNetworkHandleTest::onAuthenticationRequired(QNetworkReply* reply, QAuthenticator* authenticator)
{
}
CNetworkHandleTest.h
#ifndef CNETWORKHANDLETEST_H
#define CNETWORKHANDLETEST_H
// Required packages
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QUrlQuery>
#include <QHostInfo>
#include <QObject>
#include <QUrl>
// Helper packages
#include <QCoreApplication>
#include <QFile>
#include <QDir>
// Our packages
#include <iostream>
#include <fstream>
#include <cstdlib>
#define BASE_URL "localhost:5000"
#define BOUNDARY "123456787654321"
class CNetworkHandleTest : public QObject
{
Q_OBJECT
public:
CNetworkHandleTest();
~CNetworkHandleTest();
void start();
protected Q_SLOTS:
void onFinished(QNetworkReply* reply);
void onReadyRead();
void onAuthenticationRequired(QNetworkReply* reply, QAuthenticator* authenticator);
private:
QNetworkAccessManager* m_Manager;
QNetworkRequest m_Request;
QNetworkReply* m_Reply;
QUrl m_Url;
int m_nTotalBytes;
};
#endif // CNETWORKHANDLETEST_H
When you close the console, your program dies in a most ungraceful manner. You need to write some code to make it graceful instead:
The below is a complete test case:
// https://github.com/KubaO/stackoverflown/tree/master/questions/network-cleanup-40695076
#include <QtNetwork>
#include <windows.h>
extern "C" BOOL WINAPI handler(DWORD)
{
qDebug() << "bye world";
qApp->quit();
return TRUE;
}
int main(int argc, char *argv[])
{
SetConsoleCtrlHandler(&handler, TRUE);
QCoreApplication a(argc, argv);
QNetworkAccessManager mgr;
int totalBytes = 0;
QObject::connect(&mgr, &QNetworkAccessManager::finished, [](QNetworkReply *reply){
qDebug() << "Error string:" << reply->errorString();
});
QNetworkRequest request(QUrl{"http://www.google.com"});
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlenconded");
auto reply = mgr.post(request, QByteArray{"abcdefgh"});
QObject::connect(reply, &QIODevice::readyRead, [&]{
qDebug() << "Bytes available:" << reply->bytesAvailable();
totalBytes += reply->bytesAvailable();
qDebug() << "Bytes thus far:" << totalBytes;
reply->readAll();
});
QObject::connect(reply, &QObject::destroyed, []{
qDebug() << "reply gone";
});
QObject::connect(&mgr, &QObject::destroyed, []{
qDebug() << "manager gone";
});
return a.exec();
}
If you press Ctrl-C or click [x] on the console window, the shutdown is orderly, the output being:
[...]
bye world
reply gone
manager gone
I am trying to transfer data from Arduino to a C++ Qt5.7 and from a Arduino to a C++ Qt5.7 (MinGW) program.
I am able to transfer the data FROM QT TO ARDUINO without any problems.
The Arduino blinks perfectly.
On the other hand, the data transfered FROM THE ARDUINO TO QT isnt always the expected (sends "LED ON" when it should be "LED OFF") and sometimes it doesnt communicate at all!
QT code:
#include <QCoreApplication>
#include <QDebug>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QThread>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSerialPort serial;
serial.setPortName("COM6");
serial.setBaudRate(9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
if(serial.open(QSerialPort::ReadWrite))
{
string c;
QByteArray s;
QByteArray received;
while(true)
{
qDebug("TRUE");
//WRITE
cin >> c;
cout << endl;
s = QByteArray::fromStdString(c);
serial.write(s);
serial.waitForBytesWritten(-1);
//serial.flush();
s = serial.readAll();
serial.waitForReadyRead(-1);
cout << s.toStdString() << endl;
//serial.flush();
}
}
else
{
QString error = serial.errorString();
cout << error.toStdString() << endl;
qDebug("FALSE") ;
}
serial.close();
return a.exec();
}
The ARDUINO CODE:
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
// the loop function runs over and over again forever
void loop() {
delay(1000); // wait for a second
}
void serialEvent()
{
char inChar;
while (Serial.available())
{
// get the new byte:
inChar = (char)Serial.read();
if(inChar == 'a')
{
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
}
else
{
digitalWrite(LED_BUILTIN, LOW); // turn the LED off (LOW is the voltage level)
}
}
delay(500);
if(inChar == 'a')
{
Serial.write("LED ON");
}
else
{
Serial.write("LED OFF");
}
}
Terminal Image of Error:
TERMINAL WITH ERROR image
Please help!
Thank you,
You have no packetization whatsoever: there are no delimiters between individual chunks of data - other than time passing.
On the Arudino side, instead of write, you should use println so that each message is a complete line.
On the Qt side, process complete lines. You're not guaranteed to get a complete response from the serial port after waitForReadyRead. All that you're guaranteed is that at least 1 byte is available to read. That is the source of your problem. Note how you got LE, then sometime later you got D OFF immediately followed by LED ON. You must wait for data until complete line(s) are available.
The following should work on the Qt end of things - also note that you don't need as many includes, and you can use QTextStream instead of iostream, to lower the number of APIs that you use. Finally, you don't need app.exec since you write blocking code.
// https://github.com/KubaO/stackoverflown/tree/master/questions/arduino-read-40246601
#include <QtSerialPort>
#include <cstdio>
int main(int argc, char *argv[])
{
QCoreApplication a{argc, argv};
QTextStream in{stdin};
QTextStream out{stdout};
QSerialPort port;
port.setPortName("COM6");
port.setBaudRate(9600);
port.setDataBits(QSerialPort::Data8);
port.setParity(QSerialPort::NoParity);
port.setStopBits(QSerialPort::OneStop);
port.setFlowControl(QSerialPort::NoFlowControl);
if (!port.open(QSerialPort::ReadWrite)) {
out << "Error opening serial port: " << port.errorString() << endl;
return 1;
}
while(true)
{
out << "> ";
auto cmd = in.readLine().toLatin1();
if (cmd.length() < 1)
continue;
port.write(cmd);
while (!port.canReadLine())
port.waitForReadyRead(-1);
while (port.canReadLine())
out << "< " << port.readLine(); // lines are already terminated
}
}
If you wish, you can also easily turn it into a GUI application, it's only a few lines to do so:
#include <QtSerialPort>
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app{argc, argv};
QWidget ui;
QFormLayout layout{&ui};
QLineEdit portName{"COM6"};
QTextBrowser term;
QLineEdit command;
QPushButton open{"Open"};
layout.addRow("Port", &portName);
layout.addRow(&term);
layout.addRow("Command:", &command);
layout.addRow(&open);
ui.show();
QSerialPort port;
port.setBaudRate(9600);
port.setDataBits(QSerialPort::Data8);
port.setParity(QSerialPort::NoParity);
port.setStopBits(QSerialPort::OneStop);
port.setFlowControl(QSerialPort::NoFlowControl);
QObject::connect(&open, &QPushButton::clicked, &port, [&]{
port.setPortName(portName.text());
if (port.open(QSerialPort::ReadWrite)) return;
term.append(QStringLiteral("* Error opening serial port: %1").arg(port.errorString()));
});
QObject::connect(&command, &QLineEdit::returnPressed, &port, [&]{
term.append(QStringLiteral("> %1").arg(command.text()));
port.write(command.text().toLatin1());
});
QObject::connect(&port, &QIODevice::readyRead, &term, [&]{
if (!port.canReadLine()) return;
while (port.canReadLine())
term.append(QStringLiteral("< %1").arg(QString::fromLatin1(port.readLine())));
});
return app.exec();
}
I think you must use EOL and Carrige return character on QT. Try to replace Serial.write to Serial.println in Arduino code.
I wrote a C++ program in Qt that used dynamic memory allocation, and I made sure to include the free() call at the end. However, when the program reaches the free statement, it crashes. (I know this because the test that I added never printed after the free statements) Anyway, here's the code:
#include <QCoreApplication>
#include <QSerialPort>
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
using namespace std;
int main(int argc, char *argv[])
{
QSerialPort serial0;
//serial.open(serial);
serial0.setBaudRate(QSerialPort::Baud9600);
serial0.setDataBits(QSerialPort::Data8);
serial0.setParity(QSerialPort::NoParity);
serial0.setStopBits(QSerialPort::OneStop);
serial0.setFlowControl(QSerialPort::NoFlowControl);
char *com="com";
int number;
char *comPlusNumber;
comPlusNumber=(char*) malloc(8*sizeof(char));
int j=10000;
while(j>0)
{
number=j;
sprintf(comPlusNumber, "%s%d",com,number);
//printf("%s \n",comPlusNumber);
serial0.setPortName(comPlusNumber);
serial0.open(QIODevice::ReadWrite);
if(serial0.isOpen()==true)
{
printf("YES*****************");
printf("%s \n",comPlusNumber);
}
else
//printf("No %d\n", number);
serial0.close();
j--;
}
free(com);
free(comPlusNumber);
printf("\n\n Test");
//QCoreApplication a(argc, argv);
//return a.exec();
}
I just wanted to make sure that I wasn't creating a memory leak.
Use the framework. You've got the power of Qt!
There are several problems:
The C-style string manipulations are unnecessary and wrong. Use QString:
auto name = QStringLiteral("COM%1").arg(i);
You can't use the serial port without a QCoreApplication instance present.
You shouldn't be testing for the presence of a port by iterating what you think might be valid ports. This is non-portable and unnecessary. Get a list of ports to start with.
Thus:
// https://github.com/KubaO/stackoverflown/tree/master/questions/simple-serial-35181906
#include <QtCore>
#include <QtSerialPort>
int main(int argc, char ** argv) {
QCoreApplication app{argc, argv};
QSerialPort serial;
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
for (auto port : QSerialPortInfo::availablePorts()) {
serial.setPort(port);
serial.open(QIODevice::ReadWrite);
if (serial.isOpen()) {
qDebug() << "port" << port.portName() << "is open";
serial.close();
} else
qDebug() << "port" << port.portName() << "couldn't be opened";
}
}
Here's the output on my machine:
port "cu.serial1" is open
port "cu.usbserial-FTELA9I5" is open
port "cu.usbserial-PX9A3C3B" is open
You can only free what you dynamically allocated. You never dynamically allocated anything for com, so passing it to free is an error. It's equivalent to free("com"); which attempts to free a string constant.