#include "mbed.h"
#include "I2S.h"
#include "Amp_Init_Lib.h"
Ticker sampletick;
DigitalOut myled(LED1);
//Plays Audio Clip using Array in Flash
//using I2S input Class D audio amp
//setup const array in flash with audio values
//from free wav file conversion tool at
//http://ccgi.cjseymour.plus.com/wavtocode/wavtocode.htm
//see https://os.mbed.com/users/4180_1/notebook/using-flash-to-play-audio-clips/
//tested on MAX98357A
#include "Misty.h"
#define sample_freq 44100.0

I2S i2s(I2S_TRANSMIT, p5, p6, p7);
//p5(PWM value sent as serial data bit) <-> Din
//p6(WS) <-> LRC left/right channel clock
//p7(bit clock) <-> BCLK
int addr8 = 0x94; //AMP ADDRESS
DigitalOut SHDNZ(p20); //idk just pick a pin NEED TO KEEP ADC OFF UNTIL A PERIOD OF TIME AFTER SUPPLIES ARE ON!
DigitalOut RESET_AMP(p21);
DigitalOut DAC_RESET(p19);
AnalogIn ADC(p15);
int addr9 = 0x98; //ADC ADDRESS
I2C i2c(p9, p10);   
Serial pc(USBTX, USBRX);         

float freq = 2000.0; //in Hz
int8_t sineData[22050];
int i = 0;
int j = 0;
int bufflen = 1;
int buffer[1];
int temp0;
float temp1;
void isr()
{
    
//    if(j==3)
    {
//        j=0;
//        temp1 = ADC.read();
//        temp0 = temp1*32767.0;
//        i2s.write(&temp0, 1);
    }
//    else
//    {
//        i2s.write(&temp0, 2);
//        j++;
//    }

//
//    if(j ==3){
//        j = 0;
        buffer[0] = sound_data[i];//scale down volume a bit on amp
        i2s.write(buffer, bufflen);//Send next PWM value to amp
        i++;
        if (i>= NUM_ELEMENTS) {
            i = 0;
            sampletick.detach();
            i2s.stop();
            myled = 0;
        }
//    }
//    else
//    {
//        buffer[0] = sound_data[i]>>1;//scale down volume a bit on amp
//        i2s.write(buffer, bufflen);//Send next PWM value to amp
//        j++;
//    }
    
}

//the format is 2's compliment!
long total = 0;
int temp;
void isr_sine(void)
{
    if(++i == (int)sample_freq)
    {
        i =0;
        //pc.printf("%d", total);
    }
    temp = sineData[i]<<8;
    i2s.write(&temp,1);
    total+= sineData[i];
}

int main()
{
//    for(i=0; i<(int)(sample_freq/2); i++)
//    {
//        sineData[i] = (int8_t)(128.0*sin((((float)i)*3.14159*2.0/sample_freq)*freq));
//    }

    i2s.stereomono(I2S_MONO);
    i2s.masterslave(I2S_MASTER);
    i2s.frequency(sample_freq);
    i2s.wordsize(16);
    i2s.start();
    sampletick.attach(&isr, 1.0/sample_freq);//turn on timer interrupt


    pc.printf("*************************\nSTART\n*************************\n");
    amp_init();
    pc.printf("\n");
    
    while(1) {
        i2s.start();
        myled = 1;
        sampletick.attach(&isr, 1.0/sample_freq);//turn on timer interrupt
        wait(2.5);
    }    
}
