我正在尝试使用 QTimer
函数运行一个函数大约 5 秒。在研究了文档和测试之后,我似乎无法在 Qt 中找到执行此操作的函数。
我尝试了以下方法:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(myFunction());
timer->start(5000);
此方法每 5 秒运行一次函数。这不是我想要实现的目标。我还尝试使用以下代码来使用 singleShot()
属性:
QTimer::singleShot(5000,this,SLOT(myFunction()));
这个函数只会触发我的函数一次。 QTimer
是否有任何属性可以在给定时间内运行我的函数。像这样的东西:
run function and timeout function after 5 seconds.
编辑:更多信息:
这是我大学的机器人比赛。我开车要做的是通过 TCP 驱动机器人的轮子。我知道两个轮子需要运行多少秒才能让机器人转动某个角度。 myFunction
中的 SLOT 类似于 senddatatoRobot()
该函数基本上通过 TCP 向我的机器人发送数据,根据机器人从期望的端点。例如,我知道如果我向左右轮发送 4096 和 0 的 PWM 值 5 秒,我的机器人将进行 360 度转弯。例如,要进行 45 度转弯,我会发送指定秒数的数据。
最佳答案
你可以尝试这样的事情:
QElapsedTimer t;
t.start();
while (t.elapsed() < 5000) { ...do stuff... } // this will block the thread
你也可以这样做:
startDoingStuff(); // must not block the thread
QTimer::singleShot(5000, this, "stopDoingStuff");
但是从您的评论来看,您似乎需要分享该函数的实际作用,并且肯定会更多地了解事件驱动编程,然后您将能够提出更好的设计。
The function basically sends data over TCP to my robot, turning it a certain angle based on the orientation of the robot from a desired endpoint. For example, I know my robot will make a 360 degree turn if I send a PWM value of 4096 and 0 to the left and right wheels for 5 seconds. So to make a 45 degree turn for example, I would enter send data for a specified number of seconds.
在我看来,更有效的解决方案似乎是只发送值更改而不是重复发送相同的数据。
因此,在机器人的微 Controller 代码中,您将连续缓存和使用这些值,而在您的 Controller 应用程序中,您将仅“设置”远程值:
public slots:
void reset() { send(0, 0); }
...
// begin turning
send(4096, 0);
QTimer::singleShot(5000, this, "reset"); // end turning in 5 secs
更好的解决方案是不发送 PWM 值,而是发送机器人特定命令,并让机器人的微 Controller 保持计时,因为它很可能比 QTimer
更擅长.您甚至可以获得更具体的信息,例如在 T 秒内旋转 X 度的命令。在机器人微 Controller 代码方面,您肯定有很大的改进空间。
如果您必须使用您当前正在尝试的方法,您可以使用QElapsedTimer
方法来实现一个具有函数void send(v1, v2 , time)
只要你把 worker 放在另一个线程中,这样你就不会阻塞主线程,这会导致操作系统报告你的应用程序“没有响应”。但是这样命令就不能被打断,在当前命令完成之前不能发出新的命令。您可以通过实现非阻塞 worker 来改进它,如 this example 中所述。 .这样您就可以在当前命令完成之前通过中断发出新命令。
关于c++ - 在 Qt 中运行一个定时器 5 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36769933/