jack06215
1/23/2018 - 10:51 PM

sinusoidal waveform

Python code to draw a sample sin waveform using matlplot

import numpy as np
import matplotlib.pyplot as plt
import struct
import wave

# sine wave generator 
# --------------------
# amplitude, base frequency, num of samples, sampling duration
def create_wave(A,f0,fs,t):
    data = []
    for n in np.arange(t * fs): # arange(): return evently spaced values
        y = A * np.sin(2 * np.pi * f0 * n / fs)
        # clip the amplitude to [-1 1]
        if y > 1.0: y = 1.0
        if y < -1.0: y = -1.0
        
        # C++ equivalence 'data.push_back(y)'
        data.append(y)
    return data

def main():
    data = create_wave(1, 261.63, 10000, 1)
    
    # similar to MATLAB plotting function component
    plt.plot(data)
    plt.xlim([0, 100])
    plt.show()

if __name__ == '__main__':
    main()