Wikipedia

Search results

Uthid

Massage To Print

Serial Port

 

ทดสอบทำ Data Visualization โดยรับค่าจาก Serial Port นำมาแสดงผลด้วย matplotlib บน Python Platform

Library ที่จำเป็น

- matplotlib-1.3.1.win-amd64-py2.7
- numpy-MKL-1.8.1.win-amd64-py2.7
- pyparsing-2.0.2.win-amd64-py2.7
- pyserial-2.7.win-amd64-py2.7
- python-dateutil-2.2.win-amd64-py2.7
- six-1.6.1.win-amd64-py2.7

สามารถดาวน์โหลดได้ที่ http://www.lfd.uci.edu/~gohlke/pythonlibs/#six
Python ดาวน์โหลดได้ที่ https://www.python.org/‎

Arduino Sketch
int i = 0; void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { do { i = i+1; Serial.println(i); delay(1); } while(i < 5); do { i = i-1; Serial.println(i); delay(1); } while(i > 0); delay(1); // delay in between reads for stability }

Python Code

import sys, time
import numpy as np from matplotlib import pyplot as plt from serial import Serial from serial import SerialException ## specify your serial port here ## for Ubuntu: use '/dev/ttyUSB0' or '/dev/ttyACM0' com_port = 'COM1' ## specify baudrate baudrate = 9600 timeout = 1.0 # set serial I/O timeout in seconds try: ser = Serial( port=com_port, baudrate=baudrate, timeout=timeout, bytesize=8, parity='N', stopbits=1 ) except SerialException as ex: print ex sys.exit(-1) nsteps = 200 ymax = 5.5 ymin = 0.0 xdata = [] ydata = [] fig, ax = plt.subplots() data, = ax.plot( xdata, ydata ) plt.axis( [0,nsteps,ymin,ymax] ) plt.ion() # enable interactive plotting mode plt.title('Arduino Serial Plot') plt.xlabel('Index') plt.ylabel('Data') plt.grid(True) plt.show(block=False) x = 0 new_y = [] print 'Press Ctrl+C to exit...' try: while True: y = ser.readline() if y is None or len(y) == 0: continue ##y = int(y.strip()) / 1000.0 new_y.append( y ) if len(new_y) < 10: continue for y in new_y: ydata.append(y) xdata.append(x) x += 1 new_y = [] if len(xdata) > nsteps: n = len(xdata)-nsteps del xdata[0:n] del ydata[0:n] plt.xlim( [x-nsteps+1,x] ) else: plt.xlim( [0,nsteps] ) data.set_data( xdata, ydata ) #fig.canvas.draw() fig.canvas.flush_events() except KeyboardInterrupt as ex: print 'Exit' except Exception as ex: print 'Exception:', ex finally: print 'Done...' pass sys.exit(0)


Serial Port Serial Port Reviewed by Uthid on December 01, 2020 Rating: 5

No comments:

Powered by Blogger.