Updating ac value for Qtimer - qt

I am using qt tool for mini2440.
I make a gui for i2c adc having starti2c and stopi2c.
All things are working well: it reads value of signal when starti2c button press, but I want this value to be updated. I know that Qtimer can be used, but how can I do it?
Here is the code:
# include <termio.h>
# include <time.h>
# include <string.h>
# include <sys/time.h>
HelloForm::HelloForm(QWidget* parent, const char* name, WFlags fl):
HelloBaseForm(parent, name, fl)
{
connect(PushButton1,SIGNAL(clicked()),this,SLOT(starti2c()));
connect(PushButton2,SIGNAL(clicked()),this,SLOT(stopi2c()));
}
HelloForm::~HelloForm()
{
}
//*********************Code for getting i2c**************************//
char HelloForm::geti2c()
{
char buf[100];
char buff[100];
char valuee;
int m1;
char con_buff[10];
int fd=open("/dev/i2c/0",O_RDWR);
if (fd<0)
{
Message->setText(" NOT ABLE TO OPEN THE DRIVER ");
}
else
{
Message->setText(" I2C IS WORKING ");
}
int io,wbyte,rbyte,i;
//********i2cdetect and read************
buf[0]=0x48;
buf[1]=0x00;
buf[2]=0x91;
io=ioctl(fd,I2C_SLAVE,0x48);
if(io<0)
{
Message->setText(" ");
Message->setText("error ioctl");
}
else
{
wbyte=write(fd,buf,3);
// write all three control word to arm
usleep(1*1000);
}
if(wbyte!=3)
{
Message->setText("error write");
Message->setText(QString::number(wbyte));
rbyte=read(fd,buff,10);
//ADC->setText(buff);
sscanf(buff,"%c",&valuee);
m1=int(valuee);
return(m1);
}
void HelloForm::starti2c()
{
while(1)
{
float adc_val=0;
adc_val=geti2c();
adc_val=(adc_val*5)/255.00;
usleep(1*1000);
ADC->setText(QString::number(adc_val));
}
}
//***********stop********//
void HelloForm::stopi2c()
{
ADC->setText(" ");
Message->setText("Stopped");
}

Hopefully this will get you started - it creates a timer which times out every 1000 milli seconds. The timer's timeout signal is connected to the same slot that your PushButton1 is connected to - starti2c.
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(starti2c()));
timer->start(1000);
That code should be placed below where you have your 2 connection statements.

Related

How to stop a loop in a QPushButton pressed?

I have a connection with Arduino. I need to send continuously a character to serial port to handle a motor series when I press a button. So I created a QPushButton and I want when it is pressed it send this character.
But when I need to create a loop I don't know how to break it. I tried this solution
...
Class .... {
private:
bool buttonPressed = false;
}
void MainWindow::on_pulsante1_pressed()
{
buttonPressed = true;
while (buttonPressed == true)
{
connect(ui->pulsante1,SIGNAL(released()),this,SLOT(on_pulsante1_released()));
qDebug() << "pressed";
}
}
void MainWindow::on_pulsante1_released()
{
buttonPressed = false;
qDebug() << "released";
}
Where did I do wrong?
You probably want to use a QTimer for that. Also you can define the frequency that the timer fires. For example:
#include <QTimer>
..
Class .... {
private:
QTimer timer;
}
void MainWindow::MainWindow(){
// in your constructor
connect(&timer, [this]{
//
// write to serial here
//
});
}
void MainWindow::on_pulsante1_pressed()
{
qDebug() << "pressed";
timer.start(1); // run this every 1 milisecond
}
void MainWindow::on_pulsante1_released()
{
timer.stop();
qDebug() << "released";
}
}
Take a look to QTimer documentation

How to make animation in *.gif run only once in Qt? [duplicate]

