Push button to MIDI note... note-off being send constantly.

Hi, I've been building a MIDI controller with a Mega 2560. I have all of my analogue controls working nicely but now am having trouble getting my digital push buttons to behave correctly. For some reason it sends repeated note-off messages to ableton constantly until the button is pressed and then stops sending at all until the button is released when it starts sending note-off again. I have tried quite a few ways to stop this happeneing but none have seemed to work.

Here is my code: -

#include <MIDI.h>
#include <midi_Defs.h>
#include <midi_Message.h>
#include <midi_Namespace.h>
#include <midi_Settings.h>
MIDI_CREATE_DEFAULT_INSTANCE();


const int  buttonPin = 3;    // the pin that the pushbutton is attached to

int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  // initialize the button pin as an input:
  pinMode(buttonPin, INPUT);
  // begin MIDI communication:
  MIDI.begin(4);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state:
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      MIDI.sendNoteOn(67, 127, 1);
  lastButtonState = buttonState;
  }
      else if (buttonState != lastButtonState) {
        if (buttonState == LOW);
          MIDI.sendNoteOff(67, 0, 1);
  lastButtonState = buttonState;  
  }
  }
}

As you can see I have used if statements to specify when messages should be sent but I'm obviously missing something.

Thanks in advance for any help

You have probably got the button wired so that when you push it, it is grounded which means that you should be looking for "buttonState == LOW".
Also, if you aren't using an external pullup resistor, it helps to define the pinMode as INPUT_PULLUP so that the pin isn't floating when it isn't pushed.
If this doesn't fix it, describe exactly how you have wired up the button.

Pete

at the moment I have one leg of the button wired to ground and one wired to digital pin 3. That is it.

one second... I think what u said about declaring 'PULL-UP' Might have done it... or so it looks like on the onboard LED.

Give me a minute or so to test it in Ableton... I'll let you know how it goes shortly.

okay it's almost working. Only now it's sending note.on when i let go and note.off when i press it. So it's inverted. I'm guessing it has something to do with what you said: -

"You have probably got the button wired so that when you push it, it is grounded which means that you should be looking for "buttonState == LOW"."

How can I change this? There is only two pins on the button. I've tried switching them but it has no effect?

Thank A LOT for your help.

Okay... I've managed to get it working correctly now. Thanks very much you've been very helpful :slight_smile:

You're very welcome :slight_smile: