import math import random import matplotlib.pyplot as plt # -------------------------------------------------- # FSK parameters # -------------------------------------------------- Fs = 100000 # Sample rate: 100 kHz Rb = 100 # Bit rate: 100 bits/sec f0 = 1000 # Frequency for bit 0 f1 = 2000 # Frequency for bit 1 bits = [1, 0, 1, 1, 0, 0, 1, 0] # Number of samples used to represent one bit samples_per_bit = int(Fs / Rb) # -------------------------------------------------- # FSK modulator # -------------------------------------------------- phase = 0 time = [] signal = [] bit_signal = [] for bit in bits: # Select the frequency for this bit if bit == 0: f = f0 else: f = f1 # Generate samples for this bit for i in range(samples_per_bit): # Advance phase phase += 2 * math.pi * f / Fs # Keep phase between 0 and 2*pi phase %= 2 * math.pi # Generate carrier sample = math.cos(phase) time.append(len(time) / Fs) signal.append(sample) bit_signal.append(bit) # -------------------------------------------------- # Plot # -------------------------------------------------- fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 6), sharex=True) # Bits ax1.step(time, bit_signal, where="post") ax1.set_ylabel("Bit") ax1.set_title("FSK Data") ax1.grid() # FSK waveform ax2.plot(time, signal) ax2.set_xlabel("Time (seconds)") ax2.set_ylabel("Amplitude") ax2.set_title("Phase-Continuous BFSK Signal") ax2.grid() plt.tight_layout() plt.show()