# -*- coding: utf-8 -*-
"""
Created on Sat Nov  8 22:50:26 2025

@author: AKourgli
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, filtfilt

# Paramètres
Fe = 200e3
Te = 1/Fe
t = np.arange(0, 20e-3, Te)

fm = 500
fc = 10e3
kf = 2000

# Signal modulant
m_t = np.sin(2*np.pi*fm*t)
# Signal FM
s_fm = np.cos(2*np.pi*fc*t + (kf/fm)*np.sin(2*np.pi*fm*t))

# Paramètres PLL
Kp = 0.5
Kv = 2*np.pi*5000
fc_vco = fc
alpha = 0.05  # constante de filtre

vco_phase = 0
v_control = 0
v_control_tab = []
vco_signal = []

for i in range(len(t)):
    vco_out = np.cos(vco_phase)
    phase_error = s_fm[i] * vco_out
    v_control = (1-alpha)*v_control + alpha*phase_error  # filtre passe-bas
    vco_freq = fc_vco + Kv * v_control
    vco_phase += 2*np.pi * vco_freq * Te
    vco_signal.append(vco_out)
    v_control_tab.append(v_control)

# Filtrage sortie
b, a = butter(3, (2*fm)/(Fe/2))
m_rec = filtfilt(b, a, v_control_tab)

# Affichage
plt.figure(figsize=(10,8))
plt.subplot(3,1,1)
plt.plot(t*1e3, m_t)
plt.title("Signal modulant m(t)")
plt.ylabel("Amplitude")

plt.subplot(3,1,2)
plt.plot(t*1e3, s_fm)
plt.title("Signal FM")
plt.ylabel("Amplitude")

plt.subplot(3,1,3)
plt.plot(t*1e3, m_rec, label="démodulé")
plt.plot(t*1e3, m_t, '--', label="original", alpha=0.7)
plt.title("Signal démodulé par PLL")
plt.xlabel("Temps (ms)")
plt.legend()
plt.tight_layout()
plt.show()
