

// MIDI üzeneteket olvas a billentyűzetről, majd elküldi a hanggenerátornak
#include <MIDI.h>
#include <SN76489.h> //This is an SN76489 C++ library for Arduino 0004+ by Kobi Tyrkel, based on one created by Nicholas Zambetti for Wiring 0006+ 
#include "Pitches.h"
//LiquidCrystal_I2C lcd(0x3F, 16, 2); // LCD address 0x27, 20 chars and 4 line display
MIDI_CREATE_DEFAULT_INSTANCE();
#define PIN_NotWE 2   // SN 76489 WE láb
#define FREQUENCY 1843200.0    //#define FREQUENCY 4000000.0 Define FREQUENCY according to the frequency in your hardware setup

#define PIN_D0 11   // Az IC lábai
#define PIN_D1 12
#define PIN_D2 A5
#define PIN_D3 A4
#define PIN_D4 A3
#define PIN_D5 A2
#define PIN_D6 A1
#define PIN_D7 A0
SN76489 mySN76489 = SN76489(PIN_NotWE, PIN_D0, PIN_D1, PIN_D2, PIN_D3, PIN_D4, PIN_D5, PIN_D6, PIN_D7, FREQUENCY);
int type, noteMsg, velocity, channel, modulation, d2, i;
#define gate 13   //  kapuzó kimenet

void setup() {
  MIDI.begin(MIDI_CHANNEL_OMNI);
  pinMode(gate, OUTPUT);
  mySN76489.setAttenuation(0, 0xF);
  mySN76489.setAttenuation(1, 0xF);
  mySN76489.setAttenuation(2, 0xF);
  mySN76489.setAttenuation(3, 0xF); // Zaj? nem működik még
  csipp();
  digitalWrite(gate, LOW);
}

void loop() {
  if (MIDI.read()) {
    byte type = MIDI.getType();   // 
    if (type == midi::PitchBend) {
      d2 = MIDI.getData2();       // d2 from 0 to 127, mid point = 64
      mySN76489.setFrequency(0, (MIDItoF[noteMsg - 36]) + d2 - 64);
    }
    if (type == midi::ControlChange) {    // a modulációs kerék olvasása
      modulation = MIDI.getData2();       // mod: from 0 to 127,
    }
    if (type == midi::NoteOff) {          // Billentyű felengedése esetén
      digitalWrite(gate, LOW);
      for (i = 0; i < 16; i++) {          // Lecsengése. Ha külső ADSR-t használunk, akkor ez a for ciklus törlendő!
        mySN76489.setAttenuation(0, i);   // csitu:  mySN76489.setAttenuation(0, 0xF); 
        delay(modulation / 8);            // a modulációs keréknek megfelelő értékkel
      }
    }
    if (type == midi::NoteOn) {           // Billentyű lenyomása esetén
      noteMsg = MIDI.getData1();          // hangjegyek: 36d-96d 
      mySN76489.setAttenuation(0, 0x0);   // hang bekapcs
      mySN76489.setFrequency(0, (MIDItoF[noteMsg - 36])); // PitchBend: (MIDItoF[noteMsg-36])+d2-64)
      digitalWrite(gate, HIGH);
    }
    if (type == midi::ModulationWheel) {  // nem tudom mi ez! 
    }
  }
}

void csipp() {
  mySN76489.setAttenuation(0, 0x0);   // hang bekapcs
  mySN76489.setFrequency(0, 1000);
  delay(100);
  mySN76489.setAttenuation(0, 0xF);   // hang bekapcs
}
