#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_ADS1015.h>
#include <NoodleSynth.h>
#include <SensorToButton.h> 
SensorToButton btn(2, 50);  //pin, debounce time(ms)
synthEngine mixer(20E3);
#define NUM 8   
MusicWithoutDelay instruments[NUM];
int vol = 0;
uint16_t INTERVAL = 15;
bool mode = true;
int flip = 1;
// int pins[6] = {CHA,CHB,6,9,22,23}; //for Teensy 3+
int pins[2] = {CHA,CHB};


//multiplex adresses
Adafruit_ADS1115 adsa (0x48);
Adafruit_ADS1115 adsb (0x49);
Adafruit_ADS1115 adsc (0x4A);
Adafruit_ADS1115 adsd (0x4B);

int count= 0;
int TH;
int16_t adc0a, adc1a, adc2a, adc3a, adc0b, adc1b, adc2b, adc3b, adc0c, adc1c, adc2c, adc3c, adc0d, adc1d, adc2d, adc3d;
boolean codeswitch = false;


void setup(){
      //set the gain for multiplexed ins
      adsa.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
      adsb.setGain(GAIN_ONE); 
      adsc.setGain(GAIN_ONE); 
      adsd.setGain(GAIN_ONE); 
      
      //start the multiplexing
      adsa.begin();
      adsb.begin();
      adsc.begin();
      adsd.begin();

for (byte i = 0; i < NUM; i++) {
    MusicWithoutDelay *myInstrument = &instruments[i];
    float freq = MusicWithoutDelay::getNoteAsFrequency(NOTE_A3 + i * 4);               //Function gives Frequceny using a Formula.  Every other 4 notes is a harmonic major(something like that)
    myInstrument->begin(pins[i%2], SINE, ENVELOPE0, 0).setVolume(0).setFrequency(freq);  //set up instruments and their frequencies

  }
    
      //set tone frequency and phase
//      tone_1.setFreq(165);
//      tone_1.setPhase(0);
//      tone_2.setFreq(196);
//      tone_2.setPhase(30);
//      tone_3.setFreq(220);
//      tone_3.setPhase(60);
//      tone_4.setFreq(262);
//      tone_4.setPhase(90);
//      tone_5.setFreq(330);
//      tone_5.setPhase(120);
//      tone_6.setFreq(392);
//      tone_6.setPhase(150);
//      tone_7.setFreq(440);
//      tone_7.setPhase(180);
//      tone_8.setFreq(523);
//      tone_8.setPhase(210);
//      tone_9.setFreq(659);
//      tone_9.setPhase(240);
//      tone_10.setFreq(784);
//      tone_10.setPhase(270);
//      tone_11.setFreq(880);
//      tone_11.setPhase(300);
//      tone_12.setFreq(1047);
//      tone_12.setPhase(330);
    
      //calibrate (set treshold)
      TH = adsb.readADC_SingleEnded(3);
}



uint32_t pMillis, serialMillis;
void loop(){
uint32_t cMillis = millis();
  btn.read();
  //  if (cMillis - serialMillis > 500) {
  for (byte i = 0; i < NUM; i++) {
    MusicWithoutDelay *myInstrument = &instruments[i];
    myInstrument->update().setVolume(vol);             //update instruments
  }
  //    serialMillis = cMillis;
  //  }
  if (mode) {
    vol = analogRead(potPin);
    vol = map(vol, 0, 1023, 0, 127);
  }
  else {
    if (cMillis - pMillis >= INTERVAL) {   //Vibrato
      vol += flip;
      if (vol < 90 || vol > 126) {
        flip *= -1;
      }
      pMillis = cMillis;
    }
  }
  if (btn.wasPressed()) {
    vol = 95;
    mode = !mode;
  }
}
