Skip to content

Instantly share code, notes, and snippets.

@smotesko
Created February 14, 2017 12:54
Show Gist options
  • Save smotesko/fdf003fde8a6a6979c4081b1315bbf13 to your computer and use it in GitHub Desktop.
Save smotesko/fdf003fde8a6a6979c4081b1315bbf13 to your computer and use it in GitHub Desktop.
Generate sine wave
#include <stdio.h>
#include <math.h>
#define NUMBER_OF_SAMPLES 4410 // for 44100 Hz sample rate and 10Hz min f.
#define MAX_VALUE 0xFFFFFF // 24-bit samples
#define MID_VALUE (MAX_VALUE/2)
#define DC_OFFSET (MID_VALUE) // set to 0 for no offset
// Generates a wavetable (a single wavecycle) of a sine wave.
// compile: gcc -o generate-sine generate-sine.c
// usage: ./generate-sine | gnuplot > sine.png
int main(int argc, char *argv[])
{
unsigned int i;
float pi=3.141592;
float phase=0.0;
long int y;
float w;
long int sample;
// gnuplot header
printf("set terminal png size 4096, 2160\n");
printf("plot '-'\n");
w=2*pi;
w/=NUMBER_OF_SAMPLES;
for (i=0; i<NUMBER_OF_SAMPLES; i++) {
y=MID_VALUE*sin(phase);
phase+=w;
sample=y+DC_OFFSET;
printf("%ld\n", sample);
}
// gnuplot end
printf("e\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment