Skip to content

Instantly share code, notes, and snippets.

@linneman
Created June 28, 2016 20:23
Show Gist options
  • Select an option

  • Save linneman/c3c703a9e1db78b4baeeb338f71431d9 to your computer and use it in GitHub Desktop.

Select an option

Save linneman/c3c703a9e1db78b4baeeb338f71431d9 to your computer and use it in GitHub Desktop.
/*
sine wave generator using IIR filter
taken from: http://home.anadolu.edu.tr/~sgorgulu/dsphw/Lab2/Lab2.pdf
2016 OL
*/
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static double update( const double y1, const double y2, const double x0,
const double a1, const double a2, const double b0 )
{
return -a1 * y1 -a2 * y2 + b0 * x0;
}
void sine( const double fs, const double f0, const double amp, const int out_len, int16_t* out)
{
const double w0 = 2 * M_PI * f0/fs;
const double a1 = -2 * cos(w0);
const double a2 = 1.0;
const double b0 = amp * sin(w0);
double y0 = 0, y1 = 0, x0 = 1.0, y2;
int cnt = 0;
for( cnt=0; cnt < out_len; ++ cnt ) {
y0 = update( y1, y2, (cnt==0) ? x0 : 0.0, a1, a2, b0 );
y2 = y1;
y1 = y0;
// printf( "%lf\n", y0 );
out[cnt] = (int16_t) ( 32767 * y0 );
}
}
int main()
{
const char* filename = "test.raw";
const int nr_samples = 60 * 48000;
int16_t out[nr_samples];
FILE* fp;
fp = fopen( filename, "w" );
if( fp == NULL ) {
fprintf( stderr, "could not open file %s\n", filename );
return -1;
}
sine( 48000, 440, 0.3, nr_samples, out );
fwrite( out, sizeof(int16_t), nr_samples, fp );
fclose( fp );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment