#include <SoftwareSerial.h>
#include <MIDI.h>
// Pin-Definitionen
const int button1Pin = 2;
const int button2Pin = 3;
const int potPin = A0;
const int midiTxPin = 6;
const int led1Pin = 8;  // LED für Button 1
const int led2Pin = 9;  // LED für Button 2
// MIDI-Konstanten
const byte midiChannel1 = 1;
const byte midiChannel2 = 2;
const byte ccButton1 = 36;
const byte ccButton2 = 37;
const byte ccPot = 31;
// MIDI via SoftwareSerial
SoftwareSerial midiSerial(-1, midiTxPin); // RX, TX
MIDI_CREATE_INSTANCE(SoftwareSerial, midiSerial, MIDI_OUT);
// Entprell-Zeit
const unsigned long debounceDelay = 50; // in Millisekunden
// Taster 1
bool button1StableState = HIGH;
bool button1LastRead = HIGH;
unsigned long button1LastChangeTime = 0;
// Taster 2
bool button2StableState = HIGH;
bool button2LastRead = HIGH;
unsigned long button2LastChangeTime = 0;
// Poti
int lastCCValuePot = -1;
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  midiSerial.begin(31250); // MIDI-Standard Baudrate
  MIDI_OUT.begin(MIDI_CHANNEL_OMNI);
}
void loop() {
  unsigned long currentTime = millis();
  // === Taster 1 mit Entprellung ===
  bool currentRead1 = digitalRead(button1Pin);
  if (currentRead1 != button1LastRead) {
    button1LastChangeTime = currentTime;
    button1LastRead = currentRead1;
  }
  if ((currentTime - button1LastChangeTime) > debounceDelay && currentRead1 != button1StableState) {
    button1StableState = currentRead1;
    if (button1StableState == LOW) {
      MIDI_OUT.sendControlChange(ccButton1, 127, midiChannel2);
      digitalWrite(led1Pin, HIGH); // LED1 an
    } else {
      MIDI_OUT.sendControlChange(ccButton1, 0, midiChannel2);
      digitalWrite(led1Pin, LOW);  // LED1 aus
    }
  }
  // === Taster 2 mit Entprellung ===
  bool currentRead2 = digitalRead(button2Pin);
  if (currentRead2 != button2LastRead) {
    button2LastChangeTime = currentTime;
    button2LastRead = currentRead2;
  }
  if ((currentTime - button2LastChangeTime) > debounceDelay && currentRead2 != button2StableState) {
    button2StableState = currentRead2;
    if (button2StableState == LOW) {
      MIDI_OUT.sendControlChange(ccButton2, 127, midiChannel2);
      digitalWrite(led2Pin, HIGH); // LED2 an
    } else {
      MIDI_OUT.sendControlChange(ccButton2, 0, midiChannel2);
      digitalWrite(led2Pin, LOW);  // LED2 aus
    }
  }
  // === Potentiometer lesen und MIDI CC senden ===
  int potValue = analogRead(potPin);
  int ccValuePot = map(potValue, 0, 1023, 0, 127);
  if (ccValuePot != lastCCValuePot) {
    MIDI_OUT.sendControlChange(ccPot, ccValuePot, midiChannel1);
    lastCCValuePot = ccValuePot;
  }
}