FSK modulation python code | FSK python script

This page covers FSK modulation python code. FSK python script plots FSK modulated waveform and binary data waveform as output.

Introduction: FSK stands for Frequency Shift Keying. This is the digital modulation scheme in which digital data (in the form of binary 0's and 1's) are represented by carrier frequencies. Binary 1 is represented by frequency ('f1') and binary 0 is represented by frequency ('f2'). In FSK python script, f1 is set to 45 Hz where as f2 is set to 30 Hz. Random binary data is generated using Binarygen.py python script.

FSK modulation

Binary FSK can be represented by following equation:
s(t) = A* sin(2*π*f1*t) for Binary 1, f1 = 45 Hz in python code below
s(t) = A* sin(2*π*f2*t) for Binary 0, f2 = 30 Hz in python code below

Binary data generator Python script | Binarygen.py

Following python script can be used to generate random binary data. This is used as baseband data in FSK modulation.

def binary(sym, sym_len):

  import numpy as np
  rand_n = np.random.rand(sym)
  rand_n[np.where(rand_n >= 0.5)] = 1
  rand_n[np.where(rand_n <= 0.5)] = 0

  sig = np.zeros(int(sym*sym_len))

  # generating symbols
  id1 = np.where(rand_n == 1)

  for i in id1[0]:
    temp = int(i*sym_len)
    sig[temp:temp+sym_len] = 1
  return sig

FSK Python script

Following FSK python script can be used to generate FSK modulated waveform for random binary data given as input.

# This python script generates FSK modulated waveforms
# Library files
import matplotlib.pyplot as plt
import numpy as np
from Binarygen import binary
from math import pi
plt.close('all')
# Carrier wave and binary signal configuration parameters
Fs = 1000 # Samples per second
fc = 30 # Carrier frequency 30 Hz, 30 cycles/sec
T = 1 # Total simulation time in seconds, 1sec
t = np.arange(0, T, 1/Fs)
Td = 0.1 # Bit duration
Nsamples = int(Td*Fs) # Samples in one bit duration
Nsym = int(np.floor(np.size(t)/Nsamples))
# Binary waveform generation
sig = binary(Nsym,Nsamples)
# FSK waveform generation
f = fc + fc*sig/2
Xfsk = np.sin(2*pi*f*t)
# Binary waveform and FSK modulation waveform Plots
figure, axis = plt.subplots(2)
axis[0].plot(t, sig)
axis[0].set_title("Binary digital data")
axis[1].plot(t, Xfsk, 'r')
axis[1].set_title("FSK modulated signal")
plt.tight_layout()
plt.show()

Output plots of FSK modulation python code

Following are the output plots (Binary input data and FSK modulated waveform) of above FSK modulation python script.

FSK modulation python plots

Other useful DSP codes in Python

Useful Links to MATLAB codes

RF and Wireless tutorials