gpt4 book ai didi

c++ - 如何让我的 Qt 程序持续向我的 Arduino 发送字符串?

转载 作者:行者123 更新时间:2023-11-28 05:10:10 25 4
gpt4 key购买 nike

我在尝试让我的程序在按住按钮时持续发送字符串 "move 200" 时遇到了问题。我将按钮设置为自动重复,但它只会在按钮被释放时发送,而不是在按住按钮时发送。然而,当被按住时,计数器会添加消息应该发送的次数。我迷路了。

主窗口.cpp

void MainWindow::on_forwardButton_clicked()
{
if(arduino->isWritable()){

arduino->write(command.toStdString().c_str());

qDebug() << i;

}else{
qDebug() << "Couldn't write to serial!";
}

ui->label->setText("Moving");
i++;

}

主窗口.h

ifndef MAINWINDOW_H
define MAINWINDOW_H
include <QMainWindow>
include <QDialog>
include <QSerialPort>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private slots:

void on_forwardButton_clicked();

private:
Ui::MainWindow *ui;
QSerialPort *arduino; //makes arduino a pointer to the SerialPort
bool arduino_is_available;
QString command = "move 200";
bool buttonReleased = false;
};

endif // MAINWINDOW_H

根据@dtech 建议添加的代码

    pButtonTimer = new QTimer;
connect(pButtonTimer, SIGNAL(timeout()), this, SLOT(sendData()));

int i = 0;
void MainWindow::on_forwardButton_pressed()
{
pButtonTimer->start(1000);
ui->label->setText("Moving");
qDebug() << "Button Pushed";
}

void MainWindow::on_forwardButton_released()
{
pButtonTimer->stop();
}


void MainWindow::sendData(){
i++; //used to count how many times the command should have been sent
qDebug() << i << "sendData is running"; //notifies me the function has been called
if(arduino->isWritable()){
arduino->write(command.toStdString().c_str());
qDebug() << i << "arduino is writable with command " << command; //lets me know the Arduino is writable
}
else{qDebug() << "Couldn't write to serial!";}
}

松开按钮后,Arduino 中的串口监视器会显示发送的所有内容和机器人移动

最佳答案

我建议您稍微扩展一下您的设计:

  • 有一个重复的QTimer,其间隔取决于您希望发送字符串的速率,以及发送字符串的函数的计时器
  • 连接按钮的按下信号以启动定时器
  • 连接按钮的释放信号以停止定时器

事件只发送一次,因此处理程序只会执行一次,如果你想继续重复它,你将不得不使用定时器或其他一些事件驱动的方式。您不能使用循环,因为这会阻塞 GUI 线程并且您的应用程序将停止响应。

当然,您可以使用按钮的自动重复,并且可以选择调整触发和重复间隔,但是在逻辑和 GUI 之间划清界线的解决方案更好。您应该真正依赖 GUI 来存储数据或控制内部逻辑。 GUI 应该只是一个前端。

但您需要在串行端口上做更多的工作。如果要从 GUI 线程使用它,则必须使用非阻塞 API。这将需要更多地扩展您的实现。有一个good example on how to achieve that ,您只需要修改它以在成功发送前一个有效负载后简单地启用发送更多有效负载。在伪代码中:

on button press
start timer
on button release
stop timer
onTimeout
if (can send)
send
can send = false
onBytesWritten
accumulate bytes
if (payload is completed)
can send = true
reset payload byte counter

当然,您还必须进行一些错误检查,您不能指望它会起作用。链接的示例包含基本的错误处理。

关于c++ - 如何让我的 Qt 程序持续向我的 Arduino 发送字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43695121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com