In: Computer Science
Write C code that contains a function called triangle_generator that outputs a triangle wave at a specified frequency (in hertz) using a specified sample rate (in hertz), and for a specified time duration (in seconds). These parameters are float type. The output you generate are floating point numbers between -1 and 1, one number per output line. The math trig functions in C use radians while all the specifications here are in hertz (cycles per second). One hertz is 2*Pi radians.
The required answer is given below in case of any doubts you can ask me in comments.
Explanation:
main.c
#include<stdio.h>
#include<math.h>
// prototype
float triangle_generator(float frequency, float sample_rate, float timeDuration);
// driver function.
int main()
{
// variable declaration
float frequency, sampleRate, timeDuration;
// To take inputs from the user
printf("Enter Frequency, Sample Rate and Time separated by space:\n");
scanf("%f%f%f",&frequency, &sampleRate, &timeDuration);
// getting value.
float res = triangle_generator(frequency, sampleRate, timeDuration);
// Displaying value.
printf("Result = %f", res);
return 0;
}
// Function for finding the sin value
float triangle_generator(float freq, float sampleRate, float timeDuration)
{
float temp = sampleRate/freq; // cycles per second
float x = sin((2*3.1414)/temp*timeDuration);
return x;
}
Output: