Deprecated: Assigning the return value of new by reference is deprecated in /f2/blendedtechnologies/public/wp-content/plugins/pmetrics.php on line 1192
Blended Technologies » Blog Archive » Realtime Plot of Arduino Serial Data Using Python

Realtime Plot of Arduino Serial Data Using Python

So I got an Arduino a few weeks ago, and just made my second little project:

Arduino Knock Sensor Circuit

It simply has a piezo element connected to an analog input pin. The Arduino polls the value every 100ms and prints it to the serial port. Here is the sketch:

/* Knock Poller
 * ----------------
 * We listen to an analog pin, sample the
 * signal and write it to the serial port.
 */

int knockSensor = 5;
byte val = 0;

void setup() {
 Serial.begin(9600);
}

void loop() {
    val = analogRead(knockSensor);
    Serial.println(val,DEC);
    delay(100);  // we have to make a delay to avoid overloading the serial port
}

The problem was that I found it was hard to tell what was happening just by reading the values printed to the serial monitor in the Arduino IDE’s serial monitor.

So I researched realtime plots/graphs/charts in Python, and sadly didn’t find too much. Finally I came across
Eli Bendersky’s live graph demo using wxPython and matplotlib
which was exactly what I was looking for.

I repurposed it to listen to the Arduino and set it listening:

arduino_plot_screenshot.PNG

You can see how my pushing on the knock sensor makes the voltage go up and down.

You can get the code here. (I only tested it on Windows XP.)
It should work for any Arduino sketch that sends numeric data to the serial port at least a few times per second. It’s smart enough to ignore non-numeric lines.

I got a lot of help from the folks at Stack Overflow on how to use pySerial.

Update:

It turns out the proper search term would have been “arduino oscilloscope” which does bring back some useful projects:

http://code.google.com/p/arduinoscope/

http://accrochages.drone.ws/en/node/90

But I still like mine since you don’t have to compile anything to run it, and it doesn’t dictate what Arduino sketch you use.

del.icio.us |  Digg |  FURL |  Yahoo! My Web 2.0 |  Reddit

