![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Cricket (insect) emulation
Fork of talking by
Diff: cricket.cpp
- Revision:
- 2:c6c74e788985
- Parent:
- 1:91104d67b0af
- Child:
- 3:1b91d910dabd
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/cricket.cpp Sat Feb 11 15:45:54 2017 +0000 @@ -0,0 +1,81 @@ +#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"; + + +bool done = false; + + +void myrhythm() +{ + done = true; +} + +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(); + } +} + +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% percentage to wait 2 sec + if (c > 70) + { + wait(2); + } + // 70% percentage to wait 0-1 sec + else + { + wait(c / 100); + } +}