设置开关直到达到标志,然后将开关设置为关闭

时间:2013-06-06 19:41:53

标签: c

最好和最简单(最简单)的方法是什么??

我用C或Capel编写代码(Vector CANoe) 我在Vector Canoe设计的面板上有一个开关,打开和关闭电机(0 ==关闭,1 ==打开),我想在达到极限时关闭电机..停止电机烧坏了! (当传感器表示达到极限时,我们知道它已达到极限(传感器=达到极限值为1,未达到极限值为0)

我该怎么做?

我想做这样的事情

WHILE (clutchMotorPower==1 & sensorClutchDisengaged !=1) 
break; 
else clutchMotorPower==0 

WHILE (clutchMotorPower==1 & sensorClutchEngaged !=1) 
break;     
else clutchMotorPower==0

1 个答案:

答案 0 :(得分:2)

我对你正在研究的系统知之甚少,所以这将是一些简单的代码。无论如何,让我们一步一步地完成。

假设:

  • button是一个变量,如果当前按下按钮则为1,否则为0。
  • motor是一个变量,我们设置为1以打开电机,或0设置为关闭电机。
  • sensor是一个变量,当传感器被激活时为1,否则为0

首先,我们需要代码来按下按钮时切换电机状态。 (假设所有代码示例都在从主循环调用的函数内)

//values of static variables are preserved between function calls
static char bActivateMotor = 0; //1 if we should activate motor, 0 otherwise
static char bButtonHeld = 0; //1 if button was pressed last loop
    //(to differentiate between button being held and it being released and pressed again)
if(!button) {
    bButtonHeld = 0; //if button is not being pressed, it can't be being held down.
}
if(!bActivateMotor) { //we aren't running the motor
    if(button && !bButtonHeld) { //button was pressed this loop (not held from previous loop)
        bButtonHeld = 1; //Don't toggle motor state next loop just because button was held down
        bActivateMotor = 1; //we should be running the motor
    }
    else {
        motor = 0;
    }
}
if(bActivateMotor) { //not else because could be activated this loop
    if(button && !bButtonHeld) { //button toggles motor; if we're running, stop.
        bButtonHeld = 1;
        bActivateMotor = 0;
    }
    else {
        motor = 1;
    }
}

现在,下一部分是在传感器激活时停止电机:

//values of static variables are preserved between function calls
static char bActivateMotor = 0; //1 if we should activate motor, 0 otherwise
static char bButtonHeld = 0; //1 if button was pressed last loop
    //(to differentiate between button being held and it being released and pressed again)
if(!button) {
    bButtonHeld = 0; //if button is not being pressed, it can't be being held down.
}
if(!bActivateMotor) { //we aren't running the motor
    if(button && !bButtonHeld) { //button was pressed this loop (not held from previous loop)
        bButtonHeld = 1; //Don't toggle motor state next loop just because button was held down
        bActivateMotor = 1; //we should be running the motor
    }
    else {
        motor = 0;
    }
}
if(bActivateMotor) { //not else because could be activated this loop
    if(button && !bButtonHeld) { //button toggles motor; if we're running, stop.
        bButtonHeld = 1;
        bActivateMotor = 0;
    }
    /////////////////////
    // Added Code Here //
    /////////////////////
    else if(sensor) {
        bActivateMotor = 0; //motor will shut off next loop
    }
    else {
        motor = 1;
    }
}

由于缺乏关于代码的细节,很难确切地知道您可能遇到的困难,但希望上面的算法将是一个很好的起点。