Audio demo

Dependencies:   mbed tsi_sensor

main.cpp

Committer:
acracan
Date:
2015-07-11
Revision:
0:ed8de6dbc531

File content as of revision 0:ed8de6dbc531:

#include "mbed.h"
#include "tsi_sensor.h"

/* This defines will be replaced by PinNames soon */
#if defined (TARGET_KL25Z) || defined (TARGET_KL46Z)
  #define ELEC0 9
  #define ELEC1 10
#elif defined (TARGET_KL05Z)
  #define ELEC0 9
  #define ELEC1 8
#else
  #error TARGET NOT DEFINED
#endif
Serial pc(USBTX, USBRX);
AnalogOut DAC(PTE30);
//global variables used by interrupt routine
const int SAMPLE_COUNT = 128;
float samples[SAMPLE_COUNT];
int sampleIdx = 0;
float period = 1.0e-3f;
Timer sensorTimer;
PwmOut player(PTE31);
TSIAnalogSlider tsi(ELEC0, ELEC1, 40);
float sliderValue = 0.0;
bool active = false;

void computeSamples();
void writeSample();

int main(void) {
    DAC = 0.0f;
    computeSamples();
    pc.printf("Hello World\n");
    player.period(period);
    player = 0.5f;
    TPM0->SC |= TPM_SC_TOIE_MASK;
    NVIC_SetVector(TPM0_IRQn, (uint32_t)&writeSample);
    NVIC_EnableIRQ(TPM0_IRQn);
    
    sensorTimer.start();
    writeSample();
    pc.printf("Hello again\n");
    while (true) {
        if (sensorTimer.read() > 100.0e-3f) {
            sliderValue = tsi.readPercentage();
            active = sliderValue > 0.0f ? true : false;
            period = pow(10.0f, 0.5f * (1.0f - sliderValue)) * 7.0e-6f;
            player.period(period);
            sensorTimer.reset();
        }
    }
}

void computeSamples()
{
    for(int k = 0; k < SAMPLE_COUNT; k++) {
        samples[k]=(1.0f + sin(float(k) / float(SAMPLE_COUNT) * 6.283185f)) * 0.5f;
    }
}

void writeSample()
{
    if (active) {
        sampleIdx = (sampleIdx + 1) % SAMPLE_COUNT;    
        DAC = samples[sampleIdx];
    }
    else {
        DAC = 0.5f;
    }
    TPM0->SC |= TPM_SC_TOF_MASK;
}