Where is the flaw in this Potentiometer script?

My understanding of this loop is, if the prior reading of the pot is not = to or +/- 1 of the current pot reading, then there must have been a change, so send the midi command and update the last value read.

However, all I get is a constant stream of midi signals all with the current pot value.

Where is my logic wrong?

edit: I realized it right after I posted it... I suppose I am continuously setting lastPotValue to 0 therefore triggering my if statement every loop. I moved it to global and it appears to work now :slight_smile:

#include <frequencyToNote.h>
#include <MIDIUSB.h>
#include <pitchToFrequency.h>
#include <pitchToNote.h>

// First parameter is the event type (0x0B = control change).
// Second parameter is the event type, combined with the channel.
// Third parameter is the control number number (0-119).
// Fourth parameter is the control value (0-127).
// controlChange(0, 10, 65); // Set the value of controller 10 on channel 0 to 65

void controlChange(byte channel, byte control, byte value) {
  midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
  MidiUSB.sendMIDI(event);
}



void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  int lastPotValue;
  int potValue = analogRead(A0);

  if (lastPotValue != potValue && lastPotValue != potValue +1 && lastPotValue != potValue -1){
    controlChange(0, 50, potValue);
    lastPotValue = potValue;
  }

}

That's because you've declared lastPotValue inside loop(). So every time it loops round it creates a new version losing any value you'd previously put in it. Move the "int lastPotValue;" up so it's outside any function definition.

Steve

Aimbit:
I am continuously setting lastPotValue to 0 therefore triggering my if statement every loop.

It was not set to 0 but to an arbitrary value.

You could have made it static instead of global.

Whandall:
It was not set to 0 but to an arbitrary value.

You could have made it static instead of global.

hmm, I never learned static. I will check it out, thanks