如何在不暂停循环的情况下使用字符输入停止循环

How to stop loop using character input without pausing loop

美好的一天,

我正在尝试创建一个程序,从传感器获取方向数据,然后在 PID 控制算法中使用该数据来创建相应的 PWM 信号。我希望能够通过按 enter 来停止程序。我尝试使用 opencv 的 waitKey();但是它不接受我的键盘输入。我也试过 cin.get();但它暂停了我的循环,从而产生了问题。一旦四轴飞行器改变方向,我的 pwm 就不会刷新。我尝试研究其他方法,但我无法让它们起作用。这是我使用上述两种方法的代码示例。

使用cin.get():

using namespace std;

int main(void){

    while(1){
        /* get orientation data */

    /* output corresponding pwm */

    //Press enter to stop loop
        if(cin.get() == '\n'){
            /* Stop Pwm */ 
            break;
        }
    }
    return 0;
}

使用 waitKey();

using namespace std;
using namespace cv;

int main(void){

    while(1){
        /* get orientation data */

        /* output corresponding pwm */

        //Press ESC to stop loop
        int key = waitKey(33){
        if(key == 27){
            /* Stop Pwm */ 
            break;
        }
    }
    return 0;
}

您需要一种查询键盘当前状态的方法,C++ 本身不提供这种方法。过去我使用 SDL for this exact thing. I like SDL because it is simplistic in nature, and is entirely written in C. There is an example on the SDL wiki that demonstrates detecting keyboard state 来检测按钮是否被按下。

编辑:SDL 可以放在 Raspbian Pi 上。我找到了一个示例设置 here