I'm using QMovie and gif to create explosion after collision. The problem is that my gif is looping over and over, I've checked loopcount status and it returns -1 (infinite). How to display my gif just one time?
#include "Bullet.h"
#include <QTimer>
#include <QGraphicsScene>
#include <QList>
#include "Enemy.h"
#include "Game.h"
#include <typeinfo>
#include "levels.h"
extern Game * game; // there is an external global object called game
int Bullet::killed = 0;
int Bullet::missed = 0;
double Bullet::accurancy = 0;
Bullet::Bullet(QGraphicsItem *parent): QGraphicsPixmapItem(parent){
// draw graphics
setPixmap(QPixmap(":/images/res/images/bullets/bullet.png"));
missed++; // increse missed when bullet is created
movie = new QMovie(":/images/res/images/effects/explosion/64x48.gif");
processLabel = new QLabel;
processLabel->setMovie(movie);
// make/connect a timer to move() the bullet every so often
QTimer * timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(move()));
// start the timer
timer->start(2);
}
void Bullet::move(){
// get a list of all the items currently colliding with this bullet
QList<QGraphicsItem *> colliding_items = collidingItems();
// if one of the colliding items is an Enemy, destroy both the bullet and the enemy
for (int i = 0, n = colliding_items.size(); i < n; ++i){
if (typeid(*(colliding_items[i])) == typeid(Enemy)){
// increase the score
game->score->increase();
//play explosion animation
movie->start();
movie->setSpeed(180);
processLabel->setAttribute(Qt::WA_NoSystemBackground);
processLabel->setGeometry(QRect(x()-15,y()-15,64,48));
scene()->addWidget(processLabel);
qDebug() << movie->loopCount();
//connect(movie,SIGNAL(finished()),movie,SLOT(stop()));
// remove them from the scene (still on the heap)
scene()->removeItem(colliding_items[i]);
scene()->removeItem(this);
// delete them from the heap to save memory
delete colliding_items[i];
delete this;
killed++;
missed--; // decrese missed if bullet colide with enemy
if((killed+1) % 9 == 0)
{
game->level->Levels::incrementLevels();
game->score->Score::addToSum(); /// TODO
}
//qDebug() << "Already killed: " << killed;
//qDebug() << "Already missed: " << missed;
// return (all code below refers to a non existint bullet)
return;
}
}
// if there was no collision with an Enemy, move the bullet forward
setPos(x(),y()-1);
// if the bullet is off the screen, destroy it
if (pos().y() < 0){
scene()->removeItem(this);
delete this;
}
}
I had the same question and didn't find anything, so here's my solution:
connect the signal "frameChanged(int)" to:
void Bullet::frameChanged_Handler(int frameNumber) {
if(frameNumber == (movie->frameCount()-1)) {
movie->stop();
}
}
If you want to run X times the loop you just have to add a static counter to know how many times you've passed the last frame:
void Bullet::frameChanged_Handler(int frameNumber) {
static int loopCount = 0;
if(frameNumber == (movie->frameCount()-1)) {
loopCount++;
if(loopCount >= MAX_LOOP_TIMES)
movie->stop();
}
}
and of course, connect with this:
connect(movie, SIGNAL(frameChanged(int)), this, SLOT(frameChanged_Handler(int)));
That's it... Hope it can help you.

How to stop the pintool artificially

I want to use the pin to track the address of the first 256*256 instructions, but I don't know how to stop the pin after the number is reached. I know there is a method PIN_ExitProcess(), but make will cause an error after adding it. Is there any other way?
#include <stdio.h>
#include "pin.H"
FILE * trace;
VOID printip(VOID *ip) {
fprintf(trace, "%p\n", ip);
}
VOID Instruction(INS ins, VOID *v)
{
if(0x70000000>INS_Address(ins))
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)printip, IARG_INST_PTR, IARG_END);
}
VOID Fini(INT32 code, VOID *v)
{
fprintf(trace, "#eof\n");
fclose(trace);
}
INT32 Usage()
{
PIN_ERROR("This Pintool prints the IPs of every instruction executed\n"
+ KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
int main(int argc, char * argv[])
{
trace = fopen("itrace.out", "w");
if (PIN_Init(argc, argv)) return Usage();
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddFiniFunction(Fini, 0);
PIN_StartProgram();
return 0;
}
You have two options:
Simply count the number of traced instructions and stop fprintfing when you reach the threshold using an if statement.
Call PIN_Detach() when the instruction threshold is reached. See more here: https://software.intel.com/sites/landingpage/pintool/docs/97503/Pin/html/group__PIN__CONTROL.html#ga6277d16bf33ede39685a26a92fc3cbef

How to write data to a given serial port with qt?

#include <QSerialPort>
#include <QSerialPortInfo>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Example use QSerialPortInfo
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
// Example use QSerialPort
QSerialPort serial;
serial.setPort(info);
if (serial.open(QIODevice::ReadWrite))
//I try to send a string of hexadecimal numbers,seems not right
//serial.write(QByteArray("0xFF010100FFFFFF"));
serial.close();
}
return a.exec();
}
The example above shows how to open all available serial ports and then close them. But I want to open a given serial port, such as COM6, set its BaudRate,DataBits,Parity,StopBits ,FlowControl and then send a string of hexadecimal numbers.
This video will definitely help you: https://www.youtube.com/watch?v=UD78xyKbrfk
You can also find similar code here: https://cboard.cprogramming.com/cplusplus-programming/169624-read-write-serial-port.html
Example code:
#include <QSerialPort>
MySerialPort::MySerialPort()
{
serial = new QSerialPort(this);
openSerialPort();
}
void MySerialPort::openSerialPort()
{
serial->setPortName("COM3");
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
if (serial->open(QIODevice::ReadWrite))
{
//Connected
}
else
{
//Open error
}
}
void MySerialPort::writeData(const QByteArray &data)
{
serial->write(data);
}

