Create Real-Time Oscilloscope with Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This tutorial is a step-by-step guide on how to create an oscilloscope using Python's Matplotlib library. An oscilloscope is a device used to measure and display voltage signals over time. In this tutorial, we will use Matplotlib's animation module to create a real-time display of a voltage signal.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/animation_creation("`Animation Creation`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/while_loops("`While Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/AdvancedTopicsGroup -.-> python/generators("`Generators`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} matplotlib/animation_creation -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/booleans -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/conditional_statements -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/while_loops -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/lists -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/tuples -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/function_definition -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/default_arguments -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/importing_modules -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/using_packages -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/standard_libraries -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/classes_objects -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/constructor -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/polymorphism -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/encapsulation -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/generators -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/math_random -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/numerical_computing -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/data_visualization -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} python/build_in_functions -.-> lab-48963{{"`Create Real-Time Oscilloscope with Matplotlib`"}} end

Import Libraries

Before we start coding, we need to import the necessary libraries. We will be using Matplotlib, NumPy, and the animation module.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib.lines import Line2D

Set up the Scope Class

The Scope class will hold the data and methods we need to create the oscilloscope. In the constructor, we initialize the necessary variables and set up the plot.

class Scope:
    def __init__(self, ax, maxt=2, dt=0.02):
        self.ax = ax
        self.dt = dt
        self.maxt = maxt
        self.tdata = [0]
        self.ydata = [0]
        self.line = Line2D(self.tdata, self.ydata)
        self.ax.add_line(self.line)
        self.ax.set_ylim(-.1, 1.1)
        self.ax.set_xlim(0, self.maxt)

Define the Update Method

The update method is called for each frame of the animation. It takes in a new value and updates the plot accordingly.

def update(self, y):
        lastt = self.tdata[-1]
        if lastt >= self.tdata[0] + self.maxt:  ## reset the arrays
            self.tdata = [self.tdata[-1]]
            self.ydata = [self.ydata[-1]]
            self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
            self.ax.figure.canvas.draw()

        t = self.tdata[0] + len(self.tdata) * self.dt

        self.tdata.append(t)
        self.ydata.append(y)
        self.line.set_data(self.tdata, self.ydata)
        return self.line,

Create the Emitter Function

The emitter function generates the data that will be passed to the update method. In this case, we are generating random data with a probability of 0.1.

def emitter(p=0.1):
    while True:
        v = np.random.rand()
        if v > p:
            yield 0.
        else:
            yield np.random.rand()

Set up the Plot

We create a new figure and axis object and initialize the Scope class. We then pass the update and emitter functions to the FuncAnimation method to create the animation.

fig, ax = plt.subplots()
scope = Scope(ax)

ani = animation.FuncAnimation(fig, scope.update, emitter, interval=50,
                              blit=True, save_count=100)

plt.show()

Summary

In this tutorial, we learned how to use Matplotlib to create an oscilloscope that displays voltage signals over time. We defined a Scope class to hold the data and methods needed for the oscilloscope, created an update method to update the plot, and used the emitter function to generate the data. Finally, we set up the plot and passed the update and emitter functions to the FuncAnimation method to create the animation.

Other Python Tutorials you may like