GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing learn.sparkfun.com — Graph Sensor Data with Python and Matplotlib - SparkFun Learn Graph Sensor Data with Python and Matplotlib
Contributors:
Share
Use this URL to share:
IntroductionPython is a wonderful high-level programming language that lets us quickly capture data, perform calculations, and even make simple drawings, such as graphs. Several graphical libraries are available for us to use, but we will be focusing on matplotlib in this guide. Matplotlib was created as a plotting tool to rival those found in other software packages, such as MATLAB. Creating 2D graphs to demonstrate mathematical concepts, visualize statistics, or monitor sensor data can be accomplished in just a few lines of code with matplotlib. The Raspberry Pi is a great platform for connecting sensors (thanks to the exposed GPIO pins), collecting data via Python, and displaying live plots on a monitor. Notice: This tutorial was written with Raspbian version "June 2018" and Python version 3.5.3. Other versions may affect how some of the steps in this guide are performed.
Required MaterialsTo work through the activities in this tutorial, you will need a few pieces of hardware:
Note: As an alternative, you could also use the the Qwiic cables and the Qwiic TMP102 to easily connect without needing to solder or connect to the four pins.
SparkFun Digital Temperature Sensor - TMP102 (Qwiic)SEN-16304The SparkFun TMP102 Qwiic is an easy-to-use digital temperature sensor equipped with a couple of Qwiic connectors for easy I2…
$8.23
SparkFun Qwiic SHIM for Raspberry Pi & NVIDIA Jetson Orin NanoDEV-15794The SparkFun Qwiic SHIM for Raspberry Pi is a small, easily removable breakout that easily adds a Qwiic connector to your Ras…
$1.95
Qwiic Cable - Breadboard Jumper (4-pin)PRT-14425This is a jumper adapter cable that comes pre-terminated with a female Qwiic JST connector on one end and a breadboard hookup… Qwiic Cable - 200mmPRT-14428This is a 200mm long 4-conductor cable with 1mm JST termination. It’s designed to connect Qwiic enabled components together… Optional MaterialsYou have several options when it comes to working with the Raspberry Pi. Most commonly, the Pi is used as a standalone computer, which requires a monitor, keyboard, and mouse (listed below). To save on costs, the Pi can also be used as a headless computer (without a monitor, keyboard, and mouse). Note that for this tutorial, you will need access to the Raspbian (or other Linux) graphical interface (known as the desktop). As a result, the two recommended ways to interact with your Pi is through a monitor, keyboard, and mouse or by using Virtual Network Computing (VNC). Raspberry Pi LCD - 7" TouchscreenLCD-13733This 7" Raspberry Pi Touchscreen LCD provides you with the ability to create a standalone device that can be utilized as a cu…
$88.30
Multimedia Wireless KeyboardWIG-14271With Single-Board Computers (SBCs) on the rise, it is a good idea to have an easy way to interface with them. Operating on a …
$29.95
$19.95
SmartiPi TouchPRT-14059The SmartiPi Touch is a case and stand for the official [Raspberry Pi 7" Touchscreen LCD](https://www.sparkfun.com/products/1… At the bare minimum, you need a breadboard and some jumper wires to connect the Pi to the TMP102 sensor. However, the Pi Wedge and some M/M jumper wires may make prototyping easier. Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)PRT-11026If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…
$3.50
SparkFun Pi WedgeBOB-13717This is the SparkFun Pi Wedge, a small board that connects to the 40-pin GPIO connector on the Raspberry Pi and breaks the pi…
$13.50
Suggested ReadingIf you aren't familiar with the following concepts, we recommend checking out these tutorials before continuing: Serial Terminal Basics
This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.
Raspberry Pi 3 Starter Kit Hookup Guide
Guide for getting going with the Raspberry Pi 3 Model B and Raspberry Pi 3 Model B+ starter kit.
Getting Started with the Raspberry Pi Zero Wireless
Learn how to setup, configure and use the smallest Raspberry Pi yet, the Raspberry Pi Zero - Wireless.
Python Programming Tutorial: Getting Started with the Raspberry Pi
This guide will show you how to write programs on your Raspberry Pi using Python to control hardware.
Please note: If you have trouble seeing any of the images throughout this tutorial, feel free to click on it to get a better look!
Prepare Your PiTo begin, you will need to flash an image of the Raspbian operating system (OS) onto an SD card (if you have not done so already). You have a couple of options:
OR
Once you have installed the OS for your Raspberry Pi, follow the steps in Configure Your Pi. If given the choice, choose the steps that relate to the Full Desktop setup. Alias Python and PipWe will be using Python 3 in this tutorial. At the time of writing, Python 2 was still the default version with Raspbian, which means that we will need to tell Linux that the command Note: If you have already performed these steps in the Configure Your Pi portion previously, feel free to skip this part.
Open a terminal and enter the following command to edit the .bashrc file:
Scroll down to the bottom of the file, and add the following (if they are not already present):
Exit out of nano with ctrl+x, press y, and press enter. Run the .bashrc script with:
You can check the versions of Python and pip with:
Both should tell you the they are using a version of Python 3 (e.g. 3.5.3). Enable I2CBy default, Raspbian disables the I2C port, which we'll need to talk to the TMP102. Note: If you have already performed these steps in the Configure Your Pi portion previously, feel free to skip this part.
Bring up the Raspberry Pi configuration menu:
If asked to enter a password, type in the password you set for your Raspberry Pi. If you did not change it, the default password is Select 5 Interfacing Options. Select P5 I2C, select yes on the following screen, and press enter to enable the I2C port. Back on the main screen, highlight Finish and press enter. A reboot is not necessary if you did not change any other options. Install DependenciesLike any good Linux project, we need to install a number of dependencies and libraries in order to get matplotlib to run properly. Make sure you have an Internet connection and in a terminal, enter the following commands. You may need to wait several minutes while the various packages are downloaded and installed.
You are now ready to build your circuit and make some graphs! Hardware AssemblyIn this guide, we will read temperature data from a TMP102 temperature sensor and plot it in various ways using matplotlib. After a brief introduction to matplotlib, we will capture data before plotting it, then we'll plot temperature in real time as it is read, and finally, we'll show you how to speed up the plotting animation if you want to show faster trends. To begin, you'll need to connect the TMP102 to the Raspberry Pi, either directly or through a Pi Wedge. We recommend soldering headers onto the TMP102 if you plan to use a breadboard. If you need help, this tutorial shows you the basics of soldering. Connect the TMP102 as shown in one of the following diagrams (with or without the Pi Wedge). If you need help with layout of the Pi's GPIO headers, refer to this guide. Connecting through a Pi Wedge: Click the image for a closer look.
Connecting directly to the Raspberry Pi: Click the image for a closer look. Introduction to MatplotlibMatplotlib is a wonderful tool for creating quick and professional graphs with Python. It operates very similarly to the MATLAB plotting tools, so if you are familiar with MATLAB, matplotlib is easy to pick up. The Absolute BasicsThe easiest way to make a graph is to use the pyplot module within matplotlib. We can provide 2 lists of numbers to pyplot, and it will create a graph with them. Note that the 2 lists need to have the same length (same number of elements). The first list is a collection of numbers in the X domain, and the second is a collection of numbers in the Y range. Use your favorite text editor or Python IDE to enter the following code:
Save the program (e.g. as myplot.py). Run it with:
You should see the graph appear in a new window. While the basic line graph is likely the most used graph, matplotlib is also capable of plotting other types of graphs, including bar, histogram, scatter, and pie (among others). If you want to save the image, you can click on the Save icon in the plot's window. Note that the points from the FormattingLike any good graph-creation tool, pyplot lets you change the formatting of your graphs with legends, titles, and labels. Let's create a new plot:
Save and run this code. You should see two different sinewaves overlapping each other. Here, you might notice a few differences from the first plot. We are creating two different plots, and by calling Note: As it turns out, Python does not have many easy ways to interact with lists or arrays. The numpy package is a great way to work with arrays, and it offers an impressive speed boost over native Python methods. If you are looking for a free MATLAB replacement, numpy is a good contender. When you installed the matplotlib package, numpy was installed by default!
When it comes to formatting the graph, we have plenty of options at our fingertips. We can "zoom" by setting the limit on the axes with Additionally, if you look at our call to Finally, we were able to create the image above by calling Refer to the pyplot documentation to see all the available functions for plotting and formatting. SubplotsSometimes, you may want to display multiple plots on a single image (or figure). To accomplish this, we can use supblots:
Run this, and you should get two sinewaves, each in its own subplot. Up to this point, we had been calling The To learn more about how to create subplots, see the add_subplot definition. We then draw our sinewaves on the axes directly (rather than using the shortcut Plot Sensor DataIn the Python Programming Tutorial: Getting Started with the Raspberry Pi, the final example shows how to sample temperature data from the TMP102 once per second over 10 seconds and then save that information to a comma separated value (csv) file. To start plotting sensor data, let's modify that example to collect data over 10 seconds and then plot it (instead of saving it to a file). TMP102 ModuleIn order to simplify I2C reading and writing to the TMP102, we will create our own TMP102 Python module that we can load into each of our programs. Open a new file named tmp102.py:
Copy in the following Python code:
Save the code with ctrl + x, press y, and press enter. This allows us to call the Temperature Logging and GraphingIn the same directory as the tmp102.py file, create a new file (using your favorite editor), and paste in the following code:
Save (give it a name like tempgraph.py) and exit. Run the program with:
Wait while the program collects data (about 10 seconds). Feel free to breathe on or fan near the temperature sensor to change the ambient temperature (gives you some interesting data to look at). Once the collection has finished, you should be presented with a plot showing how the temperature changed over time. Code to NoteWe create the graph in a very similar manner to the Formatting example in Introduction to Matplotlib. The only difference is that we build the The Update a Graph in Real TimeWaiting to collect measurements from a sensor before plotting it might work in some situations. Many times, you would like to be able to monitor the output of a sensor in real time, which means you can look for trends as they happen. To accomplish that, we will create an animation where a temperature sample is taken and the graph is updated immediately. Animation CodeOpen a new file (once again, make sure it's in the same directory as tmp102.py so that we can use the tmp102 module). Copy in the following code:
Save and run the code. You should immediately see a graph that gets updated about once every second. Feel free to breathe on the sensor to see how the temperature fluctuates. Code to NoteTo create a real-time plot, we need to use the At the bottom of the code, you'll see the secret sauce to the animation:
FuncAnimation is a special function within the Still in the Note: As an argument to FuncAnimation, notice that
animate does not have any parentheses. This is passing a reference to the function and not the result of that function. If you accidentally add parentheses to animate here, animate will be called immediately (only once), and you'll likely get an error (probably something about a tuple not being callable)!If you look at the call to
Within In order to draw the plot, we must clear the axes with You might notice that the plot updates only once per second (as defined by Try lowering the Speeding Up the Plot AnimationClearing a graph and redrawing everything can be a time-consuming process (at least in terms of computer time). As a result, our Raspberry Pi can struggle keeping up with more animations when we push it past about 2-3 frames per second (fps). To remedy that, we are going to use a trick known as blitting. Blitting is an old computer graphics technique where several graphical bitmaps are combined into one. This way, only one needed to be updated at a time, saving the computer from having to redraw the whole scene every time. Matplotlib allows us to enable blitting in FuncAnimation, but it means we need to re-write how some of the Animation with Blitting CodeOpen a new file in the same directory as our tmp102.py module, and copy in the following code:
Save and run the code. A graph should appear with a line that animates much faster than in the previous example (i.e. around 20 fps). You should also note that there are no timestamps (i.e. the x axis does not contain any useful data), and the y axis (temperature) does not automatically scale. In fact, if you were to measure a temperature below 10° or above 40° C, it would not be drawn on the graph. Code to NoteFirst, notice that we removed any reference to Next, we set up a number of static parameters. In the
The trailing comma on After updating the Line2D object with With these changes, we can set the Resources and Going FurtherPlotting sensor data can be incredibly useful if you need to make a dashboard to watch the temperature in your server room or if you want to monitor the humidity around your classroom for a science experiment. If you would like to learn more about matplotlib, here are some great resources: If you are interested in keeping the tmp102.py file in a different directory and still access its functions, we recommend turning it into a package. Here is a good tutorial that shows you how to make your own Python package.
Looking for even more inspiration? Check out these other Raspberry Pi projects: Building Large LED Installations
Learn what it takes to build large LED installations from planning to power requirements to execution.
Bark Back Interactive Pet Monitor
Monitor and interact with pets through this dog bark detector project based on the Raspberry Pi!
Raspberry Pi Zero Helmet Impact Force Monitor
How much impact can the human body handle? This tutorial will teach you how to build your very own impact force monitor using a helmet, Raspberry Pi Zero, and accelerometer!
Using Flask to Send Data to a Raspberry Pi
In this tutorial, we'll show you how to use the Flask framework for Python to send data from ESP8266 WiFi nodes to a Raspberry Pi over an internal WiFi network.
Share
Use this URL to share:
Sections
Introduction
Prepare Your Pi
Hardware Assembly
Introduction to Matplotlib
Plot Sensor Data
Update a Graph in Real Time
Speeding Up the Plot Animation
Resources and Going Further
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |