Arkadi Rafalovich
/
ADC_DAC
Microphone Record and play. using Nucleo STM32F303RE STM32 Hands On Makers Workshop
main.cpp
- Committer:
- STM32Workshop
- Date:
- 2015-11-11
- Revision:
- 0:ff0b6f6ddb23
- Child:
- 1:5f34e59f97f7
File content as of revision 0:ff0b6f6ddb23:
#include "mbed.h" // Serial pc(SERIAL_TX, SERIAL_RX); // for debbug // Peripherials DigitalIn mybutton(USER_BUTTON); DigitalOut myled(LED1); AnalogIn AudioIn(A0); AnalogOut AudioOut(A2); // Define Ticker Ticker Audio_Sample_Ticker; // Audio Buffer #define BUFFERSIZE 30000 // Sample rate 10 Khz, 3 sec record 30*10^3 samples uint16_t ABuffer[BUFFERSIZE]={0}; // variables to store buffer position and lenght uint32_t BufferEnd=0; uint32_t Buffer_i=0; bool RecordFull=0; // Variable to store button state bool ButtonState=0; bool LastButtonState=0; volatile bool Audio_Sample_Flag=0; // Filter sound HPF to remove dc for amplification // Simple First order filter float AudioSignal=0; float AHPF=0.99f; float LastY=0; float CurY=0; float LastU=0; float CurU=0; // Ticker function void Audio_Sample() { Audio_Sample_Flag=1;; } int main() { // setup loop // attach Ticker object Audio_Sample_Ticker.attach_us(&Audio_Sample, 100); // create 10Khz Ticker while(1) { // infinite loop if (Audio_Sample_Flag){ Audio_Sample_Flag=0; LastButtonState=ButtonState; ButtonState=mybutton.read(); // Record sample and apply filter // Buffer variables LastU=CurU; CurU=AudioIn.read(); LastY=CurY; // Simple Filter HPF CurY=AHPF*(LastY+CurU-LastU); // Amplify, add dc offset and add to buffer; AudioSignal=CurY*3.0f+0.5f;//*10.0f+0.5f); if (AudioSignal>1){ AudioSignal=1; }else if (AudioSignal<0){ AudioSignal=0; } if ((!ButtonState)&&(!RecordFull) ){ // Button is pressed and record is not full myled.write(1); // LED On if (LastButtonState){ // first sample Buffer_i=0; // Re-set Ticker object Audio_Sample_Ticker.attach_us(&Audio_Sample, 100); // create 10Khz Ticker } // Record samples //ABuffer[Buffer_i]=AudioIn.read_u16(); AudioSignal=AudioSignal*0xFFFF; // scale to 16 bit (aligned to left apparently, wasted an hour on that one) ABuffer[Buffer_i]=(uint16_t)AudioSignal; // Store to buffer; //pc.printf("%d \r\n",ABuffer[Buffer_i]); // debug check/ //AudioOut.write_u16(ABuffer[Buffer_i]); // Debug output BufferEnd=Buffer_i; Buffer_i++; if (Buffer_i==BUFFERSIZE){ // buffer full RecordFull=1; Buffer_i=0; myled.write(0); // LED Off // record off } }else if (ButtonState) { //Button is unpressed if (!LastButtonState){ // first sample // Re-set Ticker object Audio_Sample_Ticker.attach_us(&Audio_Sample, 75); // create 10Khz Ticker // Buffer_i=0; } myled.write(0); // LED Off // Play Recorded audio RecordFull=0; if (Buffer_i>BufferEnd){ // Replay record Buffer_i=0; } AudioOut.write_u16(ABuffer[Buffer_i]); Buffer_i++; } } } }