I am working on a project where I have to write to an read from a serial port. I have written the following code, but I am getting the message "can't open the port" in my else statement.
When I use hercules, I can open the "COM1" port. But I don't know why can't I open this port via my QT program.
code:
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtSerialPort/QSerialPort>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
QSerialPort *serial;
private slots:
void on_pushButton_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp:
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QtSerialPort/QSerialPort>
#include <QSerialPortInfo>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
serial = new QSerialPort(this);
serial->setPortName("COM1");
for(const auto &serialPortInfo : QSerialPortInfo::availablePorts())
{
qDebug() << "find serial port: " << serialPortInfo.portName() ;
}
serial->open(QIODevice::ReadWrite);
if(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(1)
{
serial->write("ok");
qDebug() << " Reading " << serial->read(1);
serial->flush();
}
}
else
{
qDebug() << "can't open the port";
}
}
Widget::~Widget()
{
delete ui;
serial->close();
}
void Widget::on_pushButton_clicked()
{
qDebug() << "salam";
}
main.cpp:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
You do open two times, I guess second one should be isOpen
Related
So I am learning Qt GUI for C++ (Linux Mint 21, Qt Creator 5). I am trying to write a simple program that will open a box with 3 fields for the user to enter values: a1, a2, and a3. Then there are two buttons: OK and Quit. See screenshot below for GUI box. Then when the user hits "Quit" the GUI and entire C++ code should terminate. I got this part working. When the user hits "OK", then the Qt GUI should save these values into variables, quit the GUI entirely, and pass the variables back to the main c++ code for use in ....this is where I am stuck:
Qt GUI Input Box
I want Qt GUI to completely shutdown and pass the control back to main c++ with the values/variables that the user entered. This is where I am stuck. Code is below:
main.cpp:
#include "mainwindow.h"
#include <QtCore>
#include <QApplication>
#include <QString>
int main(int argc, char *argv[])
{
//=========================================================
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
// Qt GUI stops, main C++ code continues....
//=========================================================
//float a1_temp = MainWindow::on_pushButton_clicked();
//float a2_temp = MainWindow::on_pushButton_clicked();
//float a3_temp = MainWindow::on_pushButton_clicked();
//std::cout << "Qt passed back into main: " << a1_temp << std::endl;
//std::cout << "Qt passed back into main: " << a2_temp << std::endl;
//std::cout << "Qt passed back into main: " << a3_temp << std::endl;
}
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_2_clicked() // When QUIT is pressed, exit/terminate the whole program
{
QApplication::quit();
}
void MainWindow::on_pushButton_clicked() // When OK is pressed, save values and return to main C++
{
float a1 = ui->lineEdit->text().toFloat();
float a2 = ui->lineEdit_2->text().toFloat();
float a3 = ui->lineEdit_3->text().toFloat();
// print values to verify of variables correctly saved the values
std::cout << a1 << std::endl;
std::cout << a2 << std::endl;
std::cout << a3 << std::endl;
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_2_clicked();
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Looks like your only problem is that you're calling return from main() when exec() returns:
return a.exec();
You could replace that with this:
int retVal = a.exec();
[.... Main C++ code continues here ....]
float a1 = w.ui->lineEdit->text().toFloat();
[...]
return retVal; // only at the end of main()
... and get the behavior you want.
I am using QAudioInput to record audio from the system default input device.
I get a callback from QIODevice::readyRead that bytes are ready for read, but reading the bytes return an array of \0 's, equal to the size of the audioInput->bytesReady().
What am I doing wrong here and I cannot get the actual bytes recorded from the device?
This is the complete code:
file main.cpp
#include "mainwindow.h"
#include "audiorecorder.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
AudioRecorder recorder;
recorder.startRecording();
return a.exec();
}
file audiorecorder.h
#ifndef AUDIORECORDER_H
#define AUDIORECORDER_H
#include <QObject>
#include <QAudioInput>
class AudioRecorder : public QObject
{
Q_OBJECT
public:
explicit AudioRecorder(QObject *parent = nullptr);
void startRecording();
private:
QAudioInput *audioInput;
QAudioDeviceInfo deviceInfo;
QAudioFormat format;
QIODevice *iodevice;
QAudioDeviceInfo devInfo;
void onReadyRead();
signals:
};
#endif // AUDIORECORDER_H
file audiorecorder.cpp
#include "audiorecorder.h"
#include <iostream>
AudioRecorder::AudioRecorder(QObject *parent) : QObject(parent)
{
}
void AudioRecorder::startRecording()
{
deviceInfo = deviceInfo.defaultInputDevice();
std::cout << deviceInfo.deviceName().toStdString() << std::endl;
format = deviceInfo.preferredFormat();
format.setSampleRate(44100);
format.setChannelCount(1);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
if (!deviceInfo.isFormatSupported(format)) {
std::cout << "raw audio format not supported by backend, finding closest alternative." << std::endl;
format = deviceInfo.nearestFormat(format);
}
audioInput = new QAudioInput(deviceInfo, format, this);
iodevice = audioInput->start();
QObject::connect(AudioRecorder::iodevice, &QIODevice::readyRead, this, &AudioRecorder::onReadyRead);
}
void AudioRecorder::onReadyRead()
{
QByteArray buffer;
auto bytesReady = audioInput->bytesReady();
std::cout << "bytesReady: " << bytesReady << std::endl;
buffer.resize(bytesReady);
//buffer.fill(0);
auto ret = iodevice->read(buffer.data(), bytesReady);
std::cout << "bytes read: " << ret << std::endl;
}
I uploaded the complete project code here: https://www.sendspace.com/file/99dlei
I'm new to Qt framework. This is my first C++ implementation in real world applications. I was facing problem in preparing this bluetooth based application. I went through Qt documentation too, but it didn't work. Code is :
CLASS HEADER
#ifndef MAINCLASS_H
#define MAINCLASS_H
#include <QObject>
#include <QBluetoothServiceDiscoveryAgent>
#include <QBluetoothServiceInfo>
#include <QBluetoothLocalDevice>
class MainClass : public QObject
{
Q_OBJECT
public:
explicit MainClass(QObject *parent = 0);
~MainClass();
void startDiscovery(void);
signals:
public slots:
void onDiscovery(const QBluetoothServiceInfo &serviceInfo);
private:
QBluetoothServiceDiscoveryAgent *discoveryAgent;
QBluetoothLocalDevice *bluetoothDevice;
};
#endif // MAINCLASS_H
// MEMBER DEFINITIONS
#include "mainclass.h"
#include <QDebug>
MainClass::MainClass(QObject *parent) : QObject(parent)
{
bluetoothDevice = new QBluetoothLocalDevice();
QBluetoothAddress bluetoothAddress = bluetoothDevice->address();
discoveryAgent = new QBluetoothServiceDiscoveryAgent(bluetoothAddress);
connect(discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
this, SLOT(onDiscovery(QBluetoothServiceInfo)));
discoveryAgent->setUuidFilter(QBluetoothUuid(QBluetoothUuid::ObexObjectPush));
discoveryAgent->start();
if(!discoveryAgent->isActive())
qDebug()<<"Not active";
if(discoveryAgent->error() != QBluetoothServiceDiscoveryAgent::NoError)
qDebug()<<discoveryAgent->errorString();
}
MainClass::~MainClass()
{
delete(discoveryAgent);
}
void MainClass::onDiscovery(const QBluetoothServiceInfo &serviceInfo)
{
qDebug() << "Discovered service on"
<< serviceInfo.device().name() << serviceInfo.device().address().toString();
qDebug() << "\tService name:" << serviceInfo.serviceName();
qDebug() << "\tDescription:"
<< serviceInfo.attribute(QBluetoothServiceInfo::ServiceDescription).toString();
qDebug() << "\tProvider:"
<< serviceInfo.attribute(QBluetoothServiceInfo::ServiceProvider).toString();
qDebug() << "\tL2CAP protocol service multiplexer:"
<< serviceInfo.protocolServiceMultiplexer();
qDebug() << "\tRFCOMM server channel:" << serviceInfo.serverChannel();
}
Main Function
#include "mainclass.h"
int main()
{
MainClass obj;
}
This piece of code wasn't showing lists of surrounding bluetooth devices. Any suggestions?
I am trying write a QT program to receive UDP packet.I am trying to receive from Packet Sender software
This is my code
socket = new QUdpSocket(this);
bool result = socket->bind(QHostAddress("150.100.50.88"),45454);
qDebug() << result;
if(result)
{
qDebug << "PASS";
}
else
{
qDebug << "FAIL";
}
processPendingDatagrams();
connect(socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()),Qt::QueuedConnection);
void UDP::processPendingDatagrams()
{
QHostAddress sender;
u_int16_t port;
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
qDebug() <<"Message From :: " << sender.toString();
qDebug() <<"Port From :: "<< port;
qDebug() <<"Message :: " << datagram;
} //! [2]
}
UDP.h:
class UDP : public QObject
{
Q_OBJECT public:
explicit UDP(QObject *parent = 0);
signals:
public slots:
void SendDatagram(u_int8_t,u_int8_t,u_int8_t);
private slots:
void processPendingDatagrams();
private :
QUdpSocket *socket;
};
The readReady signal and corresponding slot are not working . I can see the packets in Wireshark.
If a I try receive the packets in continuously in a loop I am able see the datagrams.What can be the reason for signals and Slots for not working.Sending operation is working well.
This code work for me. Try it please.
.pro:
#-------------------------------------------------
#
# Project created by QtCreator 2017-03-10T11:44:19
#
#-------------------------------------------------
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = test
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
mainwindow.cpp:
#include "mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
socket = new QUdpSocket(this);
bool result = socket->bind(QHostAddress::AnyIPv4, 45454);
qDebug() << result;
if(result)
{
qDebug() << "PASS";
}
else
{
qDebug() << "FAIL";
}
processPendingDatagrams();
connect(socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()),Qt::QueuedConnection);
}
MainWindow::~MainWindow()
{
}
void MainWindow::processPendingDatagrams()
{
qDebug() << "in !";
QHostAddress sender;
u_int16_t port;
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
qDebug() <<"Message From :: " << sender.toString();
qDebug() <<"Port From :: "<< port;
qDebug() <<"Message :: " << datagram;
}
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QUdpSocket>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void processPendingDatagrams();
private:
QUdpSocket *socket = nullptr;
};
#endif // MAINWINDOW_H
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
tried with netcat with the command:
netcat -u 127.0.0.1 45454
once you ran the command, just type anything and press return.
In my case this did not work, because there was always a "dummy" datagram left somewhere in memory, even if hasPendingDatagrams() returned false, I had to call readDatagram one more time to let my program receive newer datagrams. My answer is here anyways https://stackoverflow.com/a/74056997/11414500
Good luck!
#Gabriel answer did't work for me because it's using the old connect syntax. I updated it to the following (Qt 6):
// udpclient.h
#ifndef UDPCLIENT_H
#define UDPCLIENT_H
#include <QObject>
#include <QUdpSocket>
class UdpClient: public QObject
{
Q_OBJECT
public:
explicit UdpClient(QObject *parent);
void initSocket();
private:
void processPendingDatagrams();
QUdpSocket *socket=nullptr;
};
#endif // UDPCLIENT_H
// udpclient.cpp
#include "udpclient.h"
UdpClient::UdpClient(QObject *parent) : QObject(parent) {
}
void UdpClient::initSocket()
{
socket = new QUdpSocket(this);
bool result = socket->bind(QHostAddress::AnyIPv4, 4999);
if(result)
{
qDebug() << "Socket PASS";
}
else
{
qDebug() << "Socket FAIL";
}
processPendingDatagrams();
connect(socket, &QUdpSocket::readyRead, this, &UdpClient::processPendingDatagrams);
}
void UdpClient::processPendingDatagrams()
{
qDebug() << "in !";
QHostAddress sender;
quint16 port;
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
qDebug() <<"Message From :: " << sender.toString();
qDebug() <<"Port From :: "<< port;
qDebug() <<"Message :: " << datagram;
}
}
It can be used in a function or main() as:
auto udpClient = new UdpClient(0);
udpClient->initSocket();
I wrote a client server program in Qt that client send some message to server but during compile the "startserver" function can't run and i get the following error:could not start server. Could you please say where is problem?
"main.cpp"
#include <QApplication>
#include "mythread.h"
#include "myserver.h"
#include "QtSql/QtSql"
#include "QMessageBox"
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
myserver server;
server.startserver();
MainWindow w;
w.show();
return a.exec();
}
"myserver.h"
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QMainWindow>
#include "QTcpServer"
#include "mythread.h"
#include "QTcpSocket"
namespace Ui
{
class myserver;
}
class myserver : public QObject
{
Q_OBJECT
public:
server(QObject * parent = 0);
explicit myserver(QObject *parent = 0);
void startserver();
public slots:
void acceptConnection();
protected:
void incomingConnections(qintptr socketDescriptor);
QTcpSocket* c_client;
QTcpServer s_server;
private:
qintptr socketDescriptor;
};
#endif
"myserver.cpp"
#include "myserver.h"
#include "mythread.h"
myserver::myserver(QObject *parent) :
QObject(parent)
{
}
void myserver::startserver()
{
int port = 1234;
if(s_server.listen(QHostAddress::Any, port))
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "Listening to port " ;
}
}
void myserver::incomingConnections(qintptr socketDescriptor)
{
mythread *thread = new mythread(socketDescriptor,this);
qDebug() << socketDescriptor << " Connecting...";
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
void myserver::acceptConnection()
{
c_client = s_server.nextPendingConnection();
connect(c_client,SIGNAL(readyRead()),this, SLOT(startRead()));
qDebug() << " Connecting...";
}
if(s_server.listen(QHostAddress::Any, port))
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "Listening to port " ;
}
reads as "if the server CAN listen to any address on given port, print could not start server"
just change it to if (!s_server.listen(...)) and the missleading message should be gone