The experiment using this program is introduced on "Interface" No.4, CQ publishing Co.,Ltd, 2015. 本プログラムを使った実験は,CQ出版社のインターフェース 2015年4月号で紹介しています.

Dependencies:   DSProcessingIO mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers FFT_Sampling.cpp Source File

FFT_Sampling.cpp

00001 //--------------------------------------------------------------
00002 // Sampling and Spectrum analysis using FFT
00003 // Copyright (c) 2014 MIKAMI, Naoki,  2014/06/29 
00004 //--------------------------------------------------------------
00005 
00006 #include "mbed.h"
00007 #include "AdcInternal.hpp"
00008 #include "fftReal.hpp"
00009 
00010 using namespace Mikami;
00011 
00012 // sampling frequency
00013 const float FS_ = 10.0e3f;
00014 const int N_FFT_ = 256;
00015 
00016 Adc adc_(A0);
00017 Ticker timer_;      // for timer interrupt
00018 DigitalIn userButton_(USER_BUTTON);
00019 FftReal fft_(N_FFT_);
00020 
00021 float xn_[N_FFT_+1];
00022 volatile int count_;
00023 
00024 // Sampling
00025 void TimerIsr()
00026 {
00027     xn_[count_] = adc_.Read();  // AD
00028     count_++;
00029 }
00030 
00031 int main()
00032 {
00033     printf("Ready.\r\n");
00034     while(userButton_);     // wait for user button pressed
00035     printf("User button is pushed!\r\n");
00036 
00037     count_ = 0;
00038     timer_.attach_us(&TimerIsr, 1.0e6f/FS_);
00039     while (count_ < N_FFT_+1);
00040     timer_.detach();        // Detach TimerIsr
00041     printf("End of Sampling.\r\n");
00042 
00043     float xnW[N_FFT_];      // for windowed data
00044     Complex yk[N_FFT_/2+1];
00045     float yDb[N_FFT_/2+1];
00046     
00047     // Windowing
00048     float pi2N = 6.283185f/N_FFT_;
00049     for (int n=0; n<N_FFT_; n++)
00050         xnW[n] = (xn_[n+1] - xn_[n])*(0.54f - 0.46f*cosf(pi2N*n));
00051         
00052     // Execute FFT
00053     fft_.Execute(xnW, yk);
00054     
00055     // Square of absolute value of FFT
00056     for (int n=0; n<=N_FFT_/2; n++)
00057         yDb[n] = norm(yk[n]);
00058         
00059     // Get maximum value of yk[n]
00060     float max = 0;
00061     for (int n=0; n<=N_FFT_/2; n++)
00062         max = (yDb[n] > max) ? yDb[n] : max;
00063         
00064     // Normalized spectra to dB
00065     for (int n=0; n<=N_FFT_/2; n++)
00066         if (yDb[n] > 0)
00067             yDb[n] = 10.0f*log10f(yDb[n]/max);
00068         else
00069             yDb[n] = -100.0f;
00070 
00071     // Output to terminal
00072     float dt = 1.0e3f/FS_;
00073     float df = FS_/N_FFT_;
00074     for (int n=0; n<N_FFT_; n++)
00075     {
00076         if (n <= N_FFT_/2)
00077             printf("%3d, %4.1f,%8.4f, %10.4f,%6.1f\r\n",
00078                    n, n*dt, xn_[n], n*df, yDb[n]);
00079         else
00080             printf("%3d, %4.1f,%8.4f\r\n", n, n*dt, xn_[n]);
00081     }
00082 }
00083