Hi i'm trying to create a class which compares a value (val) against a previous value (val) from a potentiometer reading and then sends the reading to Serial monitor. I've used this tutorial: -
I'm not actually getting any errors but once i upload to the board (MEGA) there is no print out in the serial monitor.
here is my code: -
class pot{
public:
int pin;
int val;
int lastVal;
pot(int aPin, int aVal, int aLastVal){
pin = aPin;
val = aVal;
lastVal = aLastVal;
}
int stablePot(){
if(abs(val - lastVal) > 4){
Serial.println(val);
lastVal = val;
}
}
};
void setup(){
Serial.begin(9600);
}
void loop(){
pot pot0(A0, 0, 0);
pot0.stablePot();
delay(25);
}
I'm wondering if my problem is that I shouldn't be sending the Serial.println from within the class itself. perhaps extracting the result as an int and then printing from there. it would be much handier to keep it all within the class though.
is this possible? can anybody see where I'm going wrong?
Many thanks
There's no problem printing from the class, but you only do so if there is a difference between values greater than four. Since there isn't, nothing is ever printed. Try adding an else clause to that if to print a different message and you'll see it.
You are creating a new 'pot0' each time through loop(). When it is created you set lastVal to zero. When you add the reading of the pot pin you will get output whenever the pot pin is >4.
Note: 'abs()' returns a float. In your case, it will probably work but it is going to be relatively slow. You could write:
if (val - lastVal > 4 || lastVal - val > 4)
That would do everything in integers and avoid bringing in the floating-point libraries.
You are creating a new 'pot0' each time through loop(). When it is created you set lastVal to zero. When you add the reading of the pot pin you will get output whenever the pot pin is >4.
Note: 'abs()' returns a float. In your case, it will probably work but it is going to be relatively slow. You could write:
if (val - lastVal > 4 || lastVal - val > 4)
That would do everything in integers and avoid bringing in the floating-point libraries.
That's a good idea john. I wasn't aware that abs returned float but that makes sense. thanks
liamobsolete:
I wasn't aware that abs returned float but that makes sense. thanks
Looks like I was mistaken and 'abs()' is a macro so it returns a value of the same type as the argument. If you "#undef" the macro, the library function returns an integer.
Apologies for the misinformation.