如何废除延迟功能会导致不良影响(如何解决这种情况)?

时间:2015-10-08 22:14:52

标签: microcontroller pic

我有一个场景问题,我不想使用中断导致同样的问题,我将被迫使用延迟来确保特定时间确实通过。

问题:

我不想使用延迟功能,因为它会在某种情况下停止检查或执行其他任务:

如果按下按钮1,我的电机运行6秒,如果按下按钮2,则马达2需要立即启动并工作2秒钟。

所以代码将是这样的:

main ()
{

if( Rd0 == 0 )   // is button1 is pressed
{
RunMotre1(); 

__delay_ms(6000);
StopMotor1();

}


if( Rd1 == 0 )  // is button2 is pressed
{
RunMotor2();
__delay_ms(2000);
StopMotor2();
}

}

如果我们按下按钮b启动Motor 2,这个代码的问题就会出现 不起作用导致系统在延迟时被阻止并等待它完成。

这导致如果我们开始 - >按下按钮1->电动机1运行 - >按下buTTon2以启动Motor2->电机2在6秒钟后才工作。

有没有办法解决这个问题。

例如,如果存在比较谁的变速时间Motor1确实运行,如果是greate或= 6 secound然后停止电机1示例(如果存在则这样的事情):

Time counter1;
Time Counter2;

main()
{ 


if( Rd0 == 0 )     // is button 1 to start motor1 is presed ?
{
RunMotre1(); 

counter1.start();
}


if(counter1.CurentElapsedTimes==6 Secound)   // is motor1 did run 6 seconds
{
counter1.stop();
counter1.Initialise();

StopMotor1();
}

if( Rd1 == 0 )        // is button 2 to start motor2 is pressed.
RunMotor2();
counter2.start();
}

if(counter2.CurentElapsedTimes==2 Secound)   // is motor2 did run 2 seconds
{
counter2.stop();
counter2.Initialise();

StopMotor2();
}

或任何解决方案

平台pic微控制器使用xc8编译器

1 个答案:

答案 0 :(得分:0)

PRESUPPOSITION:我不知道你使用的PIC,但我认为它至少有一个空闲计时器。

这里的问题是你需要一些东西来追踪时间。我的建议是使用Arduino FW使用的相同技术:设置定时器每隔X毫秒/秒触发一次中断,然后在中断服务程序(ISR)中更新计数器。

当您按下按钮设置计数器时,等待计数器达到另一个值,然后再关闭电机。

我将在这里写一个小的伪代码示例,因为我不记得如何用PIC编译器正确编写ISR,也不知道你的PIC是什么(以及初始化定时器的命令)

我选择使用100毫秒的计时器粒度,但您可以根据需要更改它。 我还选择将counter设置为8位变量;它最多可以计算25.5秒,但由于最高延迟是6秒,所以没关系。

请注意,您只需要一个计时器,因此您可以添加任意数量的电机而无需添加计数器

char counter;
char motor1StartTime;
char motor2StartTime;
bool motor1Running;
bool motor2Running;

Timer1_ISR()
{
    counter++;
}

main()
{ 
    counter = 0;
    motor1StartTime = 0;
    motor2StartTime = 0;
    motor1Running = false;
    motor2Running = false;

    // Setup the timer to trigger the Timer1_ISR every 100ms
    ...

    while(1)
    {
        if( Rd0 == 0 )
        { // If the button is pressed start the motor and save the counter
            RunMotor1(); 
            motor1StartTime = counter;
            motor1Running = true;
        }

        if ((motor1Running) && ((counter - motor1StartTime) >= 60))
        { // If the motor is running from more than 6 seconds, shut it down
            StopMotor1();
            motor1Running = false;
        }


        if( Rd1 == 0 )
        { // If the button is pressed start the motor and save the counter
            RunMotor2(); 
            motor2StartTime = counter;
            motor2Running = true;
        }

        if ((motor2Running) && ((counter - motor2StartTime) >= 20))
        { // If the motor is running from more than 2 seconds, shut it down
            StopMotor2();
            motor2Running = false;
        }
    }
}