Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
microphone.cpp
00001 #include "Microphone.h" 00002 00003 bool _mic_toggle = false; 00004 uint8_t _mic_pulses= 0; 00005 uint8_t _mic_pulses_buffered = 0; 00006 uint8_t _mic_counter = 0; 00007 DigitalIn* _mic_d; 00008 DigitalOut* _mic_clk; 00009 00010 void _mic_timer_int() 00011 { 00012 // If clock output to mic is low, read data pin and increment 00013 // pulse count if it's high. 00014 if (!_mic_toggle) { 00015 _mic_counter += 1; 00016 if (_mic_counter == 0) { 00017 _mic_pulses_buffered = _mic_pulses; 00018 _mic_pulses = 0; 00019 } 00020 if (_mic_d->read()) _mic_pulses++; 00021 } 00022 00023 // Toggle clock output to mic 00024 _mic_toggle = !_mic_toggle; 00025 _mic_clk->write(_mic_toggle); 00026 00027 // Clear interrupt 00028 TIM3->SR &= ~TIM_SR_UIF; 00029 } 00030 00031 Microphone::Microphone() 00032 { 00033 this->isStarted = false; 00034 } 00035 00036 void Microphone::start() 00037 { 00038 if (!this->isStarted) { 00039 // Two pins: clock to microphone and data from microphone. 00040 _mic_d = new DigitalIn(PC_3); 00041 _mic_clk = new DigitalOut(PB_10); 00042 00043 // Use timer 3 to sample from the MP45DT02 microphone. 00044 00045 // Enable timer. 00046 RCC->APB1ENR |= RCC_APB1ENR_TIM3EN; 00047 00048 // Scale timer so ticks are 100ns 00049 uint32_t PCLK = SystemCoreClock / 4; 00050 uint32_t prescale = PCLK / 10000000; // 10Mhz (100ns ticks) 00051 TIM3->PSC = prescale - 1; 00052 00053 // Enable counter 00054 TIM3->CR1 |= TIM_CR1_CEN; 00055 00056 // Set auto-reset after five ticks (500ns). 00057 TIM3->ARR = 4; 00058 00059 // Re-initialize counter. 00060 TIM3->EGR |= TIM_EGR_UG; 00061 00062 // Set up and enable interrupt for when timer overflows. 00063 NVIC_SetVector(TIM3_IRQn, (uint32_t)_mic_timer_int); 00064 NVIC_EnableIRQ(TIM3_IRQn); 00065 TIM3->DIER |= TIM_DIER_UIE; 00066 this->isStarted = true; 00067 } 00068 } 00069 00070 void Microphone::stop() // Not tested! 00071 { 00072 if (this->isStarted) { 00073 // Disable interrupts. 00074 NVIC_SetVector(TIM3_IRQn, (uint32_t)_mic_timer_int); 00075 NVIC_DisableIRQ(TIM3_IRQn); 00076 TIM3->DIER &= ~TIM_DIER_UIE; 00077 00078 // Disable counter 00079 TIM3->CR1 &= ~TIM_CR1_CEN; 00080 00081 // Disable timer. 00082 RCC->APB1ENR &= ~RCC_APB1ENR_TIM3EN; 00083 00084 // Clear interrupt 00085 TIM3->SR &= ~TIM_SR_UIF; 00086 00087 delete _mic_d; _mic_d = NULL; 00088 delete _mic_clk; _mic_clk = NULL; 00089 } 00090 } 00091 00092 signed char Microphone::read() 00093 { 00094 if (this->isStarted) { 00095 return (int8_t)((uint16_t)_mic_pulses_buffered - 128); 00096 } else { 00097 return 0; 00098 } 00099 }
Generated on Wed Jul 13 2022 06:29:03 by
 1.7.2
 1.7.2