![](https://csdnimg.cn/release/download_crawler_static/88811985/bg1.jpg)
设计一个 Python 波形发生器通常涉及到使用 numpy 库来生成各种数学函数表示的波形数
据,然后利用 matplotlib 等可视化库进行绘制。以下是一个基本的设计步骤和代码示例,用
于创建一个能够生成正弦、三角和方波,并且具有可调幅度、频率及直流偏置的简单波形发
生器:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义波形类型选择函数
def generate_waveform(type='sine', amplitude=1.0, freq=1.0, dc_offset=0.0,
sampling_rate=1000, duration=1):
t = np.linspace(0, duration, int(sampling_rate * duration), endpoint=False)
if type == 'sine':
waveform = amplitude * np.sin(2 * np.pi * freq * t) + dc_offset
elif type == 'triangle':
n_periods = int(freq * duration)
periods = 2 * np.arange(n_periods) / n_periods - 1
waveform = amplitude * np.abs(periods - periods.astype(int)) + dc_offset
elif type == 'square':
duty_cycle = 0.5 # 默认占空比为 50%
waveform = amplitude * (np.sign(np.sin(2 * np.pi * freq * t)) + 1) / 2 + dc_offset
else:
raise ValueError("Unsupported waveform type. Choose from 'sine', 'triangle', or
'square'.")
return t, waveform
# 用户自定义参数
wave_type = 'sine'
amp = 1.0
freq_hz = 100
offset = 0.0
duration_s = 1
# 生成并绘制波形
t, signal = generate_waveform(wave_type, amp, freq_hz, offset, sampling_rate=1000,
duration=duration_s)
plt.figure(figsize=(10, 6))
plt.title(f"{wave_type.capitalize()} Waveform Generator")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')