// EMTronic 2020

//Hardware connections:

//                    +10µF
//PIN 11 ---[ 1k ]--+---||--->> Audio out
//                  |
//                 === 10nF
//                  |
//                 GND


#include <synth.h>

synth emSynth;    //-Make a synth

//------ Pins -------
const int wavePin = 3;      //  this is the pin for the push button
const int outputGndPin = 7; //  this is a little cheat to get a gnd pin where we want it
const int ledPin = 13;
//-------------------

//------ Vars -------
int waveState = 0;      //  has the button been pressed
int waveMode = 0;       //  what waveform are we playing
//-------------------

void setup() {
  //Serial.begin(9600);

  pinMode(outputGndPin, OUTPUT);    //set our sneaky gnd pin as an output
  pinMode(wavePin, INPUT_PULLUP);   //setup our mode pin
  pinMode(ledPin, OUTPUT);    //set our led pin pin as an output
  digitalWrite(outputGndPin, LOW);   //set the gnd pin to LOW

  emSynth.begin();                                   //   Start up the em synth
  emSynth.setupVoice(0, SINE, 60, ENVELOPE1, 10, 64); //  first waveform setup

}

void loop()
{
  digitalWrite(ledPin, HIGH);   //turn led on
  int modValue = analogRead(A0);          //read the frequency value of the pot on A0
  int freqValue = analogRead(A1);         //read the modulation value of the pot on A1

  emSynth.setFrequency(0, freqValue);   //  set the freqency with the value of the pot
  emSynth.trigger(0);   //  trigger the output
  modValue = map(modValue, 0, 1024, 0, 100);  //  we don't want a big delay value so reduce it to 0 to 100
  digitalWrite(ledPin, LOW);    // turn led off
  delay(modValue);    // this chucks in a delay between the times we turn the waveform on

  //Serial.println(waveMode);

  waveState = digitalRead(wavePin); //  read the digital pin 3
  if (waveState == LOW) {       //  if the botton has been pressed do this stuff
    waveMode++;       //  move the the next mode
    delay(500);       //  debounce so we don;t keep adding to wavemode

    if (waveMode > 5) {       //  if we get past the noise waveform form reset to the sine waveform
      waveMode = 0;
    }

    // here we check for the different modes and change the waveform
    if (waveMode == 0) {
      emSynth.setupVoice(0, SINE, 60, ENVELOPE1, 10, 64); //-Set up voice sine wave
    }
    else if (waveMode == 1) {
      emSynth.setupVoice(0, SQUARE, 60, ENVELOPE1, 10, 64); //-Set up voice square wave
    }
    else if (waveMode == 2) {
      emSynth.setupVoice(0, TRIANGLE, 60, ENVELOPE1, 10, 64); //-Set up voice triangle wave
    }
    else if (waveMode == 3) {
      emSynth.setupVoice(0, SAW, 60, ENVELOPE1, 10, 64); //-Set up voice saw tooth wave
    }
    else if (waveMode == 4) {
      emSynth.setupVoice(0, RAMP, 60, ENVELOPE1, 10, 64); //-Set up voice ramp wave
    }
    else if (waveMode == 5) {
      emSynth.setupVoice(0, NOISE, 60, ENVELOPE1, 10, 64); //-Set up voice noise wave
    }

  }
}
