how to calculate speed by gps data in qt mobility? - qt

How I can get my speed, and distance by using gps data in qt?
I have such class, maybe is any standart method?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "quitdiallog.h"
#include <QGeoCoordinate>
#include <QDebug>
#include <QtGui/QMessageBox>
#include <QList>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
setWindowTitle("Мой кОмпаС");
ui->setupUi(this);
startGPS();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::startGPS()
{
// Obtain the location data source if it is not obtained already
if (!locationDataSource)
{
locationDataSource =
QGeoPositionInfoSource::createDefaultSource(this);
if (locationDataSource)
{
// Whenever the location data source signals that the current
// position is updated, the positionUpdated function is called.
QObject::connect(locationDataSource,
SIGNAL(positionUpdated(QGeoPositionInfo)),
this,
SLOT(positionUpdated(QGeoPositionInfo)));
// Start listening for position updates
locationDataSource->setUpdateInterval(200);
locationDataSource->startUpdates();
} else {
// Not able to obtain the location data source
// TODO: Error handling
}
} else {
// Start listening for position updates
locationDataSource->setUpdateInterval(5000);
locationDataSource->startUpdates();
}
}
void MainWindow::positionUpdated(QGeoPositionInfo geoPositionInfo)
{
if (geoPositionInfo.isValid())
{
//locationDataSource->stopUpdates();
QGeoCoordinate geoCoordinate = geoPositionInfo.coordinate();
this->latitude = geoCoordinate.latitude();
this->longitude = geoCoordinate.longitude();
this->altitude=geoCoordinate.altitude();
ui->label->setNum(latitude);
ui->label_2->setNum(longitude);
}
}
void MainWindow::on_pushButton_clicked()
{
ui->label_3->setNum(latitude);
qDebug()<<latitude<<" "<<longitude<<" "<<altitude;
}
void MainWindow::on_pushButton_4_clicked()
{
QuitDiallog *qi=new QuitDiallog;
this->hide();
qi->show();
}
How to get speed???

first i would do source->setPreferredPositioningMethods(QGeoPositionInfoSource::AllPositioningMethods);
The groundspeed can be fetched (theoretically) by geoPositionInfo.attribute(QGeoPositionInfo::GroundSpeed)
But be sure that geoPositionInfo.hasAttribute(QGeoPositionInfo::GroundSpeed) == true
AFAIK there are some issues with groundspeed on several mobile devices.

Related

adjust brightness of led using QSlider and PWM in arduino

i try to control the brightness of the led with QSlider qt ui.i was facing issue which is led not turn on with the slider value. i think it has taken value like 123456... then i tried solution which is add some separator.. parseInt() stops on any not digit character. now i am facing the issue that led is turning on properly with pwm value which is passed from slider but it is turning off automatically after one second.
here is my qt code.
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <string>
#include <QDebug>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QRegularExpression>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
arduino = new QSerialPort(this);
bool is_arduino_avilable = false;
QString portNmae;
databuf = "";
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
if(info.hasProductIdentifier() && info.hasVendorIdentifier())
{
if(info.productIdentifier() == arduino_productId && info.vendorIdentifier() == arduino_vendorId)
{
is_arduino_avilable = true;
portNmae = info.portName();
}
}
}
if(is_arduino_avilable)
{
qDebug() << "Arduino port is found " + portNmae;
arduino->setPortName(portNmae);
arduino->open(QSerialPort::ReadWrite);
arduino->setBaudRate(QSerialPort::Baud9600);
arduino->setDataBits(QSerialPort::Data8);
arduino->setFlowControl(QSerialPort::NoFlowControl);
arduino->setParity(QSerialPort::NoParity);
arduino->setStopBits(QSerialPort::OneStop);
QObject::connect(arduino,SIGNAL(readyRead()),this,SLOT(readSerialdata()));
}
else
{
qDebug() << "Couldn't find the correct port for the arduino.\n";
QMessageBox::information(this,"Serial Port Error","Couldn't open serial port to arduino");
}
}
MainWindow::~MainWindow()
{
if(arduino->isOpen())
{
arduino->close();
}
delete ui;
}
void MainWindow::on_pluse_slider_valueChanged(int value)
{
ui->slider_value->setText(QString("<span style=\"font-size:14pt; font-weight:600;\">%1</span>").arg(value));
qDebug()<<value;
arduino->write(QString("%1").arg(value).toStdString().c_str());
}
and here is my arduino code.
pwm.ino
const int LED = 11;
int rsv_data;
void setup()
{
Serial.begin(9600);
pinMode(LED,OUTPUT);
}
void loop()
{
if(Serial.available())
{
rsv_data = Serial.parseInt();
analogWrite(LED,rsv_data);
}
}
Thank you in advance.
this is ui image
this is debug output image
i have solved this issue using below solution:
i have added the comma(,) as separator befor the value in this below line arduino>write(QString(",%1").arg(val).toStdString().c_str());
this line is in this function void MainWindow::on_pluse_slider_valueChanged(int value)

