Error in QT c++ program, it shows arduino is not found - c++

I am learning QT, and following a video tutorial for practice. the code is given below, in if statement i have written if arduino is not found, print, arduino is not found. But it always gives this error, there is some problem in my program but I am unable to diagnose it, help me.
this is the program
#include "dialog.h"
#include "ui_dialog.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QtWidgets>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
arduino_is_available = false;
arduino_port_name = "";
arduino = new QSerialPort;
/*qDebug() << "Number of available ports: " <<QSerialPortInfo::availablePorts().length();
foreach(const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()){
qDebug() <<"Has vendorID: " << serialPortInfo.vendorIdentifier();
if(serialPortInfo.hasVendorIdentifier()){
qDebug() <<"Vendor ID:" <<serialPortInfo.vendorIdentifier();
}
qDebug() <<"Has product ID:" <<serialPortInfo.hasProductIdentifier();
if(serialPortInfo.hasProductIdentifier()){
qDebug() <<"Product ID:" <<serialPortInfo.productIdentifier();
}
}
*/
foreach(const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()){
if(serialPortInfo.hasVendorIdentifier() && serialPortInfo.hasProductIdentifier()){
if(serialPortInfo.hasVendorIdentifier() == arduino_uno_vendor_id){
if(serialPortInfo.hasProductIdentifier() == arduino_uno_product_id){
arduino_port_name = serialPortInfo.portName();
arduino_is_available = true;
}
}
}
if(arduino_is_available){
//open and configure the serialport
arduino->setPortName(arduino_port_name);
arduino->open(QSerialPort::WriteOnly);
arduino->setBaudRate(QSerialPort::Baud9600);
arduino->setDataBits(QSerialPort::Data8);
arduino->setParity(QSerialPort::NoParity);
arduino->setStopBits(QSerialPort::OneStop);
arduino->setFlowControl(QSerialPort::NoFlowControl);
}else{
//give error message if not available
QMessageBox::warning(this, "port error", "couldn't find the arduino!");
}
}
}
Dialog::~Dialog()
{
if(arduino->isOpen()){
arduino->close();
}
delete ui;
}
void Dialog::on_redslider_valueChanged(int value)
{
ui->redvalue->setText(QString("<span style=\" font-size:18pt; font-weight:600;\">%1</span>").arg(value));
Dialog::updateRGB(QString("r%1").arg(value));
qDebug() <<value;
}
void Dialog::on_greenslider_valueChanged(int value)
{
ui->greenvalue->setText(QString("<span style=\" font-size:18pt; font-weight:600;\">%1</span>").arg(value));
Dialog::updateRGB(QString("g%1").arg(value));
qDebug() <<value;
}
void Dialog::on_blueslider_valueChanged(int value)
{
ui->bluevalue->setText(QString("<span style=\" font-size:18pt; font-weight:600;\">%1</span>").arg(value));
Dialog::updateRGB(QString("b%1").arg(value));
qDebug() <<value;
}
void Dialog::updateRGB(QString command)
{
if(arduino->isWritable()){
arduino->write(command.toStdString().c_str());
} else{
qDebug() << "Couldn't write to serial";
}
}

You are comparing a boolean to an integer (or some other type)) in the two tests for vendor id and product id.
serialPortInfo.hasVendorIdentifier() returns bool and you do an equality test to some unknown value arduino_uno_vendor_id that certainly cannot be bool. Probably string.
Same for Product ID.
'Twill always be FALSE

Related

Why qDebug() returns "failed" when I try to connected the PostgreSql Database

