basic help with functions and variable declaration

howdy. here's my code.

int lastvalue = 0;

void setup()
{
  Serial.begin(9600);   
} 

void loop()
{
  int value = minMax(3);
  if(value != lastvalue)
  {
    Serial.println(value);
    lastvalue = value;
  }
}


int minMax(int pin)
{
  int prevRead;
  int output;
  int THRESHOLD = 2;
  int readVal = analogRead(pin);         //read input from potentiometer
  int readMap = map(readVal, 0, 1023, 0, 255);
  if(abs(readMap - prevRead) >= THRESHOLD)
  {
       output = readMap;
       prevRead = readMap;
     
  }
  return(output);
}

my problem/question is regarding this:

the THRESHOLD bit and the != lastval bit never seem to work when i try sticking them into a function other than void(main). why is that? also, in void(main), it only seems to work when the variables "threshold" and "prevX" and "lastX" are global.

can someone help clarify WHY?

without the "!= lastvalue" bit in void(main), serial.println will just print and print and print the output of int(minMax)

in my application, i need things to just print ONCE (rather, be sent once - serial print is just a way for me to see the data) and be done.

any direction would be great. i've pulled this off in void(main) a hundred times, but i've been taking C++ classes and would like to make my programs more modular with separate functions...
nym

First thing noticed is the line

int prevRead;

This variable gets out of scope when the function returns. The first time it is also not initialized. Change the line to :

static int prevRead = 0;

and see what it does.

Second not all code paths of minMax() set a value for the variable output.

A rewrite of minMax (): if there is a new value it return that if it is approx the same return the old one. (my interpretation of what could be meant)

int minMax(int pin)
{
  static int prevRead = 0;   // static to keep it's values between calls 
  int THRESHOLD = 2;   // could be a #define
  int readVal = analogRead(pin);         //read input from potentiometer
  int output = map(readVal, 0, 1023, 0, 255);
  // is there a (really) new value (not some fluctuation of the pot-meter)
  if (abs(output - prevRead) >= THRESHOLD)
  {
    // remember the new value
    prevRead = output;
  }
  else
  {
    // if it is (allmost) the same return the old value
    output = prevRead;
  }
  return output;
}

Note 1: the threshold acts upon the mapped value!
Note 2: the mapping to 0..255 can be done faster with

int output =  analogRead(pin) / 4;  // or >> 2