Easily generate square/triangle/sawtooth/inverse sawtooth waveform data in Python using UliEngineering
In a previous post, I’ve detailed how to generate sine/cosine wave data with frequency, amplitude, offset, phase shift and time offset using only a single line of code.
This post extends this approach by showing how to generate square wave, triangle wave, sawtooth wave and inverse sawtooth wave data - still in only one line of code.
All of the parameters, including frequency, amplitude, offset, phase shift and time offset apply for those functions as well - see the previous post for details and examples for those parameters.
We are using the UliEngineering library, more specifically the UliEngineering.SignalProcessing.Simulation package:
First, install UliEngineering.
Square wave
square_wave_example.py
from UliEngineering.SignalProcessing.Simulation import square_wave
data = square_wave(frequency=10.0, samplerate=10e3)Triangle wave
triangle_wave_example.py
from UliEngineering.SignalProcessing.Simulation import triangle_wave
data = triangle_wave(frequency=10.0, samplerate=10e3)Sawtooth wave
sawtooth_example.py
from UliEngineering.SignalProcessing.Simulation import sawtooth
data = sawtooth(frequency=10.0, samplerate=10e3)Inverse sawtooth wave
inverse_sawtooth_example.py
from UliEngineering.SignalProcessing.Simulation import inverse_sawtooth
data = inverse_sawtooth(frequency=10.0, samplerate=10e3)Plotting code
This code was used to generate the plots for this post in Jupyter:
plot_waveforms.py
%matplotlib inline
from matplotlib import pyplot as plt
plt.style.use("ggplot")
from UliEngineering.SignalProcessing.Simulation import square_wave
data = square_wave(frequency=10.0, samplerate=10e3)
# set_size_inches(20, 10) to make it even larger!
plt.gcf().set_size_inches(10, 5)
plt.plot(data, label="original")
plt.savefig("/dev/shm/square-wave.svg")Check out similar posts by category:
Data Science, Mathematics, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow