def update_port(self): self.port = self.cbPort.currentIndex() self.baudrate = serial.Serial.BAUDRATES[self.cbBaudrate.currentIndex()] self.bytesize = serial.Serial.BYTESIZES[self.cbBytesize.currentIndex()] self.parity = serial.Serial.PARITIES[self.cbParity.currentIndex()] self.stopbits = serial.Serial.STOPBITS[self.cbStopbits.currentIndex()] self.timeout = self.spbTimeout.value() self.datagen = DataGen(port=self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, timeout=self.timeout) self.data = [self.datagen.next()]
def __init__(self): wx.Frame.__init__(self, None, -1, self.title) self.datagen = DataGen() self.data = [self.datagen.next()] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REFRESH_INTERVAL_MS)
class GraphFrame(wx.Frame): """ The main frame of the application """ title = 'Demo: dynamic matplotlib graph' def __init__(self): wx.Frame.__init__(self, None, -1, self.title) self.datagen = DataGen() self.data = [self.datagen.next()] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REFRESH_INTERVAL_MS) def create_menu(self): self.menubar = wx.MenuBar() menu_file = wx.Menu() m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file") self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt) menu_file.AppendSeparator() m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) self.menubar.Append(menu_file, "&File") self.SetMenuBar(self.menubar) def create_main_panel(self): self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) self.xmin_control = BoundControlBox(self.panel, -1, "X min", 0) self.xmax_control = BoundControlBox(self.panel, -1, "X max", 50) self.ymin_control = BoundControlBox(self.panel, -1, "Y min", 0) self.ymax_control = BoundControlBox(self.panel, -1, "Y max", 100) self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.cb_grid = wx.CheckBox(self.panel, -1, "Show Grid", style=wx.ALIGN_RIGHT) self.Bind(wx.EVT_CHECKBOX, self.on_cb_grid, self.cb_grid) self.cb_grid.SetValue(True) self.cb_xlab = wx.CheckBox(self.panel, -1, "Show X labels", style=wx.ALIGN_RIGHT) self.Bind(wx.EVT_CHECKBOX, self.on_cb_xlab, self.cb_xlab) self.cb_xlab.SetValue(True) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox1.AddSpacer(20) self.hbox1.Add(self.cb_grid, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox1.AddSpacer(10) self.hbox1.Add(self.cb_xlab, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.hbox2.Add(self.xmin_control, border=5, flag=wx.ALL) self.hbox2.Add(self.xmax_control, border=5, flag=wx.ALL) self.hbox2.AddSpacer(24) self.hbox2.Add(self.ymin_control, border=5, flag=wx.ALL) self.hbox2.Add(self.ymax_control, border=5, flag=wx.ALL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.vbox.Add(self.hbox2, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) self.vbox.Fit(self) def create_status_bar(self): self.statusbar = self.CreateStatusBar() def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('black') self.axes.set_title('Arduino Serial Data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color=(1, 1, 0), )[0] def draw_plot(self): """ Redraws the plot """ # when xmin is on auto, it "follows" xmax to produce a # sliding window effect. therefore, xmin is assigned after # xmax. # if self.xmax_control.is_auto(): xmax = len(self.data) if len(self.data) > 50 else 50 else: xmax = int(self.xmax_control.manual_value()) if self.xmin_control.is_auto(): xmin = xmax - 50 else: xmin = int(self.xmin_control.manual_value()) # for ymin and ymax, find the minimal and maximal values # in the data set and add a mininal margin. # # note that it's easy to change this scheme to the # minimal/maximal value in the current display, and not # the whole data set. # if self.ymin_control.is_auto(): ymin = round(min(self.data), 0) - 1 else: ymin = int(self.ymin_control.manual_value()) if self.ymax_control.is_auto(): ymax = round(max(self.data), 0) + 1 else: ymax = int(self.ymax_control.manual_value()) self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # anecdote: axes.grid assumes b=True if any other flag is # given even if b is set to False. # so just passing the flag into the first statement won't # work. # if self.cb_grid.IsChecked(): self.axes.grid(True, color='gray') else: self.axes.grid(False) # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=self.cb_xlab.IsChecked()) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_cb_grid(self, event): self.draw_plot() def on_cb_xlab(self, event): self.draw_plot() def on_save_plot(self, event): file_choices = "PNG (*.png)|*.png" dlg = wx.FileDialog( self, message="Save plot as...", defaultDir=os.getcwd(), defaultFile="plot.png", wildcard=file_choices, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi) self.flash_status_message("Saved to %s" % path) def on_redraw_timer(self, event): # if paused do not add data, but still redraw the plot # (to respond to scale modifications, grid change, etc.) # if not self.paused: self.data.append(self.datagen.next()) self.draw_plot() def on_exit(self, event): self.Destroy() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('')
class GraphFrame(wx.Frame): title = 'Dynamic plot' def __init__(self): wx.Frame.__init__(self, None, -1, self.title) self.datagen = DataGen() self.data = [self.datagen.next()] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REFRESH_INTERVAL_MS) def create_menu(self): self.menubar = wx.MenuBar() menu_file = wx.Menu() m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file") self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt) menu_file.AppendSeparator() m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) self.menubar.Append(menu_file, "&File") self.SetMenuBar(self.menubar) def create_main_panel(self): self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) self.xmin_control = BoundControlBox(self.panel, -1, "X min", 0) self.xmax_control = BoundControlBox(self.panel, -1, "X max", 50) self.ymin_control = BoundControlBox(self.panel, -1, "Y min", 0) self.ymax_control = BoundControlBox(self.panel, -1, "Y max", 100) self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.cb_grid = wx.CheckBox(self.panel, -1, "Show Grid", style=wx.ALIGN_RIGHT) self.Bind(wx.EVT_CHECKBOX, self.on_cb_grid, self.cb_grid) self.cb_grid.SetValue(True) self.cb_xlab = wx.CheckBox(self.panel, -1, "Show X labels", style=wx.ALIGN_RIGHT) self.Bind(wx.EVT_CHECKBOX, self.on_cb_xlab, self.cb_xlab) self.cb_xlab.SetValue(True) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox1.AddSpacer(20) self.hbox1.Add(self.cb_grid, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox1.AddSpacer(10) self.hbox1.Add(self.cb_xlab, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.hbox2.Add(self.xmin_control, border=5, flag=wx.ALL) self.hbox2.Add(self.xmax_control, border=5, flag=wx.ALL) self.hbox2.AddSpacer(24) self.hbox2.Add(self.ymin_control, border=5, flag=wx.ALL) self.hbox2.Add(self.ymax_control, border=5, flag=wx.ALL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.vbox.Add(self.hbox2, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) self.vbox.Fit(self) def create_status_bar(self): self.statusbar = self.CreateStatusBar() def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('black') self.axes.set_title('Arduino Serial Data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color=(1, 1, 0), )[0] def draw_plot(self): """ Redraws the plot """ # when xmin is on auto, it "follows" xmax to produce a # sliding window effect. therefore, xmin is assigned after # xmax. # if self.xmax_control.is_auto(): xmax = len(self.data) if len(self.data) > 50 else 50 else: xmax = int(self.xmax_control.manual_value()) if self.xmin_control.is_auto(): xmin = xmax - 50 else: xmin = int(self.xmin_control.manual_value()) # for ymin and ymax, find the minimal and maximal values # in the data set and add a mininal margin. # # note that it's easy to change this scheme to the # minimal/maximal value in the current display, and not # the whole data set. # if self.ymin_control.is_auto(): ymin = round(min(self.data), 0) - 1 else: ymin = int(self.ymin_control.manual_value()) if self.ymax_control.is_auto(): ymax = round(max(self.data), 0) + 1 else: ymax = int(self.ymax_control.manual_value()) self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # anecdote: axes.grid assumes b=True if any other flag is # given even if b is set to False. # so just passing the flag into the first statement won't # work. # if self.cb_grid.IsChecked(): self.axes.grid(True, color='gray') else: self.axes.grid(False) # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=self.cb_xlab.IsChecked()) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_cb_grid(self, event): self.draw_plot() def on_cb_xlab(self, event): self.draw_plot() def on_save_plot(self, event): file_choices = "PNG (*.png)|*.png" dlg = wx.FileDialog( self, message="Save plot as...", defaultDir=os.getcwd(), defaultFile="plot.png", wildcard=file_choices, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi) self.flash_status_message("Saved to %s" % path) def on_redraw_timer(self, event): # if paused do not add data, but still redraw the plot # (to respond to scale modifications, grid change, etc.) # if not self.paused: self.data.append(self.datagen.next()) self.draw_plot() def on_exit(self, event): self.Destroy() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('')
import pygame import random from Arduino_Monitor import SerialData #arduino_analog_input ard_an = SerialData() #Define color BLACK=( 0, 0, 0) WHITE=(255, 255, 255) GREEN=( 0, 255, 0 ) RED=(255, 0, 0 ) BLUE=( 0, 0, 255) pygame.init() screen_x = 800 screen_y = 550 pad_x = 400 click_sound = pygame.mixer.Sound("/usr/share/kde4/apps/marble/data/audio/KDE-Sys-List-End.ogg") #background_image = pygame.image.load("pic.jpg").convert() size = (screen_x, screen_y) screen = pygame.display.set_mode(size)
class Main(QMainWindow, Ui_MainWindow): def __init__(self): super(Main, self).__init__() self.setupUi(self) self.set_port() self.update_port() self.paused = False self.init_plot() self.canvas = FigureCanvas(self.fig) self.navToolbar = NavigationToolbar(self.canvas, self.graphFrame) # self.canvas.setParent(self.graphFrame) self.graphLayout.addWidget(self.canvas) self.graphLayout.addWidget(self.navToolbar) # self.canvas.setSizePolicy(QSizePolicy.Expanding, # QSizePolicy.Expanding) # self.canvas.updateGeometry() self.draw_plot() self.cbPort.currentIndexChanged.connect(self.update_port) self.cbBaudrate.currentIndexChanged.connect(self.update_port) self.cbBytesize.currentIndexChanged.connect(self.update_port) self.cbParity.currentIndexChanged.connect(self.update_port) self.cbStopbits.currentIndexChanged.connect(self.update_port) self.spbTimeout.valueChanged.connect(self.update_port) self.btnDefault.clicked.connect(self.on_btnDefault_clicked) self.btnPause.clicked.connect(self.on_btnPause_clicked) self.btnPause.clicked.connect(self.on_update_btnPause_clicked) self.chbGrid.stateChanged.connect(self.on_chbGrid_stateChanged) self.chbXlabel.stateChanged.connect(self.on_chbXlabel_stateChanged) self.redraw_timer = QTimer(self) self.redraw_timer.timeout.connect(self.on_redraw_timer) self.redraw_timer.start(100) def set_port(self): # 设置端口 self.cbPort.setCurrentIndex(4) self.cbBaudrate.addItems([str(baudrate) for baudrate in serial.Serial.BAUDRATES]) self.cbBaudrate.setCurrentIndex(12) # 9600 self.cbBytesize.addItems([str(bytesize) for bytesize in serial.Serial.BYTESIZES]) self.cbBytesize.setCurrentIndex(3) # 8 self.cbParity.addItems([str(parity) for parity in serial.Serial.PARITIES]) self.cbParity.setCurrentIndex(0) # None self.cbStopbits.addItems([str(stopbits) for stopbits in serial.Serial.STOPBITS]) self.cbStopbits.setCurrentIndex(0) # 1 self.spbTimeout.setValue(0.01) def update_port(self): self.port = self.cbPort.currentIndex() self.baudrate = serial.Serial.BAUDRATES[self.cbBaudrate.currentIndex()] self.bytesize = serial.Serial.BYTESIZES[self.cbBytesize.currentIndex()] self.parity = serial.Serial.PARITIES[self.cbParity.currentIndex()] self.stopbits = serial.Serial.STOPBITS[self.cbStopbits.currentIndex()] self.timeout = self.spbTimeout.value() self.datagen = DataGen(port=self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, timeout=self.timeout) self.data = [self.datagen.next()] def init_plot(self): self.dpi = 100 self.fig = Figure((8.0, 6.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('black') self.axes.set_title('Arduino Serial Data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color=(1, 1, 0), )[0] def draw_plot(self): """ Redraws the plot """ # when xmin is on auto, it "follows" xmax to produce a # sliding window effect. therefore, xmin is assigned after # xmax. # if self.rbXmaxAuto.isChecked(): xmax = len(self.data) if len(self.data) > 50 else 50 else: xmax = float(self.XmaxManu.value()) if self.rbXminAuto.isChecked(): xmin = xmax - 50 else: xmin = float(self.XminManu.value()) # for ymin and ymax, find the minimal and maximal values # in the data set and add a mininal margin. # # note that it's easy to change this scheme to the # minimal/maximal value in the current display, and not # the whole data set. # if self.rbYminAuto.isChecked(): ymin = round(min(self.data), 0) - 1 else: ymin = int(self.YminManu.value()) if self.rbYmaxAuto.isChecked(): ymax = round(max(self.data), 0) + 1 else: ymax = int(self.YmaxManu.value()) self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # anecdote: axes.grid assumes b=True if any other flag is # given even if b is set to False. # so just passing the flag into the first statement won't # work. # if self.chbGrid.isChecked(): self.axes.grid(True, color='gray') else: self.axes.grid(False) # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=self.chbXlabel.isChecked()) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_btnDefault_clicked(self): self.set_port() self.update_port() def on_btnPause_clicked(self): self.paused = not self.paused def on_update_btnPause_clicked(self): label = u"继续" if self.paused else u"暂停" self.btnPause.setText(label) def on_chbGrid_stateChanged(self): self.draw_plot() def on_chbXlabel_stateChanged(self): self.draw_plot() def on_redraw_timer(self): # if paused do not add data, but still redraw the plot # (to respond to scale modifications, grid change, etc.) # if not self.paused: self.data.append(self.datagen.next()) self.draw_plot()
self.message_timer.Start(display_time, oneShot=True) def on_flash_status_off(self, event): self.status_bar.SetStatusText('') def parse_script_args(): parser = argparse.ArgumentParser() parser.add_argument("port", help="serial port to be used") parser.add_argument("-b", "--baudrate", type=int, help="port baud rate") parser.add_argument("-t", "--timeout", type=float, help="port timeout value") args = parser.parse_args() return {key: val for key, val in vars(args).iteritems() if val is not None} if __name__ == "__main__": kwargs = parse_script_args() data_source = SerialData(**kwargs) app = wx.App() app.frame = GraphFrame(data_source) app.frame.Show() app.MainLoop()