Smoothening a potentiometer

So im trying to build a midi controller,and i ran into this problem.
sometimes when my potentiometer sits just right it will flicker between two values.
I have tried to smoothen the readings by thaking the average of 10 readings but it was with no luck.
Then i tought "if i could code the arduino to only output serial when the potentiometer has been turned more than for example 4 values"
But i am not the best a coding yet so i sort you you forum to help...

right now i am using this code for one pot.

const int numReadings = 10;

int val = 0;
int lastVal = 0;

int readings[numReadings];
int readIndex = 0;
int total = 0;
int average = 0;

int Pot = A0;

void setup() {
  Serial.begin(9600);
  
for (int thisReading = 0; thisReading < numReadings; thisReading++) { 
  readings[thisReading] = 0;
  }
}

void loop() {
total = total - readings[readIndex];

readings[readIndex] = analogRead(Pot)/8;

total = total + readings[readIndex];

readIndex = readIndex + 1;
delay(5);

// End of array
if (readIndex >= numReadings){
  readIndex = 0;
  }
  average = total / numReadings;

  val = average;
  if (val !=lastVal)
  {
    MIDImessage(176,123,val);}
    lastVal = val;
  }
  
void MIDImessage(byte command, byte data1, byte data2)
{
  Serial.write(command);
  Serial.write(data1);
  Serial.write(data2);
  
}

any other suggestions for a way to solve this will also be greatly appreciated.

Steamed_muffin

Something like this might work

newPotVal = analogRead(potPin);
if (abs(newPotVal - potVal) > NNN) { // NNN represents the minimum change you want to detect
  potVal = newPotVal;
}

...R

Robin2:

newPotVal = analogRead(potPin);

if (abs(newPotVal - potVal) > NNN) { // NNN represents the minimum change you want to detect
  potVal = newPotVal;
}

If you pick NNN too large, you can't ever reach zero, and you'll lose a lot of resolution.

For my MIDI controller library, I used moving average filters. It works just fine.

Here's a basic sketch for a single potentiometer:

#include <MIDI_Controller.h> // Include the library
// Create a new instance of the class 'Analog', called 'potentiometer', on pin A0, 
// that sends MIDI messages with controller 7 (channel volume) on channel 1
Analog potentiometer(A0, MIDI_CC::Channel_Volume, 1);
void setup() {}
void loop() {
  // Refresh the MIDI controller (check whether the potentiometer's input has changed since last time, if so, send the new value over MIDI)
  MIDI_Controller.refresh();
}

Pieter