Signal-slot connection. The process was ended forcefully

Here below are my codes on signal-slot connection demo:
Mainwindow.cpp (it receives signal data from Sender.cpp shown next)
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
status = false; //bool status
check = 0; //int check
sender = new Sender(); //Sender *sender
}
MainWindow::~MainWindow()
{
delete ui;
if(sender!=NULL)
{
delete sender;
}
}
void MainWindow::on_pushButton_clicked() //a pushbutton is created in mainwindow.ui
{
if(sender==NULL)
{
sender = new Sender();
}
if(status==false)
{
qDebug()<<"Button pressed.";
connectionStarter(); //Signal-slot connection is triggered here!
}
}
void MainWindow::connectionStarter()
{
connect(sender,SIGNAL(sendData(int)),this,SLOT(workSlot(int)),Qt::QueuedConnection);
}
void MainWindow::workSlot(int data)
{
this->data = data;
check++;
if(check!=60)
{
qDebug()<<"connected. check="<<check;
qDebug()<<"received data="<<this->data;
}
else
{
check=0;
status = true;
disconnect(sender,SIGNAL(sendData(int)),this,SLOT(workSlot(int)));
qDebug()<<"Disconnected.";
}
}
Sender.cpp (for signal generation, controlled with a QTimer object)
#include "sender.h"
Sender::Sender(QObject *parent) : QObject(parent)
{
data = 0; //data to be updated and transmitted
timer = new QTimer(this); //QTimer *timer
timer->setInterval(1000);
timer->start();
qDebug()<<"Timer started.";
connect(timer,SIGNAL(timeout()),this,SLOT(timerHandler()),Qt::DirectConnection);
}
void Sender::timerHandler()
{
data++; //int data
emit sendData(data);
qDebug()<<"Data emited.";
}
When I run the program, it has unexpectedly finished. The process was ended forcefully. Anyone can help debug my codes? Thanks!

Qt thread makes the Qt Creator no respond for a while

I have a simple project on the demo of QThread using QtCreator4.5 and Qt5.7. In the project, three pushbuttons, threadA, threadB and quit, are created. My intention is to print A and B in the console when the threadA and threadB are clicked respectively, and the application is to be quitted when 'quit' is pressed.
Here is mythread.h:
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QString>
class mythread : public QThread
{
Q_OBJECT
public:
mythread();
void setMessage(const QString &message);
void stop();
protected:
void run();
private:
QString messageStr;
volatile bool stopped;
};
#endif // MYTHREAD_H
The mythread.cpp:
#include "mythread.h"
#include <iostream>
mythread::mythread()
{
stopped = false;
}
void mythread::setMessage(const QString &message)
{
messageStr = message;
}
void mythread::stop()
{
stopped = true;
}
void mythread::run()
{
while(!stopped)
std::cout<<qPrintable(messageStr);
stopped = false;
std::cout<< std::endl;
}
The mainwindow.cpp is:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_threadA_clicked()
{
mythreadA.start();
mythreadA.setMessage("A");
}
void MainWindow::on_threadB_clicked()
{
mythreadB.start();
mythreadB.setMessage("B");
}
void MainWindow::on_quit_clicked()
{
mythreadA.stop();
mythreadB.stop();
MainWindow::close();
}
When I run the project, the printed results are displayed in the Application Output of the QtCreator, not in an external prompt console. Quitting the application makes QtCreator no respond for a while, but finally restore to normal. It seems that the threads are still running when the application is quitted.
I have tested your code and there is nothing wrong with Qt Creator that is not frozen.
However, as your code is written, your threads are probably still running when you quit the application. Moreover, the private member stopped should be protected by a mutex, as volatile won't do this job.
To protect your private variable stopped with a mutex, you can use for example QMutexLocker in the following way :
void MyThread::stop() // called by the GUI Thread
{
const QMutexLocker locker(&m_mutex);
stopped = true;
}
and to read the value of the boolean :
bool MyThread::isStopped // called by run()
{
const QMutexLocker locker(&m_mutex);
return stopped;
}
Finally to ensure that the threads are properly finished when you press the quit button :
void MainWindow::on_quit_clicked()
{
mythreadA.stop();
mythreadB.stop();
myThreadA.wait();
myThreadB.wait();
this->close(); // close the main application
}

