波形发生器程序
时间: 2023-07-16 12:16:42 浏览: 35
以下是一个简单的波形发生器程序,可以生成正弦波、方波、三角波和锯齿波等不同类型的波形:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846
int main()
{
int type, freq, amplitude, duration, sample_rate;
double phase = 0.0, delta_phase, sample, t;
FILE *fp;
printf("Waveform Generator\n\n");
printf("Select waveform type:\n");
printf("1. Sine wave\n");
printf("2. Square wave\n");
printf("3. Triangle wave\n");
printf("4. Sawtooth wave\n");
printf("Enter selection: ");
scanf("%d", &type);
printf("Enter frequency (Hz): ");
scanf("%d", &freq);
printf("Enter amplitude: ");
scanf("%d", &litude);
printf("Enter duration (s): ");
scanf("%d", &duration);
printf("Enter sample rate (Hz): ");
scanf("%d", &sample_rate);
fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Error opening output file.\n");
exit(1);
}
delta_phase = 2.0 * PI * freq / sample_rate;
for (int i = 0; i < duration * sample_rate; i++) {
t = (double)i / sample_rate;
switch (type) {
case 1:
sample = amplitude * sin(2.0 * PI * freq * t + phase);
break;
case 2:
sample = amplitude * (sin(2.0 * PI * freq * t + phase) >= 0 ? 1.0 : -1.0);
break;
case 3:
sample = amplitude * (2.0 / PI) * asin(sin(2.0 * PI * freq * t + phase));
break;
case 4:
sample = amplitude * ((2.0 * freq * t + phase) - floor(2.0 * freq * t + phase + 0.5));
break;
default:
printf("Invalid selection.\n");
exit(1);
}
fprintf(fp, "%f\n", sample);
phase += delta_phase;
if (phase >= 2.0 * PI) {
phase -= 2.0 * PI;
}
}
fclose(fp);
printf("Waveform generated and saved to output.txt.\n");
return 0;
}
```
该程序通过读取用户输入的参数,利用数学公式生成不同类型的波形,并将波形样本写入输出文件中。可以通过修改程序中的参数来生成不同类型、不同频率、不同振幅和不同时长的波形,并保存到不同的输出文件中。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)