How do I send a MIDI message only when there is a change in the analog input?

Hi,

I have a project that sends a MIDI message relating to tremolo depth where the amount is read from a potentiometer connected to an analog input on my Arduino board. I have managed to get the sketch to send the MIDI messages, however they continue to send, even when there is no change in the value from the pot. I have been trying, with no success, to get it to only send a message when the value changes. I have tried 'if' statements and the 'EEPROM.read' and 'write' functions to compare the current value to the previous and only write when they are different but it doesn't seem to work.

Could anybody please offer me some advice. It would be greatly appreciated.
Here is my project so far:

#include <EEPROM.h>
int sensorValue=0;
int addr;
void setup() {
  //  Set MIDI baud rate:
  Serial.begin(31250);
  
}
void loop() {
    // read analogue input 0, divide by 8, set as sensorValue
    sensorValue = analogRead(A0)/8;
   
    EEPROM.write(addr, sensorValue);
   
    addr = addr+1;
    if (addr ==512)
    addr=0;
    
    int sensorValueNew = EEPROM.read(addr);
    
    if (sensorValueNew != sensorValue){
    //write midi message:: control change channel 1 (0xb0), controller 92 (tremolo depth), value 20
    depthChange(0xb0, 0x5c, 127-sensorValue);
     delay(200);
    }
   
  }
//write midi message 
void depthChange(int cmd, int controller, byte value) {
  Serial.write(cmd);
  Serial.write(controller);
  Serial.write(value);
}

Ditch the EEPROM before you harm your Arduino, 100k writes and the EEPROM will die so don't do this.

After that you compare the old value with the current value and the updtae the old with the current.

Mark