I'm wondering if someone can help me with an issue. I have a potentiometer that sends values to the serial monitor, using very simple code. What I need is code that will only print to the serial if the potentiometer value is changed and not constantly write the same value over and over again.
Your help is much appreciated ,
int Value = A0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(Value, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(analogRead(Value));
delay(500);
}
Add a variable where you can save a last variable value.
Compare this last variable with the current variable, if it changes more than an amount you think is reasonable, print the new variable and update the last variable.
const byte analogPin = A0;
//change this value to what's needed
const byte hysteresis = 20;
int currentValue;
int previousValue;
//********************************************^************************************************
void setup()
{
Serial.begin(115200);
} //END of setup()
//********************************************^************************************************
void loop()
{
currentValue = analogRead(analogPin);
//****************************
//are these two variables different "by at least 'hysteresis' amount" ?
if (abs(currentValue - previousValue) >= hysteresis)
{
Serial.println(currentValue);
//update the previous value
previousValue = currentValue;
}
//****************************
delay(500);
} //END of loop()
//********************************************^************************************************