connecting a signal of widget in a plasmoid

I am new to Qt and am trying to connect the cilicked signal o a push button with a function hile writing a plasmoid. I am trying to use an external function as a public with Plasma::PushButton type object so that I can use it to connect it with the clicked signal? With gtk it was as simple as on_...._clicked do this but isnt there a simple way in qt, where we can do away with the need to use slots?
#include "plasma-tutorial1.h"
#include<string.h>
#include <stdlib.h>
#include <QGraphicsLinearLayout>
#include <QPainter>
#include <QFontMetrics>
#include <QSizeF>
#include <QTextEdit>
#include <plasma/svg.h>
#include <plasma/theme.h>
#include <plasma/widgets/lineedit.h>
#include <plasma/widgets/pushbutton.h>
#include <plasma/widgets/textedit.h>
//PlasmaTutorial1 mainf;
themainfunction(int choice,Plasma::LineEdit *m_lineEdit,
Plasma::TextEdit *m_displaytext)
{
char buffer[100];
const char *inp=(const char *)malloc(sizeof(char)*100);
QString input;
input=m_lineEdit->text();
QByteArray byteArray = input.toUtf8();
inp = byteArray.constData();
char *expression;
expression=(char *)malloc(sizeof(char)*100);
strcpy(expression,"sudo apt-");
switch(choice)
{
case 1:{
strcat(expression,"get install ");
strcat(expression,inp);
break;
};
case 2:{
strcat(expression,"get remove ");
strcat(expression,inp);
break;
};
case 3:{
strcat(expression,"cache search ");
strcat(expression,inp);
break;
};
};
/*
FILE* in;
FILE* ptr=fopen("new.txt","w");
FILE *popen();
if(!(in = popen("cal","r")))
{return;}
while(fgets(buffer, 100, in) != NULL) {
*/
m_displaytext->append("yeah!");
// fprintf(ptr,"%s",buffer);
//}
//pclose(in);
//fclose(ptr);
}
PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args)
: Plasma::Applet(parent, args),
m_svg(this),
m_icon("document")
{
m_svg.setImagePath("widgets/background");
// this will get us the standard applet background, for free!
setBackgroundHints(DefaultBackground);
resize(200, 200);
}
PlasmaTutorial1::~PlasmaTutorial1()
{
if (hasFailedToLaunch()) {
// Do some cleanup here
} else {
// Save settings
}
}
void PlasmaTutorial1::init()
{
/* // A small demonstration of the setFailedToLaunch function
if (m_icon.isNull()) {
setFailedToLaunch(true, "No world to say hello");
}*/
Counter rt;
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(this);
layout->setOrientation(Qt::Vertical); //so widgets will be stacked up/down
m_lineEdit = new Plasma::LineEdit(this);
m_lineEdit->setText("Enter the package name here");
m_displaytext = new Plasma::TextEdit(this);
m_displaytext->setText("Terminal");
m_installButton = new Plasma::PushButton(this);
m_installButton->setText("Install");
connect(m_installButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(1,m_lineEdit,m_displaytext)));
m_removeButton = new Plasma::PushButton(this);
m_removeButton->setText("Remove");
// m_removeButton->clicked()
connect(m_removeButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(2,m_lineEdit,m_displaytext)));
m_searchButton = new Plasma::PushButton(this);
m_searchButton->setText("Search");
connect(m_searchButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(3,m_lineEdit,m_displaytext)));
layout->addItem(m_lineEdit);
layout->addItem(m_installButton);
layout->addItem(m_removeButton);
layout->addItem(m_searchButton);
layout->addItem(m_displaytext);
m_displaytext->append("yo baby!");
}
/*
void PlasmaTutorial1::paintInterface(QPainter *p,
const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
p->setRenderHint(QPainter::SmoothPixmapTransform);
p->setRenderHint(QPainter::Antialiasing);
// Now we draw the applet, starting with our svg
m_svg.resize((int)contentsRect.width(), (int)contentsRect.height());
m_svg.paint(p, (int)contentsRect.left(), (int)contentsRect.top());
// We place the icon and text
p->drawPixmap(7, 0, m_icon.pixmap((int)contentsRect.width(),(int)contentsRect.width()-14));
p->save();
p->setPen(Qt::white);
p->drawText(contentsRect,
Qt::AlignBottom | Qt::AlignHCenter,
"Hello Plasmoid!");
p->restore();
}
*/
// This is the command that links your applet to the .desktop file
K_EXPORT_PLASMA_APPLET(tutorial1, PlasmaTutorial1)
#include "plasma-tutorial1.moc"
say i want to connect themainfunction() upon clicked signal of install button . how do i do it? how can I derive a class in plasma?
i got where was i missing out. We cannot pass objects as arguments in slot functions. Now it is running smooth. thanx for all your replies.

Resources