SHARE
TWEET

Untitled

a guest Jul 15th, 2019 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <math.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5. #include <string.h>
  6. #include <time.h>
  7.  
  8. #define BUF_SIZE 1211
  9.  
  10. static int16_t buf[BUF_SIZE];
  11. static const int16_t a_sin = 2048;
  12. static const int fs = 200e3;        /* sampling rate, samples/sec */
  13. static const int16_t dc = 100;
  14. static const double k_sin_avg = 0.637;  /* A_avg/A_peak for sine wave */
  15.  
  16. /**
  17.  * Calculate the magnitude of sine wave signal (generated internally).
  18.  *
  19.  * @param f_sin Sine wave frequency, Hz
  20.  * @param theta Start phase, radians
  21.  *
  22.  * @return Calculated A_peak
  23.  */
  24. int calc(int f_sin, double theta)
  25. {
  26.     size_t n;
  27.     double sum = 0;
  28.     double ppp;         /* points per period */
  29.     double fp;          /* full periods in buffer */
  30.     size_t poi;         /* number of points of interest */
  31.     int a_avg, a_peak;
  32.  
  33.     for (n = 0; n < BUF_SIZE; ++n)
  34.         buf[n] = dc + a_sin * (1 + sin(2*M_PI*f_sin/fs * n + theta));
  35.  
  36.     /* Remove DC component first (using MEAN_BUF in fw) */
  37.     for (n = 0; n < BUF_SIZE; ++n)
  38.         buf[n] -= dc + a_sin;
  39.  
  40.     /* Calculate samples number for whole periods in the buffer */
  41.     ppp = fs/f_sin;
  42.     fp = floor((double)BUF_SIZE / ppp);
  43.     poi = round(fp * ppp);
  44.  
  45.     /* Calculate the average and peak magnitude */
  46.     for (n = 0; n < poi; ++n)
  47.         sum += abs(buf[n]);
  48.     a_avg = round(sum / poi);
  49.     a_peak = round(a_avg / k_sin_avg);
  50.  
  51.     return a_peak;
  52. }
  53.  
  54. int main(void)
  55. {
  56.     int f;
  57.  
  58.     srand(time(0));
  59.     for (f = 3000; f < 20000; ++f) {
  60.         int a_peak;
  61.         double err;
  62.  
  63.         a_peak = calc(f, rand());
  64.         err = fabs(a_sin - a_peak) / a_sin * 100;
  65.         if (err >= 1)
  66.             printf("%d,%f\n", f, err);
  67.     }
  68.  
  69.     return EXIT_SUCCESS;
  70. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top