![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Moving average using interrupt for ST Nucleo F401RE. The number of average is controled by sw. This program displays the number of average on LCD device connected by I2C.
Dependencies: UITDSP_ADDA mbed UIT_ACM1602NI UIT_AQM1602
Diff: main.cpp
- Revision:
- 0:b26f86125165
- Child:
- 2:a19243a20882
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Thu Oct 30 00:38:14 2014 +0000 @@ -0,0 +1,64 @@ +//-------------------------------------------------------------- +// 移動平均, 平均数:1, 2, 4, 8, 16, 32, 64:スイッチで選択 +// スイッチの状態を printf() で表示する +// Analog Input : A0 +// Analog Output: MCP4922 using SPI +// 2014/10/30, Copyright (c) 2014 MIKAMI, Naoki +//-------------------------------------------------------------- + +#include "mbed.h" + +#include "ADC_Interrupt.hpp" // for ADC using interrupt +#include "DAC_MCP4922.hpp" // for DAC MCP4922 +#include "ScfClockTim3.hpp" // for clock supplied to SCF + +using namespace Mikami; + +const int FS_ = 12000; // Sampling frequency: 12 kHz +ADC_Intr adc_(A0, FS_); // for AD using interrupt +DAC_MCP4922 myDac_; // for DA + +DigitalIn sw1_(D2, PullDown); +DigitalIn sw2_(D3, PullDown); +DigitalIn sw4_(D4, PullDown); +DigitalIn sw8_(D5, PullDown); + +const int M_ = 64; // Maximum of average count +float xn_[M_]; +volatile int nAv_; // "volatile": to make sure + +// Interrupt service routine for ADC +void AdcIsr() +{ + xn_[0] = adc_.Read(); // Read from A0 + //----------------------------------------------- + + float yn = 0; + for (int k=0; k<nAv_; k++) yn = yn + xn_[k]; + yn = yn/(float)nAv_; // yn: average + + // Update input buffer + for (int k = nAv_-1; k>0; k--) + xn_[k] = xn_[k-1]; + + //----------------------------------------------- + myDac_.Write(yn); // Write to DAC +} + +int main() +{ + ScfClockTim3(500000); // cutoff frequency: 5 kHz + adc_.SetIntrVec(AdcIsr); // Assign ISR for ADC interrupt + + for (int n=0; n<M_; n++) xn_[n] = 0; + + while (true) + { + int sw = (sw8_ << 3) | (sw4_ << 2) | (sw2_ << 1) | sw1_; + nAv_ = 1 << sw; + if (nAv_ > 64) nAv_ = 64; + printf("\r\nnAv = %d, sw = %d", nAv_, sw); + + wait(0.5f); + } +}