73 Responses to “Realtime Plot of Arduino Serial Data Using Python”

  1. wwn Says:

    how to export serial data to Excel file?, i need that to analysis serial output. can you help me, because i’m newbies in python language. thank’s

  2. someone Says:

    If you want to put data into excel, just open the serial monitor, and run your sketch, then when its done copy and pase the data from serial monitor to excel?

  3. flashbox Says:

    Thanks for posting this. I had a few issues. In Ubuntu 9.10 I got the following error when trying to run

    >> ImportError: Matplotlib backend_wx and backend_wxagg require wxPython >=2.8

    I fixed it by adding the following two lines to wx_mpl_dynamic_graph.py

    import wxversion
    wxversion.select(’2.8′)

    right before import wx.

    Second, when testing with the sketch above and a pot attached to the board I notice the signal was wrapping around, changing the val variable to int type instead of byte and removing the DEC from the write command fixed the problem. Thanks again!

  4. Colin Heics Says:

    I recently used this to visualize some data coming off a Bluetooth DAC I have. Did you manage to be ok with the low update rate of this graph in comparison to the realtime graph using random numbers?

    I am examining some of the buffering of the serial device, and I will post a link to it later this week if I figure out how to handle it.

  5. NAJK Says:

    Hi.

    I’m trying to read data from a serial port using this code, and haven’t modified it further than changing the port information. The only output I get is 500 “100″’s in a row, and can’t figure out where it comes from. I’m a beginner at this stuff, so I’d be glad for some help. How can I solve this?

    With best regards,
    Najk

  6. Kevin Says:

    Brilliant! This was a tremendous help. I got it rolling with Python2.5 on Vista in about 20 minutes, and most of that time was downloading libraries.

    Thank you!

    PS: For those of you looking to save the raw data into Excel, why not modify the Python to write to a file in Arduino_Monitor.py? Maybe write the buffer right after it’s read?

  7. gen Says:

    Thank you very much!! This is exactly what I needed. It’s awesome. I won’t have to adapt Eli Bendersky’s code to add serial…
    I’ll customize it a bit, to fit my needs. (add a logger and some UI elements, for COM port selection etc.)

    For those who are interested he also did this :
    http://eli.thegreenplace.net/2009/08/07/a-live-data-monitor-with-python-pyqt-and-pyserial/

  8. WaZK Says:

    Thank you very much^^

    I just copy your code and I got it!!!

    Anyway, do you know how to plot multiply data in one graph?? Data was sent by single serial port

  9. Graham Says:

    Thank you.
    I could not get Processing to run because of incompatible java versions or something.
    I have been playing with python for a while. I have the analog data comming at one byte every 100 us on a serial of 115 k and written to a csv file in python for analysis and graphing in a spreadsheet.
    I couldn’t get control of the data flow into the array for display directly in python.

  10. theepdinker Says:

    Great write up!
    I got it working in Python 2.7 on Ubuntu 11.04 with two changes:
    1. port=’/dev/ttyACM0′
    2. select a specific version of wx:
    import wxversion
    wxversion.select(”2.8″)
    import wx, wx.html

  11. Janneman Says:

    Sound and simple program. Nice work!

    I’ve got it working on debian squeeze, but had to disable the interCharTimeout=None option on line 37 of Arduino_Monitor.py. (Squeeze comes with pyserial version 1.35, which doesn’t support this option)

  12. Arduino Test Runs (part 1) | The Scrambled Bit Says:

    […] So now I have 2 pots on my board, and I have to get serial data to the computer. This time, I wanted to work… so I Googled a while, until I found that pySerial can read lines of the serial port (n delimited). Awesome, I have packets. I try this… amazing… I can draw for 3 seconds than it hangs. A bit more searching, and I found the answer to my problem: read continuously off the serial port in a thread and get the last result whenever I ask for it. A nice class which does that can be found at the answer. I can now send more numbers to the computer, awesome! This was my fifth attempt at drawing my logo using the 2 potentiometers etch-a-sketch style. […]

  13. [g12] » Blog Archive » PDP (HRV) monitorius logeris Says:

    […] Toliau: skaitau šį output’ą su python programyte: […]

  14. kooXKristenSuera Says:

    This is the proper weblog for anyone who wants to find out about this topic. You realize so much its virtually laborious to argue with you (not that I truly would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, simply great!

  15. TideMan Says:

    Running on Ubuntu, I inserted:
    import wxversion
    wxversion.select(’2.8′)
    before import wx.
    Also, I had to remove:
    interCharTimeout=None
    and change the port to /dev/ttyACM1.

    Now it’s working but straightlining at 100, yet the Arduino Serial Monitor shows changing data. What can be wrong?

  16. website Says:

    Have you thought about adding some relevant links to the article? I think it will really enhance viewers understanding.

  17. chronic mono Says:

    I have got one idea for your web site. It looks like there are a handful of cascading stylesheet problems when launching a number of web pages in google chrome and firefox. It is working alright in internet explorer. Perhaps you can double check that.

  18. roweboat Says:

    Great work! We have been working on some software to try and do this as well. Will be interested to know what you think. Check it out at megunolink.com

  19. mausgang Says:

    Cool work. Could the python be reconfigured to talk with another executable, I’m trying to get an Arduino to talk with a GC’s computer software.

  20. Felipe Martins Says:

    Great post! Very helpful!
    The only thing I had to do was to change my COM port number. It is working perfectly! I am running Windows 7 and Python 2.7.3.
    I had also changed the type of the variable “val” on your Arduino code. I am using a long int so that I can read the full ADC range (10 bits = 0-1023).
    Thanks a lot for the post!!

  21. Tim Pitman Says:

    Great work! I’ve spent a lot of time researching the best realtime Python plotting libraries. I initially used matplotlib, but eventually switched to Chaco, which is one of Enthought’s libraries. I found it much faster for realtime type stuff. It’s not quite as easy to use and not as good for live plotting, but there are other features (ie Traits) which make it really awesome in other ways. Highly recommended for anyone wanting higher refresh rates and/or lower CPU usage.

  22. steff Says:

    I am wondering if there is anyway I can export my count directly from two sensors (serial data)from Arduino connected to a serial bluetooth module to excel or any other software that can plot graphs in real time.

    Thanks for any help.

    Steff

  23. Jose Says:

    I really like reading your blog. There is only one problem. I cannot find your rss feed button.

  24. Sex anonse Says:

    www.blendedtechnologies.com gives me so much pleasure

    Sex za darmo

  25. http://newespressomachine.com/ Says:

    Im not that much of a online reader to be honest but your sites really
    nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. Cheers

  26. og?oszenia towarzyskie warszawa Says:

    I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m not 100% certain.
    Any suggestions or advice would be greatly appreciated.
    Cheers

  27. Jonny Cristhian Says:

    Testeado en Ubuntu 12.04, corre sin problemas, nicamente en el archivo “Arduino_Monitor.py” se debe cambiar ‘COM4′ por: ‘ttyUSB0′ (o el que corresponda a su versin de Arduino)
    Saludos, Muchas Gracias.

  28. oferty towarzyskie Says:

    Hey there! This is kind of off topic but I need some
    guidance from an established blog. Is it very hard to set up
    your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to start. Do you have any tips or suggestions? Cheers

  29. Aravind Says:

    Hey, thanks so much for the script man!

    Initially it didn’t work on my ubuntu, but when I changed the port=’com4′ in the Arduino_Monitor.py file to port=’/dev/ttyUSB0′, it worked beautifully :)

  30. click here Says:

    I got this site from my friend who informed me concerning this web site and at the moment
    this time I am visiting this web page and reading very informative content at this
    time.

  31. Adam Says:

    Thank you for the very helpful instructions. Any thoughts on how to plot multiple data sources such as temperature, pressure, speed, etc in real time via the serial port.

  32. sex Says:

    Excellent post. I was checking constantly this blog and I’m impressed!
    Very useful information specially the last part :) I care
    for such info much. I was looking for this particular information for a long time.
    Thank you and good luck.

  33. Angela Says:

    It is not my first time to pay a quick visit this website,
    i am visiting this web site dailly and obtain nice facts from here daily.

    Also visit my weblog … watch iron man 3 online - Angela -

  34. seo services Says:

    422811205195222220737034229746 5056122951939539 seo 64068362233011431971 company 1858802247976994. 56389 seo company 22796370475522265 green 422 92205528639612463733935995408 seo company 779778 09546670844382234612 497227.69911 :(

  35. 1 Says:

    1

  36. vintage louis vuitton purses for sale Says:

    888 seeker wait Panthers with regards to 4
    vintage louis vuitton purses for sale http://www.tzadoktorahministries.org/louis-vuitton-purses-sale-c-8.html

  37. replica louis vuitton neverfull Says:

    9985 You have a whole lot of individuals viewing this means you basically do want some wind to come in.”. Your usage of the location indicates your agreement to generally be certain with the Phrases of Use..
    replica louis vuitton neverfull http://www.trell-o.com/louisvuittonneverfull.html

  38. cheap menthol cigarettes online free shipping sale outlet store Says:

    When you practice, you’ll have the ability to established down the razor, pull it throughout the pores and skin, and increase it up in the finish of the stroke within a smooth motion. A rolling razor similar to a “Headblade” can keep the proper angle in hardtoreach locations.[9]Shave inside the appropriate path. On the initial go, constantly shave with all the grain. This ordinarily means shaving downward, although not constantly. Heading towards the grain (shaving the opposite direction the hair grows) tends to make to get a nearer shave, nevertheless it also produces by far the most irritation and cuts. If you have a bent to acquire bumps or rashes, or for those who generally get ingrown hairs, or in the event you basically consider your encounter as well pretty to abuse, commence shaving together with the grain. A couple issues to think about as you shave:
    cheap menthol cigarettes online free shipping sale outlet store http://www.howwouldyouvote.us/menthol-cigarettes/

  39. fake christian louboutin Says:

    Blended Technologies » Blog Archive » Realtime Plot of Arduino Serial Data Using Python
    fake christian louboutin http://www.hecht.org/sneakers/fake-christian-louboutin.html

  40. http://alkomatyy.pl Says:

    I know this if off topic but I’m looking into starting my
    own blog and was curious what all is required to get setup?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m not 100% sure. Any suggestions or advice would
    be greatly appreciated. Thank you

  41. hogan outlet Says:

    Ultimamente leggo sempre più ammirato tra gli altri gli interventi di Roberto ‘Vigorelli 1954′

  42. mbt outlet Says:

    12La première entrevue avec une enseignante a servi de pré test et a été faite exceptionnellement avec une enseignante du secondaire qui travaillait dans une classe d’accueil (immigrants allophones). Les données recueillies auprès de cette enseignante ne semblent pas se démarquer des autres données et ont ainsi été intégrées dans les résultats quoique la répondante ne corresponde pas aux critères d’inclusion. Toutes les autres enseignent au premier cycle du primaire.

  43. Satyr Says:

    Hi,

    Thanks for the plotting script.
    Is it possible to plot several data streams simultaneously with different colors? I am not familiar with Python. I cannot do that myself.

    Can you give me the commands please?

    THX

  44. tari Says:

    Hi,
    How to do Plotting of real-time data from MSP430 using Python ?

    Can Someone help?

  45. scott yancey review Says:

    Fantastic website. A lot of helpful information here. I¡¦m sending it to some friends ans additionally sharing in delicious. And certainly, thanks to your effort!

  46. Hildred Says:

    It’s hard to find your posts in google. I found
    it on 11 spot, you should build quality backlinks , it will help you to
    rank to google top 10. I know how to help you, just type in google
    - k2 seo tips

  47. 綠化 Says:

    Hello, all is going sound here and ofcourse every one is sharing facts,
    that’s genuinely excellent, keep up writing.

    Allso visit myy web-site :: 綠化

  48. wholesale cheap vikings #5 donovan mcnabb purple womens team color stitched nfl jersey online store Says:

    The Amazing babyliss system Works While You Fall asleep : )
    wholesale cheap vikings #5 donovan mcnabb purple womens team color stitched nfl jersey online store http://www.okonomiservice.net/TOCFrame-filer/youth-brett-favre-jersey/wholesale-cheap-vikings-5-donovan-mcnabb-purple-womens-team-color-stitched-nfl-jersey-online-store.asp

  49. just reduced womens nike new orleans saints heart & soul nfl t shirt dark green outlet online sale Says:

    Unprejudiced write-up brings out A couple of fresh new stuff about babyliss that noone is covering.
    just reduced womens nike new orleans saints heart & soul nfl t shirt dark green outlet online sale http://larservik.com/Festen/buy-fitted-mlb-hats-cheap/just-reduced-womens-nike-new-orleans-saints-heart–soul-nfl-t-shirt-dark-green-outlet-online-sale.asp

  50. online cheap coach poppy in signature medium grey totes ael online sale Says:

    Stop Complaining And Commence a personal babyliss Distribution campaign As a substitute .
    online cheap coach poppy in signature medium grey totes ael online sale http://www.sofienberg.as/class/coerver-coaching/online-cheap-coach-poppy-in-signature-medium-grey-totes-ael-online-sale.asp

  51. the fastest way to get raid your dandruff polo men sweater 1106 up to 78% off Says:

    Independent website displays 4 brand new stuff around babyliss that absolutely no one is talking about.
    the fastest way to get raid your dandruff polo men sweater 1106 up to 78% off http://www.schillingweb.com/div/ralph-lauren-polo-sweaters-for-women/the-fastest-way-to-get-raid-your-dandruff-polo-men-sweater-1106-up-to-78-off.asp

  52. cheap quality coach megan black sunglasses bhn garden fresh vegetables Says:

    Independent blog uncovers Couple of new stuff concerning babyliss that no company is talking about.
    cheap quality coach megan black sunglasses bhn garden fresh vegetables http://www.jazzmazz.com/edit/coach-leather/cheap-quality-coach-megan-black-sunglasses-bhn-garden-fresh-vegetables.asp

  53. cheap quality air jordan evolution 85 white infrared orion blue stealth wholesale Says:

    Independent brief article unveils Seven brand new stuff about babyliss that no company is mentioning.
    cheap quality air jordan evolution 85 white infrared orion blue stealth wholesale http://www.kontrollrom.com/cheap-jordan-store/cheap-quality-air-jordan-evolution-85-white-infrared-orion-blue-stealth-wholesale.asp

  54. genuine coach logo signature large pink wallets dty free shipping Says:

    The best tool for babyliss that you should find out about as we speak.
    genuine coach logo signature large pink wallets dty free shipping http://www.lillelo.com/silje/coach-watches-sale-online/genuine-coach-logo-signature-large-pink-wallets-dty-free-shipping.asp

  55. shop christian louboutin vivaeva 160mm leather sandals taupe factory outlet Says:

    This Completely new babyliss blueprint Work Even If You Go to sleep! !
    shop christian louboutin vivaeva 160mm leather sandals taupe factory outlet http://www.liberiagroupofindustries.com/includes/christian-louboutin-sneakers-women-sale/shop-christian-louboutin-vivaeva-160mm-leather-sandals-taupe-factory-outlet.asp

  56. choose the best coach bleecker monogram medium black backpacks dhk take advantage of these prices now Says:

    An excellent strategy for babyliss you can explore right away.
    choose the best coach bleecker monogram medium black backpacks dhk take advantage of these prices now http://www.nina-andresen-borud.com/bilder/purses-coach/choose-the-best-coach-bleecker-monogram-medium-black-backpacks-dhk-take-advantage-of-these-prices-now.asp

  57. best selling christian louboutin diplonana 120mm gold leather ankle boots fast shipping Says:

    What you ought to do to discover more about babyliss before you’re left behind.
    best selling christian louboutin diplonana 120mm gold leather ankle boots fast shipping http://www.mundal.com/fpdb/christian-louboutin-saks-fifth/best-selling-christian-louboutin-diplonana-120mm-gold-leather-ankle-boots-fast-shipping.asp

  58. buy designer coach laurin brown sunglasses daf outlet store Says:

    babyliss Replicas - - An Incredible babyliss hack Which Fools 96% of the end users
    buy designer coach laurin brown sunglasses daf outlet store http://www.endrefiskeside.com/captcha/coach-outlet-factory-sale/buy-designer-coach-laurin-brown-sunglasses-daf-outlet-store.asp

  59. buy authentic designer christian louboutin satin mount street t strap sandal black outlet us online Says:

    Impartial write-up unveils 2 brand new stuff on babyliss that absolutely no one is bringing up.
    buy authentic designer christian louboutin satin mount street t strap sandal black outlet us online http://www.langdalen.com/images/new-christian-louboutin-sneakers/buy-authentic-designer-christian-louboutin-satin-mount-street-t-strap-sandal-black-outlet-us-online.asp

  60. fashion discount christian louboutin booties robot 120mm ankle metallic silver exclusive at (place) Says:

    Marketplace Gossip : babyliss Thought as Essential Today
    fashion discount christian louboutin booties robot 120mm ankle metallic silver exclusive at (place) http://www.engsmyr.com/bilder/christian-louboutin-barneys/fashion-discount-christian-louboutin-booties-robot-120mm-ankle-metallic-silver-exclusive-at-place.asp

  61. many happy returns polo men t shirts 2078 unbeatable price Says:

    Greatest strategy for babyliss that you may learn more about right now.
    many happy returns polo men t shirts 2078 unbeatable price http://www.sherpakonsult.com/pdf/lauren-by-ralph-lauren-furniture/many-happy-returns-polo-men-t-shirts-2078-unbeatable-price.asp

  62. Realtime Plot of Arduino Serial Data Using Python | 123 Says:

    […] [Source: http://www.blendedtechnologies.com/realtime-plot-of-arduino-serial-data-using-python] […]

  63. cheap jordans Says:

    surprisingly|fundamentally|mainly|simply|conveniently|absolutely|readily|clearly|pretty much|truly|primarily|basically just|typically|comfortably|for instance|only just|without difficulty|as an example|nothing more than|exclusively|exactly|in essence|partly|strictly|barely|mostly|to some extent} painting
    cheap jordans http://www.floridagirlinsydney.com

  64. chojnow Says:

    whoah this blog is great i really like studying your posts.
    Keep up the good work! You realize, a lot of
    people are looking around for this information, you could aid them greatly.

  65. accident lawyer Says:

    There are varied ways in which to keep our roads safe and start eliminating the needless trucking accidents
    that are occurring in excess each year. Courts deal
    with these types of cases every single day and many people who were seriously hurt can receive compensation that helps their daily lives
    and to pay back some of the medical bills that they might have.
    With motorcycles on the other hand, that number is at
    72.

    my blog post accident lawyer

  66. mba7 Says:

    I made an equivalent tool in python that print real time data from ADXL345 accelerometer.
    https://github.com/mba7/SerialPort-RealTime-Data-Plotter
    may be it will be helpful for someone

  67. Billy Says:

    Thanks on your marvelous posting! I quite enjoyed reading it, you
    might be a great author. I will make sure to bookmark your blog and will come back from now on. I want to encourage that you continue your great writing, have a nice morning!

  68. nike jordan Says:

    Hi there just wanted to give you a quick heads up.

    The words in your post seem to be running off the screen in Opera.
    I’m not sure if this is a formatting issue or something to do with web browser
    compatibility but I figured I’d post to let you know.
    The style and design look great though! Hope you get the issue fixed soon. Cheers

    Here is my webpage nike jordan

  69. Seo Says:

    Love the title of your blog. And btw, I did not think about writing as you did on the ST, so I will drop by regularly reading your posts.

  70. Anonymous Says:

    I tend not to write a lot of remarks, but i did some searching and wound up here Blended Technologies Blog Archive Realtime Plot of Arduino Serial Data Using Python. And I do have a couple of questions for you if you tend not to mind. Could it be only me or does it seem like a few of these responses look like they are written by brain dead individuals? :-P And, if you are writing at other social sites, I would like to keep up with anything fresh you have to post. Would you make a list of the complete urls of all your social pages like your twitter feed, Facebook page or linkedin profile?

  71. ralph loren Says:

    This is especially useful for professional cyclists and runners. Lenses these days are also vented so as to maintain air circulation which prevents fogging and the consequent blurry vision.
    ralph loren http://www.simairforce.com/images/ralph-loren/

  72. where to purchase gucci handbag crystal mix 223965 fzi4g 9795 gucci outlet online at the official site Says:

    babyliss News Networks Acquire The Up-dates Rapidly
    where to purchase gucci handbag crystal mix 223965 fzi4g 9795 gucci outlet online at the official site http://www.rittenhouseacupuncture.com/images/gucci-sukey-sale/gucci-handbag-crystal-mix-223965-fzi4g-9795—gucci-outlet-online-p-4112.html

  73. Cheap Detroit Pistons cap Says:

    WOW just what I was looking for. Came here by searching for %keyword%|

Leave a Reply