Demo entry 6358825

PythonOscilliscope

   

Submitted by anonymous on Apr 26, 2017 at 20:33
Language: Python. Code size: 2.8 kB.

import serial
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
import collections
import time
import random
import math

class DynamicPlotter():

    def __init__(self, serial_port='/dev/cu.usbmodem1411', sampleinterval=0.1, 
                 timewindow=10., size=(600,350), vdiv_port='/dev/cu.usbserial-DN01Z0U3'):
        # Data stuff
        self.ser = serial.Serial(serial_port, 9600)
        self.sampleinterval = sampleinterval
        self.timewindow = timewindow
        # self.vdiv = serial.Serial(vdiv_port, 9600)
        self._interval = int(sampleinterval*1000)
        self._bufsize = int(timewindow/sampleinterval)
        self.databuffer = collections.deque([0.0]*self._bufsize, self._bufsize)
        self.x = np.linspace(-timewindow, 0.0, self._bufsize)
        self.y = np.zeros(self._bufsize, dtype=np.float)
        # PyQtGraph stuff
        self.app = QtGui.QApplication([])
        self.plt = pg.plot(title='Potential vs. Time')
        self.plt.resize(*size)
        self.plt.showGrid(x=True, y=True)
        self.plt.setLabel('left', 'amplitude', 'V')
        self.plt.setLabel('bottom', 'time', 's')
        self.curve = self.plt.plot(self.x, self.y, pen=(255,0,0))
        # QTimer
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateplot)
        self.timer.start(self._interval)
        self.trigger = 0.5

    def getdata(self):
        cont = False
        while cont is False:
            val = self.ser.readline().decode().strip('\r\n')
            try:
                float(val)
                cont = True
            except ValueError:
                print('Here')
                cont = False
        return val


    def get_vdiv(self):
        val = self.vdiv.readline().decode().strip('\r\n')
        return val

    def updateplot(self):
        range_v = 0.05
        sig = self.getdata()
        cont = False
        if float(sig) >= self.trigger:
            start = time.time()
            while cont is False:
                self.databuffer.append(self.getdata())
                try:
                    self.y[:] = [2 * x for x in self.databuffer]
                except ValueError:
                    print(type(self.databuffer))
                    self.y[:] = [2 * x for x in self.databuffer[:-2]]
                if time.time()-start > self.timewindow:
                    cont = True
            cont = False
            self.curve.setData([abs(x) for x in self.x], self.y)
            self.app.processEvents()


    def run(self):
        self.app.exec_()

a = DynamicPlotter(serial_port = '/dev/cu.usbmodem1411', sampleinterval=0.0005, timewindow=0.05)
a.run()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).