如果依赖于按钮且处于 while 循环中,如何将 int 设置为 1?

问题描述 投票:0回答:4

我正在对机器人进行编程,不幸的是在其自主模式下我遇到了一些问题。 当按下按钮时,我需要将整数设置为 1,但为了让程序识别该按钮,它必须处于 while 循环中。正如您可以想象的那样,程序最终陷入无限循环,并且整数值最终接近 4,000。

 task autonomous()
   {
    while(true)
        {
    if(SensorValue[positionSelectButton] == 1)
        {
            positionSelect = positionSelect + 1;
            wait1Msec(0350);
        }
        }
   }

我已经设法通过使用等待来获取该值,但我不想这样做。我还有其他方法可以解决这个问题吗?

c embedded
4个回答
1
投票

假设

SensorValue
来自与 while 循环异步的物理组件,并且是一个按钮(即不是切换按钮)

task autonomous()
{
    while(true)
    {
        // check whether 
        if(current_time >= next_detect_time && SensorValue[positionSelectButton] == 1)
        {
            positionSelect = positionSelect + 1;

            // no waiting here
            next_detect_time = current_time + 0350;
        }

        // carry on to other tasks
        if(enemy_is_near)
        {
            fight();
        }

        // current_time 
        current_time = built_in_now()
    }
}

通过某些内置函数或增加一个整数来获取当前时间,并在达到最大值后回绕。

或者如果您处于另一种情况:

task autonomous()
{
    while(true)
    {
        // check whether the flag allows incrementing
        if(should_detect && SensorValue[positionSelectButton] == 1)
        {
            positionSelect = positionSelect + 1;

            // no waiting here
            should_detect = false;
        }

        // carry on to other tasks
        if(enemy_is_near)
        {
            if(fight() == LOSING)
               should_detect = true;
        }
    }
}

0
投票

尝试记住按钮的当前位置,并且仅在其状态从关闭变为打开时才采取操作。

根据硬件的不同,您可能还会收到一个信号,就好像它在一毫秒内来回翻转几次一样。如果这是一个问题,您可能还想存储上次激活按钮的时间戳,然后忽略此后短时间内的重复事件。


0
投票

您可以将按钮连接到中断,然后在中断处理程序中进行必要的更改。

这可能不是最好的方法,但它是最简单的。


来自 Vex 机器人目录 :

(12)可用作中断的快速数字I/O端口

因此,您使用的 Vex 微控制器很可能支持中断。


0
投票

你的问题有点模糊
我不确定为什么你需要这个变量来增加以及事情到底是如何工作的......但我会尝试一下。更多地解释一下机器人如何移动......我们将能够提供更多帮助。

task autonomous()
{
    int buttonPressed=0;
    while(true)
    {
        if(SensorValue[positionSelectButton] == 1)
        {
            positionSelect = positionSelect +1;
            buttonPressed=1;
        }
        else{
            buttonPressed = 0;
        }


        //use your variables here 
        if( buttonPressed  == 1){
            //Move robot front a little
        }

    }
}

总体思路是:
首先,您检测按下的所有按钮,然后根据它们执行操作
所有这些都在你的 while 循环中......它将(并且应该)永远运行(至少只要你的机器人还活着:))
希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.