Declaration of variables
int val = analogRead(A0); // read the input on analog pin 0:
I don't recommend you to declare variables in the loop()
function when you can declare them outside once:
// declaration here!
int val = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
// just set the value
val = analogRead(A0); // read the input on analog pin 0:
val = map(val, 0, 1023, 0, 14); // map the vlaues to new values
...
Increase / decrease checks
In C++ you can make an assignment even in a conditional statement. if (val++)
and if (val--)
won't do what you expect. The if
statement checks if val
is not false or 0, and then ++
increases it by 1. Same for val--
but decreasing by -1.
What you can do is to keep the previous value in another variable (let's say prev
) to compare it later like this:
// declaration here!
int val = 0;
int prev;
...
void loop() {
// keep the previous value
prev = val;
// just set the value
val = analogRead(A0); // read the input on analog pin 0:
...
// compare the previous value
if (val > prev) {
Serial.println("up");
} else if (val < prev) {
Serial.println("down");
}
// and no need to leave empty an `else` block
}