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

main.cpp

Committer:
MikamiUitOpen
Date:
2014-11-12
Revision:
2:a19243a20882
Parent:
0:b26f86125165
Child:
4:7635c95836a0

File content as of revision 2:a19243a20882:

//--------------------------------------------------------------
// 移動平均, 平均数:1, 2, 4, 8, 16, 32, 64:スイッチで選択
// スイッチの状態を printf() で表示する
//      Analog Input : A0
//      Analog Output: MCP4922 using SPI
// 2014/11/12, Copyright (c) 2014 MIKAMI, Naoki
//--------------------------------------------------------------

#include "mbed.h"

#include "ADC_Interrupt.hpp"    // for ADC using interrupt
#include "DAC_MCP4922.hpp"      // for DAC MCP4922

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()
{
    myDac_.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);
    }
}