import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, filtfilt
# Time parameters
t = np.linspace(0, 1, 1000) # 1 second with 1000 points
# Frequency parameters
sine_freq = 5 # Frequency of the sine wave (Hz)
triangle_freq = 10 # Frequency of the triangular wave (Hz)
# Generate a modulated sine wave (input signal)
modulated_sine_wave = np.sin(2 * np.pi * sine_freq * t)
# Generate a carrier triangular wave
carrier_triangle_wave = 2 * np.abs(2 * (t % (1 / triangle_freq)) * triangle_freq - 1) - 1
# Comparator output
comparator_output = modulated_sine_wave > carrier_triangle_wave
# LR circuit parameters
R = 10 # ohms
L = 0.01 # henry
dt = t[1] - t[0]
# Initialize voltage across the resistor
v_R = np.zeros_like(t)
# Calculate voltage across the resistor
for i in range(1, len(t)):
di = (comparator_output[i] - v_R[i-1]/R) * dt / L
v_R[i] = v_R[i-1] + di
# Apply a low-pass filter to the voltage across the resistor
def low_pass_filter(data, cutoff_freq, fs, order=5):
nyquist = 0.5 * fs
normal_cutoff = cutoff_freq / nyquist
b, a = butter(order, normal_cutoff, btype='low', analog=False)
y = filtfilt(b, a, data)
return y
# Low-pass filter parameters
cutoff_freq = 1.0 # cutoff frequency of the low-pass filter (Hz)
fs = 1 / dt # sampling frequency
# Apply the low-pass filter to the v_R signal
v_R_filtered = low_pass_filter(v_R, cutoff_freq, fs)
# Plotting
plt.figure(figsize=(12, 12))
plt.subplot(5, 1, 1)
plt.plot(t, modulated_sine_wave, label='Modulated Sine Wave')
plt.title('Modulated Sine Wave')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)
plt.legend()
plt.subplot(5, 1, 2)
plt.plot(t, carrier_triangle_wave, label='Carrier Triangular Wave', color='orange')
plt.title('Carrier Triangular Wave')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)
plt.legend()
plt.subplot(5, 1, 3)
plt.plot(t, comparator_output, label='Comparator Output', color='green')
plt.title('Comparator Output')
plt.xlabel('Time [s]')
plt.ylabel('Output')
plt.grid(True)
plt.legend()
plt.subplot(5, 1, 4)
plt.plot(t, v_R, label='Voltage across Resistor (v_R)', color='red')
plt.title('Voltage across Resistor (LR Circuit Output)')
plt.xlabel('Time [s]')
plt.ylabel('Voltage [V]')
plt.grid(True)
plt.legend()
plt.subplot(5, 1, 5)
plt.plot(t, v_R_filtered, label='Filtered Voltage across Resistor (v_R)', color='blue')
plt.title('Filtered Voltage across Resistor (Low-pass Filtered)')
plt.xlabel('Time [s]')
plt.ylabel('Voltage [V]')
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()