Finn Quicke / Mbed 2 deprecated Basic_recursive_osc_synth

Dependencies:   mbed

main.cpp

Committer:
quickeman
Date:
2020-01-08
Revision:
0:d0c08e2c4315

File content as of revision 0:d0c08e2c4315:

#include "mbed.h"
#include "math.h"

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

AnalogIn pitchIn(p20);
AnalogIn levelIn(p19);
AnalogOut output(p18);
DigitalIn switchIn(p21);
DigitalOut led(LED1);

Ticker takePitch;
Ticker takeLevel;
Ticker outputSig;

float pitch;
float level;
float freqNorm;

// Recursive oscillator variables
float y;
float y_n1;
float y_n2;
float outSig;

void initOsc() {
    // Initialise values of recursive oscillator variables
    y = 0;
    y_n1 = sin(2 * M_PI * (1 - freqNorm));
    y_n2 = sin(2 * M_PI * (1 - (2 * freqNorm)));
}

// Flag variables
bool flag1 = 0;
bool flag2 = 0;

void getPitch() {
    // Read in relative pitch value
    pitch = pitchIn.read();
    flag2 = 1;
}

float getNormFreq(float freq, float max, float sampRate) {
    // Returns the normalised frequency for given input
    // freq: input frequency/pitch 0-1
    // max: maximum pitch defined in Hz
    // sampRate: sample rate in Hz
    float normFreq = freq * (max / sampRate);
    return normFreq;
}

void getLevel() {
    // Read in desired output level
    level = levelIn.read();
}

void genNext() {
    // Recursive oscillator
    y = (2 * cos(2 * M_PI * freqNorm) * y_n1) - y_n2;
    y_n2 = y_n1;
    y_n1 = y;
}

void outputSignal() {
    // Output signal
    output.write(outSig);
    flag1 = 1;
}

int main() {
    float sampFreq = 48000.0; // Hz
    float sampTime = 1.0 / sampFreq; // s
    float pitchMax = 9600.0; // Hz
    
    getPitch();
    freqNorm = getNormFreq(pitch, pitchMax, sampFreq);
    flag2 = 0;
    getLevel();
    
    initOsc();

    takePitch.attach(&getPitch, 0.1);
    takeLevel.attach(&getLevel, 0.1);
    outputSig.attach(&outputSignal, sampTime);
    
    while(1) {
        if(flag1) {
            genNext();
            if (switchIn.read()) {
                outSig = (level * y) / 33.0;
            } else {
                outSig = level * y;
            }
            flag1 = 0;
        }
        if(flag2){
            freqNorm = getNormFreq(pitch, pitchMax, sampFreq);
            flag2 = 0;
        }
        led = switchIn;
    }
}