Cricket (insect) emulation

Dependencies:   mbed

Fork of talking by Sakis Kasampalis

cricket.cpp

Committer:
faif
Date:
2017-02-11
Revision:
3:1b91d910dabd
Parent:
2:c6c74e788985

File content as of revision 3:1b91d910dabd:

#include "mbed.h"
#include "cricket.h"

enum
{
    OFF = 0,
    ON = 1
};

enum { MaxWavValue = 255 };

static const float ticker_rhythm = 10E-5;  // 9.766 kHz sample rate (1/9766 sec delay)
static const char clip_path[] = "/local/cricket.wav";

int main () 
{
    const int size = 1165;   // 32K max in total (~30K is enough for testing)
    char clip[size];
    
    waitForButton(led, button);
    preloadFile(clip, size, clip_path);
    
    rhythm.attach(&myrhythm, ticker_rhythm);
    
    while (true)
    {        
        playSound(clip, size, headphones);
        randomPause();
    }
}

bool done = false;

void myrhythm()
{
    done = true;
}

void waitForButton(DigitalOut& led, DigitalIn& button)
{
  led = ON;
  while (!button) {};
  led = OFF;
}

void preloadFile(char* clip, int size, const char* path)
{
  FILE* file = fopen(path, "r");
  for (int i = 0; i != size; ++i)
  {
      clip[i] = fgetc(file);
  }
  fclose(file);
}

void playSound(char* clip, int size, AnalogOut& headphones)
{
    for (int i= 0; i != size; ++i) 
    {
        while (!done) {};
        done = false;
        headphones = float(clip[i]) / MaxWavValue;
    }
}

void randomPause()
{
    float c = rand() % 100;
    // 30% chance to wait 2 sec
    if (c > 70)
    {
        wait(2);
    }
    // 70% chance to wait 0-1 sec
    else
    {
        wait(c / 100);
    }
}