Get duration of QMediaPlaylist object

I create a player for audiobooks - when you open a folder with mp3 file, whole list of them is added to playlist and List View. And i have a Label, which suppose to show duration of the whole book. But player->duration returns only a duration of current track, and if i go through the loop and do playlist->next() every step, player->duration returns 0. I know about Phonon and file metadata, but i need to do this without using it.
I am attaching a source code of a working project, you can use. When the player changes the file, the duration is changed and printed out. To loop within files, there is a need to wait till the decoder completes reading the media file. See the code below and the comments.
This is mainwindow.cpp
#include "mainwindow.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
bool done =false;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
player = new QMediaPlayer(this);
playlist = new QMediaPlaylist(player);
playlist->setPlaybackMode(QMediaPlaylist::Sequential);
player->setPlaylist(playlist);
connect(player, &QMediaPlayer::durationChanged, this, &MainWindow::on_durationchanged);
//connect(player,&QMediaPlayer::)
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
playlist->addMedia(QUrl::fromLocalFile("Ar_today.mp3"));
playlist->addMedia(QUrl::fromLocalFile("Ar_sunday.mp3"));
playlist->setCurrentIndex(0); //set the first file
while (done == false) //wait till the duration is read
{
QApplication::processEvents();
}
done = false; playlist->setCurrentIndex(1); //change to the second file
while (done == false) //wait till the duration is read
{
QApplication::processEvents();
} //this way you can loop through files
player->setVolume(80);
player->play();
qDebug() << player->errorString();
}
void MainWindow::on_pushButton_2_clicked()
{
player->stop();
}
void MainWindow::on_durationchanged(qint64 duration)
{
done = true;
qDebug() << "duration = " << player->duration();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QDebug>
extern bool done;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_durationchanged(qint64 duration);
private:
Ui::MainWindow *ui;
QMediaPlayer* player;
QMediaPlaylist* playlist;
};
#endif // MAINWINDOW_H
In the form, create 2 buttons, one called pushbutton to play and the other is pushButton_2 to stop

Qt Creator compile error for QSensor

