Hello,
I have two variables (int, long) which I want to change by pressing buttons. In both cases there is given a certain range. The variables should not become larger or smaller. Instead of of controlling the variables with if-statements it sounded a good idea to use the constrain library instead. I use the Arduino UNO.
The ZIP-library lies in the correct folder, the library shows up in the library list (Sketch - Import Library).
//Example sketch for testing, the long varable ignored
#include <Constrain.h>
Constrained<int> constrainedInt(2, 0, 10);
void setup() {
// put your setup code here, to run once:
Serial.begin(9800);
constrainedInt = 0;
for(int i=0; i<12, i++){
Serial.print(constrainedInt.Value);
constrainedInt++;}}
}
void loop() {
}
The compiler says: "Error compiling for the board Uno"
Is the constrain library not suitable for the Uno?
Thanks for answering
-richard
The problem is not in the use of the library, you have one } too many at the end of the setup.
You don't really need this library, there exist a native function to constrain a variable between 2 values : try this, it's a little heavier but it should work (not tested)
int constrainedInt;
const int minValue = 0;
const int maxValue = 10;
void setup() {
Serial.begin(115200);
for (int i = 0; i < 15; i++) {
constrainedInt = i - 2;
constrain (constrainedInt, minValue, maxValue);
Serial.print(i);
Serial.print("\t");
Serial.println(constrainedInt);
}
}
void loop() {
}
Thanks for your suggestion. I didn't know constrain() as an already implemented function. I mostly prefer genuine functions to additional libraries, if there is an alternative.
I changed your code a little to see if the constraining works:
int constrainedInt;
void setup() {
Serial.begin(115200);
for (int i = 0; i < 15; i++) {
Serial.print(i);
constrainedInt = i;
constrain(constrainedInt, 2, 10);
Serial.print("\t");
Serial.println(constrainedInt);
}
}
void loop() {
}
The left column of the output should run from 0 to 14, in the right column only numbers 2...10 should appear, but both columns show the same (0...14). It seems that I have a mental block ;-(