我正在尝试启动并运行一个小的BMP085气压计项目。我希望能够在不同的操作模式(MODE_PRESSURE和MODE_ALT)之间进行切换。我有MODE_PRESSUREMODE_ALT定义为const int

const int MODE_PRESSURE = 1;  // display pressure and temp
const int MODE_ALT      = 2;  // display altitude relative to sea level
int mode;                     // stores the current mode

void setup {
    mode = MODE_PRESSURE;
}

void loop {

    // Read mode button and set mode accordingly
    int buttonPressed = readButtons();

    switch(buttonPressed) {
    case BTN_MODE:
        if(mode == MODE_PRESSURE) { mode = MODE_ALT; }
        if(mode == MODE_ALT) { mode = MODE_PRESSURE; }
        Serial.println(mode); // <<-- always prints 1 ?!
        break;
    }
}

当按下模式按钮时,我想切换当前模式。但是我被困在if(mode == MODE_PRESSURE)。这种说法总算不算是真的...?

我的C语言不太流利,我缺少什么吗?我不能比较const intint变量吗?

附注:我还尝试了MODE_PRESSURE和MODE_ALT的#defineconst byte,但似乎没有任何效果。

最佳答案

添加else,如下所示:

    if(mode == MODE_PRESSURE)
       mode = MODE_ALT;
    else if(mode == MODE_ALT) # although not need but keep if here also
       mode = MODE_PRESSURE;

您还可以使用嵌套开关:
switch(mode){
     case MODE_PRESSURE: mode = MODE_ALT;
             break;

     case MODE_ALT: mode = MODE_PRESSURE;
             break;
}

关于c++ - Arduino:if-compare参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21108444/

10-11 19:37
查看更多