I am currently working with QT creator and PostgreSQL.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QDebug>
#include <QtSql>
static QSqlDatabase DB = QSqlDatabase::addDatabase("QPSQL");
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
DB.setHostName("db.fe.up.pt");
DB.setDatabaseName("****");
DB.setUserName("*****");
DB.setPassword("****");
if (DB.open())
{
qDebug() << "Connected!";
QSqlQuery query2;
if(query2.exec("SET search_path TO INFI")){
qDebug() << "Schema OK";
}
}
else
{
qDebug() << "Failed to connect.";
//ui->LogOk->setText("You not are connected to VPN!! ");
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_orders_clicked()
{
QSqlQuery query;
QSqlQueryModel *model = new QSqlQueryModel;
if(query.exec("SELECT * from INFI.orders")){
qDebug()<< "TOP";
}
else{
qDebug()<< "Failed";
}
model->setQuery(std::move(query));
}
I am trying to run this piece of code, and when I execute my app my connection with the DB are ok. But I dont know why I cant execute this query when I press the button, my qDebug always return me "failed", what I am doing wrong?? This is the tables and the schema I am working. I want to select all the items of my orders table, this table is inside INFI schema.

Problem with connecting to camera in Qt CPP

I'm running a simple program in Qt creator to connecting to a camera. When I run the program, the following issue is reported:
Graph failed to connect filters -2147467259
[0x0] Failed to connect graph (The operation completed successfully.)
Can somebody tell me what the problem is?! Any solution would be appreciated.
Thanks
I followed the link you mentioned. But i didn't understand the exact way to solve the problem.
Here is the code i used to connect to a camera:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connected = false;
camera = new QCamera();
qDebug() << "Number of cameras found:" << QCameraInfo::availableCameras().count();
QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
foreach (const QCameraInfo &cameraInfo, cameras)
{
qDebug() << "Camera info:" << cameraInfo.deviceName() << cameraInfo.description() << cameraInfo.position();
ui->comboBox->addItem(cameraInfo.description());
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
if(!connected)
connectCamera();
else {
camera->stop();
viewfinder->deleteLater();
ui->pushButton->setText("Connect");
connected = false;
}
}
void MainWindow::connectCamera()
{
QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
foreach (const QCameraInfo &cameraInfo, cameras)
{
qDebug() << cameraInfo.description() << ui->comboBox->currentText();
if(cameraInfo.description()==ui->comboBox->currentText()) {
camera = new QCamera(cameraInfo, this);
viewfinder = new QCameraViewfinder(this);
camera->setViewfinder(viewfinder);
ui->horizontalLayout_2->addWidget(viewfinder);
connected = true;
ui->pushButton->setText("Disconnect");
camera->start();
return;
}
}
}

How to receive proper UDP packet in QT?

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();

Qt Bluetooth unable to connect socket to device

I'm trying to establish bluetooth connection between laptop and Samsung Smart Touch Remote. My issue is that I can't connect socket to device(socket is always in "Host lookup state"):
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Create a discovery agent and connect to its signals
QBluetoothDeviceDiscoveryAgent *discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&)),
this, SLOT(deviceDiscovered(const QBluetoothDeviceInfo&)));
// Start a discovery
discoveryAgent->start();
}
void MainWindow::deviceDiscovered(const QBluetoothDeviceInfo &device)
{
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
socket->connectToService(QBluetoothAddress(device.address()),
QBluetoothUuid(QBluetoothUuid::SerialPort));
connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)),
this, SLOT(socketError(QBluetoothSocket::SocketError)));
connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(socketRead()));
connect(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState)), this, SLOT(socketStateChanged()));
}
void MainWindow::socketRead()
{
QByteArray receivedData = socket->readAll();
QMessageBox msg;
msg.setText(QString(receivedData));
msg.exec();
}
void MainWindow::socketConnected()
{
qDebug() << "Socket connected";
qDebug() << "Local: "
<< socket->localName()
<< socket->localAddress().toString()
<< socket->localPort();
qDebug() << "Peer: "
<< socket->peerName()
<< socket->peerAddress().toString()
<< socket->peerPort();
}
void MainWindow::socketDisconnected()
{
qDebug() << "Socket disconnected";
socket->deleteLater();
}
void MainWindow::socketError(QBluetoothSocket::SocketError error)
{
qDebug() << "Socket error: " << error;
}
void MainWindow::socketStateChanged()
{
int socketState = socket->state();
QMessageBox msg;
if(socketState == QAbstractSocket::UnconnectedState)
{
msg.setText("unconnected");
}
else if(socketState == QAbstractSocket::HostLookupState)
{
msg.setText("host lookup");
}
else if(socketState == QAbstractSocket::ConnectingState )
{
msg.setText("connecting");
}
else if(socketState == QAbstractSocket::ConnectedState)
{
msg.setText("connected");
}
else if(socketState == QAbstractSocket::BoundState)
{
msg.setText("bound");
}
else if(socketState == QAbstractSocket::ClosingState)
{
msg.setText("closing");
}
else if(socketState == QAbstractSocket::ListeningState)
{
msg.setText("listening");
}
msg.exec();
}
Can someone please tell me what I'm doing wrong?
Have you tried to open a COM port on your Laptop which is connected to the Laptop's bluetooth module?
You can go to Bluetooth settings -> Com Ports -> Add a new com port. Then open this Port using hypertermical or Teraterm. Now try to connect from your Android phone...
Hope this works!
I had the samme issue. The fix was to use a port 1 in argument to socket->connectToService(addr, 1).
This tells SDP to use connection as channel via SDP.

What's the best way of implementation QProcess, which reading stdout and stderr in "real time"?

This questions is often asked. Many recommend use readyReadStandardOutput for this purpose
What's the best way of implementation QProcess, which reading stdout and stderr in "real time"? I want to add messages in DisplayEdit. What i must change in my code (you can see it below )? May be use QThread for writing in DisplayEdit?
I've already the following code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QDebug>
#include <QCloseEvent>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
process = new QProcess(this);
connect(process, SIGNAL(readyReadStandardOutput()),SLOT(slotDataOnStdout()));
connect(process, SIGNAL(readyReadStandardError()), SLOT(slotProcessError()));
connect(process, SIGNAL(error(QProcess::ProcessError)),SLOT(slotProcessError()));
connect(process, SIGNAL(started()),SLOT(slotProcessStart()));
connect(process, SIGNAL(finished(int)),SLOT(slotProcessFinish(int)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_EnterButton_clicked()
{
QStringList args = ui->ArgsEdit->text().split(" ");
QString cmd = ui->CommandEdit->text();
process->start(cmd, args);
}
void MainWindow::slotDataOnStdout()
{
qDebug() << "slotDataOnStdout";
ui->DisplayEdit->append(process->readAllStandardOutput() + '\n');
}
void MainWindow::slotStderr()
{
qDebug() << "std error";
}
void MainWindow::slotProcessError()
{
qDebug() << "error";
}
void MainWindow::slotProcessStart()
{
qDebug() << "start";
}
void MainWindow::slotProcessFinish(int exitCode)
{
qDebug() << "finish: " << exitCode;
QString str = process->readAllStandardOutput();
qDebug() << str;
}
And i want to execude the binary file of countdown timer. The code of my timer (i have took it from clock reference:
#include <stdio.h>
#include <time.h>
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
int main ()
{
int n;
printf ("Starting countdown...\n");
for (n=10; n>0; n--)
{
printf ("%d\n",n);
wait (1);
}
printf ("FIRE!!!\n");
return 0;
}
Looks mostly right. You did forgot to clean up the process, or think about what to do when the process isn't finished yet.
As for the timer, use the QTimer::timeout signal.