I'm new to Qt/Symbian development (I come from an iOS background), and I can't make sense of this compiler error:
Firstly, this is the error I'm getting:
/Users/Dave/AR-build-simulator/../QtSDK/Simulator/QtMobility/gcc/include/QtSensors/qsensor.h:-1: In member function 'QtMobility::QMagnetometerReading& QtMobility::QMagnetometerReading::operator=(const QtMobility::QMagnetometerReading&)':
Here is my header file:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui/QMainWindow>
#include <QSystemDeviceInfo>
#include <QGeoPositionInfoSource>
#include <QGeoCoordinate>
#include <QGeoPositionInfo>
#include <QMagnetometer>
QTM_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
enum ScreenOrientation {
ScreenOrientationLockPortrait,
ScreenOrientationLockLandscape,
ScreenOrientationAuto
};
explicit MainWindow(QWidget *parent = 0);
virtual ~MainWindow();
// Note that this will only have an effect on Symbian and Fremantle.
void setOrientation(ScreenOrientation orientation);
void showExpanded();
private slots:
void positionUpdated(QGeoPositionInfo gpsPos);
void magnetometerReadingChanged(QMagnetometerReading mr);
private:
Ui::MainWindow *ui;
void setupGeneral();
QGeoPositionInfoSource *m_location;
QGeoCoordinate m_coordinate;
QMagnetometer *m_magnetometer;
QMagnetometerReading m_magnetometerReading;
};
#endif // MAINWINDOW_H
Here is the implementation file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore/QCoreApplication>
#include <qgeopositioninfosource.h>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
setupGeneral();
}
void MainWindow::setupGeneral()
{
m_location = QGeoPositionInfoSource::createDefaultSource(this);
//Listen to gps position changes
QObject::connect(m_location, SIGNAL(positionUpdated(QGeoPositionInfo)), this,SLOT(positionUpdated(QGeoPositionInfo)));
//Start listening to GPS position updates
m_location->startUpdates();
//Start listening to magnetometer updates
m_magnetometer = new QMagnetometer(this);
connect(m_magnetometer, SIGNAL(readingChanged(QMagnetometerReading)), this, SLOT(magnetometerReadingChanged(QMagnetometerReading)));
m_magnetometer->start();
}
void MainWindow::positionUpdated(QGeoPositionInfo gpsPos){
m_coordinate = gpsPos.coordinate();
if (m_coordinate.isValid()) {
m_location->stopUpdates();
QString longitude;
QString latitude;
longitude.setNum(m_coordinate.longitude());
latitude.setNum(m_coordinate.latitude());
QMessageBox::information(this,"latitude",latitude);
} else {
QMessageBox::information(this, "GPS Info", "Coordinator is not valid...");
}
}
void MainWindow::magnetometerReadingChanged(QMagnetometerReading mr) {
QMessageBox::information(this, "Magnetometer info", "got magnetometer reading...");
m_magnetometerReading = mr;
//m_magnetometerReading = new QMagnetometerReading(this);
//m_magnetometerReading->copyValuesFrom(mr);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setOrientation(ScreenOrientation orientation)
{
#if defined(Q_OS_SYMBIAN)
// If the version of Qt on the device is < 4.7.2, that attribute won't work
if (orientation != ScreenOrientationAuto) {
const QStringList v = QString::fromAscii(qVersion()).split(QLatin1Char('.'));
if (v.count() == 3 && (v.at(0).toInt() << 16 | v.at(1).toInt() << 8 | v.at(2).toInt()) < 0x040702) {
qWarning("Screen orientation locking only supported with Qt 4.7.2 and above");
return;
}
}
#endif // Q_OS_SYMBIAN
Qt::WidgetAttribute attribute;
switch (orientation) {
#if QT_VERSION < 0x040702
// Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
case ScreenOrientationLockPortrait:
attribute = static_cast<Qt::WidgetAttribute>(128);
break;
case ScreenOrientationLockLandscape:
attribute = static_cast<Qt::WidgetAttribute>(129);
break;
default:
case ScreenOrientationAuto:
attribute = static_cast<Qt::WidgetAttribute>(130);
break;
#else // QT_VERSION < 0x040702
case ScreenOrientationLockPortrait:
attribute = Qt::WA_LockPortraitOrientation;
break;
case ScreenOrientationLockLandscape:
attribute = Qt::WA_LockLandscapeOrientation;
break;
default:
case ScreenOrientationAuto:
attribute = Qt::WA_AutoOrientation;
break;
#endif // QT_VERSION < 0x040702
};
setAttribute(attribute, true);
}
void MainWindow::showExpanded()
{
#ifdef Q_OS_SYMBIAN
showFullScreen();
#elif defined(Q_WS_MAEMO_5)
showMaximized();
#else
show();
#endif
}
If anybody could explain to me what is going wrong, I'd be very grateful.
According to the documentation(here) readingChanged signal does not have any parameters. You should use
connect(m_magnetometer, SIGNAL(readingChanged()), this, SLOT(magnetometerReadingChanged())); and then acquire the reading from the reading property.

Resources