I'm trying to get a small BMP085 barometer project up and running. I want to be able to switch between different modes of operation (MODE_PRESSURE and MODE_ALT). I have MODE_PRESSURE
and MODE_ALT
defined as 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;
}
}
When the mode button is pressed, I want to toggle the current mode. But I'm stuck at if(mode == MODE_PRESSURE)
. This statement somehow never evaluates to true...?
I'm not very fluent in C, is there something I am missing? Can I not compare const int
and int
variables?
P.S.: I've also tried #define
for MODE_PRESSURE and MODE_ALT, and const byte
, but nothing seems to work.
Using the if Statement With Comparison Operators in Arduino The if statement is used to check different conditions, if the condition is true, the code inside the if statement parenthesis will be executed; otherwise, not. The input parameter of an if statement is a boolean which can eighter be true or false.
In this tutorial, we will discuss the use of the if statement to check for different conditions in Arduino. The if statement is used to check different conditions, if the condition is true, the code inside the if statement parenthesis will be executed; otherwise, not.
Now, if we want to compare more than two variables using the if statement, then we have to use the boolean operators. The boolean operators are logical AND, logical NOT, and logical OR. We can use these operators to put more than one condition in the if statement.
The input parameter of an if statement is a boolean which can eighter be true or false. The basic syntax of the if statement is given below. In the above code, the condition is a boolean.
Add else
as follows:
if(mode == MODE_PRESSURE)
mode = MODE_ALT;
else if(mode == MODE_ALT) # although not need but keep if here also
mode = MODE_PRESSURE;
You could also use nested-switch:
switch(mode){
case MODE_PRESSURE: mode = MODE_ALT;
break;
case MODE_ALT: mode = MODE_PRESSURE;
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With