import numpy as np
import matplotlib.pyplot as plt

# --- Basic canvas ------------------------------------------------------
fs   = 1e6          # 1 MS/s sample clock
dur  = .075                # 75 ms sweep
n    = int(fs * dur)      # total samples
t    = np.arange(n) / fs  # time axis

# --- Design the AUDIO chirp -------------------------------------------
f_start = 30             # 30 Hz
f_end   = 15000          # 15 kHz
k       = (f_end - f_start) / dur          # sweep rate (Hz/s)

# Instantaneous audio frequency: f_a(t) = f_start + k*t
# The audio phase is integral of the instantaneous audio frequency fucntion:
phi_audio = 2*np.pi*(f_start*t + 0.5*k*t**2)
m_t       = np.sin(phi_audio)              # audio message, range ±1

# --- Apply FM deviation -----------------------------------------------
dev = 75000              # 75 kHz deviation constant
# FM phase: integrate m(t) and scale by deviation
phi_fm = 2*np.pi * dev * np.cumsum(m_t) / fs

# Baseband complex envelope for the GH‑60 ARB
iq = np.exp(1j * phi_fm)

# --- Scale to 0‑255 and save interleaved -------------------------------
i_int16 = ((iq.real)*127.5).astype(np.int16) # 16‑bit signed
q_int16 = ((iq.imag)*127.5).astype(np.int16)


#Save to bin files (two files)
i_int16.tofile("fm_audio_sweep_i.bin")
q_int16.tofile("fm_audio_sweep_q.bin")
data_length = len(i_int16)

# --- (Optional) Interleave samples to save as a signal file-------------
#interleaved = np.empty(2*n, dtype=np.int16)
#interleaved[0::2] = i_int16
#interleaved[1::2] = q_int16
#interleaved.tofile("fm_audio_sweep_iq.bin")
#data_length = len(interleaved)/2


# --- (Optional) Quick sanity checks ------------------------------------
clock_rate = fs/1e6
print("Finished: The Data Length is", data_length, "and the Clock Rate is", clock_rate, "Ms/s.")
plt.plot(t[:5000], iq.real[:5000]); plt.title("I‑component (first 5 ms)")
plt.show()


