# gravity snake game/live arduino plotting using matplotlib

A video showing my project in action can be found here. This week I spent more time developing the software behind my project than the hardware. On the hardware side things are pretty simple. I took the basic Arduino we made in lab on Wednesday, plugged in a pressure sensor I found lying around, and wrote the value of the analog port to the serial monitor. I even disabled the light. I discovered that Python has two interesting characteristics that allow one to interact with an Arduino. One, it has a library, pyserial, which allows one to read values coming in from a USB port, much like the serial monitor built into the Arduino software. Two, one can plot data in real time via matplotlib

After adapting some code from this blog, I got Python to live plot data coming in from my simple Arduino setup. Instead of plotting every value that is read in, I average over a user defined slice of values. The rate at which the computer reads in from the USB port is faster than it ability to dynamically draw a plot, so there has to be some kind of delay. For a while, I thought it would be cool to simultaneously plot things like the numerical derivative of the incoming data, or the standard deviation of the sampling chunks. I then remembered that not everyone likes stuff like that as much as I do. People do like games, however! I resolved to make the gravity snake game I used to play on my mom’s black and white cell phone from the early 2000s. This game works in basically the same way as flappy bird. By pressing harder and softer on the pressure sensor, the line moves up and down the screen, such that the player can avoid the ever changing obstacles at the top and bottom of the screen.

The hardest part of this project was coding up the barriers at the top and bottom of the screen, and getting them to properly interact with the player’s line. Reading in data from the serial port can also be a little finicky. My code can be found here.

## One thought on “gravity snake game/live arduino plotting using matplotlib”

1. Awesome. We’ll spend more time with serial communication in the future, but this is great to see!