Exemplo n.º 1
0
 def port(self):
     '''
     :list_ports: This module will provide a function called comports that 
         returns an iterable (generator or list) that will enumerate 
         available com ports. Note that on some systems non-existent ports 
         may be listed.
         
     :start_stream: Start handling streaming data from the board. 
         Call a provided callback for every single sample that is processed.
     '''
     Lista_puertos = list_ports.comports()
     print(Lista_puertos)
     for serial_device in Lista_puertos:
         code_serial = serial_device.serial_number
         if code_serial != None:
             if code_serial.startswith(serial_openBCI):
                 board = OpenBCICyton(port=serial_device.device,
                                      daisy=False)
                 Data = self.lslStreamers
                 board.start_stream(Data)
             else:
                 print(
                     'No hay dispositivo OpenBCI, conectar y volver a iniciar el programa'
                 )
                 input('Presione enter para finalizar ...')
Exemplo n.º 2
0
def printChannel(channelNum):
    try:
        board = OpenBCICyton(daisy=True)
    except Exception as e:
        id.makeErrorPopup(str(e))
        return

    callback = partial(printChannelsCallback, channelNum=channelNum)
    board.start_stream(callback)
    def start_board_Ultracortex():
        global board

        try:
            board = OpenBCICyton("COM3", daisy=True)
            board.start_stream(ui.save_data_EEG)

        except:
            #ui.Errores("DONGLE DESCONECTADO")
            print("DONGLE DESCONECTADO")
Exemplo n.º 4
0
class EEGRecorder:
    def __init__(self):
        self.__board = None
        self.__outlet_eeg = None
        self.__outlet_aux = None
        self.__createEEGStream()

    def __createEEGStream(self):
        info_eeg = StreamInfo(name='OpenBCI EEG',
                              type='EEG',
                              channel_count=8,
                              nominal_srate=250,
                              channel_format='float32',
                              source_id='eeg_thread')
        info_aux = StreamInfo(name='OpenBCI AUX',
                              type='AUX',
                              channel_count=3,
                              nominal_srate=250,
                              channel_format='float32',
                              source_id='aux_thread')

        self.__outlet_eeg = StreamOutlet(info_eeg)
        self.__outlet_aux = StreamOutlet(info_aux)
        # append some meta-data
        # info.desc().append_child_value("manufacturer", "OpenBCI")
        # channels = info.desc().append_child("channels")
        # for c in ["Fp1", "Fp2", "FPz", "A1"]:
        #     channels.append_child("channel")\
        #         .append_child_value("name", c)\
        #         .append_child_value("unit", "microvolts")\
        #         .append_child_value("type", "EEG")

        # next make an outlet; we set the transmission chunk size to 32 samples and
        # the outgoing buffer size to 360 seconds (max.)
        # outlet = StreamOutlet(info, 32, 360)

    def __lsl_streamers(self, sample):
        self.__outlet_eeg.push_sample(
            np.array(sample.channels_data) * SCALE_FACTOR_EEG)
        self.__outlet_aux.push_sample(
            np.array(sample.aux_data) * SCALE_FACTOR_AUX)

    def runSession(self):
        self.__createEEGStream()
        # eeg_thread = threading.Thread(target=self.__board.start_stream, args=(self.__lsl_streamers,))
        # eeg_thread.start()
        try:
            self.__board = OpenBCICyton()
            self.__board.start_stream(self.__lsl_streamers)
        except (KeyboardInterrupt, SystemExit):
            self.__board.stop_stream()
            sys.exit()
Exemplo n.º 5
0
def main():
    TIMEOUT = 60

    #Set (daisy = True) to stream 16 ch
    board = OpenBCICyton(daisy=True)

    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(TIMEOUT)
    try:
        board.start_stream(print_raw)
    except Exception as e:
        print("timed out")
        board.stop_stream()
        sys.exit(0)
Exemplo n.º 6
0
 def port(self):
     '''
     Rec: Samples from the device (Samples)
     Func: Evaluate the list of ports in use and set the port to use.
     '''
     Lista_puertos = list_ports.comports()
     print(Lista_puertos)
     for serial_device in Lista_puertos:
         code_serial = serial_device.serial_number
         if code_serial != None:
             if code_serial.startswith(serial_openBCI):
                 board = OpenBCICyton(
                     port=serial_device.device, daisy=False)
                 Data = self.lslStreamers
                 board.start_stream(Data)
             else:
                 print(
                     'No hay dispositivo OpenBCI, conectar y volver a iniciar el programa')
                 input('Presione enter para finalizar ...')
Exemplo n.º 7
0
def stream():
    #print(address)
    #print(name)
    print(
        "Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n"
    )

    info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 16, 250, 'float32',
                          'OpenBCItestEEG')

    # print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

    # info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')

    info_eeg.desc().append_child_value("manufacturer", "OpenBCI")
    eeg_channels = info_eeg.desc().append_child("channels")

    for c in [
            'Fp1', 'Fp2', 'C3', 'C4', 'P7', 'P8', 'O1', 'O2', 'F7', 'F8', 'F3',
            'F4', 'T7', 'T8', 'P3', 'P4'
    ]:
        eeg_channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", "microvolts") \
            .append_child_value("type", "EEG")

    # eeg_outlet = StreamOutlet(eeg_info, LSL_EEG_CHUNK)

    outlet_eeg = StreamOutlet(info_eeg)

    # outlet_aux = StreamOutlet(info_aux)

    def lsl_streamers(sample):
        outlet_eeg.push_sample(
            np.array(sample.channels_data) * SCALE_FACTOR_EEG)
        # outlet_aux.push_sample(np.array(sample.aux_data)*SCALE_FACTOR_AUX)

    #board = OpenBCICyton(port='COM3', daisy=True)
    board = OpenBCICyton(port='/dev/tty.usbserial-DM01N7JO', daisy=True)

    board.start_stream(lsl_streamers)
Exemplo n.º 8
0
            np.array(sample.channels_data[3]) * SCALE_FACTOR_EEG)
        data['CP2'].append(
            np.array(sample.channels_data[4]) * SCALE_FACTOR_EEG)
        data['T8'].append(np.array(sample.channels_data[5]) * SCALE_FACTOR_EEG)
        data['O2'].append(np.array(sample.channels_data[6]) * SCALE_FACTOR_EEG)
        data['O1'].append(np.array(sample.channels_data[7]) * SCALE_FACTOR_EEG)
        if len(data['FT7']) % 125 == 0:
            json_data = {
                'raw': [
                    data['FT7'], data['FT8'], data['T7'], data['CP1'],
                    data['CP2'], data['T8'], data['O2'], data['O1']
                ]
            }
            requests.post('http://0.0.0.0:5000/compute_psd', json=json_data)
            requests.post('http://0.0.0.0:5000/store_raw', json=json_data)

    elif len(data['FT7']) == 1000:
        requests.post('http://0.0.0.0:5000/predictml', json=data)
        data['FT7'] = []
        data['FT8'] = []
        data['T7'] = []
        data['CP1'] = []
        data['CP2'] = []
        data['T8'] = []
        data['O2'] = []
        data['O1'] = []


board = OpenBCICyton(port='/dev/ttyUSB1', daisy=True)
board.start_stream(process_predict)
Exemplo n.º 9
0
class FrameGesto1(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          parent,
                          id=wx.ID_ANY,
                          title=u"Captura de señales para el gesto 1",
                          pos=wx.DefaultPosition,
                          size=wx.Size(1400, 1000),
                          style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)
        bSizer4 = wx.BoxSizer(wx.VERTICAL)
        self.panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)

        self.panel.SetSizer(sizer)
        self.m_staticText2 = wx.StaticText(
            self, wx.ID_ANY, u"Captura de señales para el primer gesto \n",
            wx.DefaultPosition, wx.Size(700, -1), 0)
        self.m_staticText2.Wrap(-1)
        self.m_staticText2.SetFont(
            wx.Font(34, 70, 90, 90, False, wx.EmptyString))

        bSizer4.Add(self.m_staticText2, 0, wx.ALIGN_CENTER_HORIZONTAL, 10)

        bSizer49 = wx.BoxSizer(wx.VERTICAL)

        bSizer50 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer50.SetMinSize(wx.Size(700, 50))
        self.m_staticText30 = wx.StaticText(
            self, wx.ID_ANY,
            u"Para iniciar el experimento por favor observe \n ",
            wx.DefaultPosition, wx.Size(1000, -1), 0)
        self.m_staticText30.Wrap(-1)
        self.m_staticText30.SetFont(
            wx.Font(17, 70, 90, 90, False, wx.EmptyString))

        bSizer50.Add(self.m_staticText30, 0, wx.ALL, 5)

        bSizer52 = wx.BoxSizer(wx.VERTICAL)

        bSizer52.SetMinSize(wx.Size(90, -1))
        self.m_button32 = wx.Button(self, wx.ID_ANY, u"Inicio",
                                    wx.Point(-1, -1), wx.Size(150, -1), 0)
        self.m_button32.SetFont(wx.Font(25, 70, 90, 90, False, wx.EmptyString))

        bSizer52.Add(self.m_button32, 0, wx.TOP, 10)

        bSizer50.Add(bSizer52, 1, 0, 5)

        self.m_animCtrl1 = AnimationCtrl(self,
                                         pos=(40, 40),
                                         size=(14, 14),
                                         name="AnimationCtrl")
        self.m_animCtrl1.LoadFile(
            r"C:\Users\crist\OneDrive\Escritorio\Universidad\LASER\Tesis\Open_BCI_and_MYO_UD\GUI_Adquisicion/manos.gif"
        )
        self.m_animCtrl1.Play()
        self.m_animCtrl1.SetMinSize(wx.Size(200, -1))

        bSizer50.Add(self.m_animCtrl1, 0, wx.ALIGN_CENTER, 5)

        bSizer49.Add(bSizer50, 1, 0, 5)

        bSizer51 = wx.BoxSizer(wx.VERTICAL)
        bSizer57 = wx.BoxSizer(wx.HORIZONTAL)

        # grafica EMG
        self.figureEMG = plt.figure(figsize=(1, 6), dpi=60)
        self.axes = [
            self.figureEMG.add_subplot('81' + str(i)) for i in range(1, 9)
        ]
        self.n = 512
        [(ax.set_ylim(ymin=-200, ymax=200)) for ax in self.axes]
        global graphs
        self.graphs = [
            ax.plot(np.arange(self.n), np.zeros(self.n))[0] for ax in self.axes
        ]
        plt.ion()
        self.canvEMG = FigureCanvas(self, wx.ID_ANY, self.figureEMG)
        bSizer57.Add(self.canvEMG, 1, wx.TOP | wx.LEFT | wx.EXPAND)

        # grafica EEG
        self.figureEEG = plt.figure(figsize=(1, 6), dpi=60)
        self.axesEEG = [
            self.figureEEG.add_subplot('81' + str(i)) for i in range(1, 9)
        ]
        [(ax.set_ylim([-150000, 150000])) for ax in self.axesEEG]
        self.m = 100
        self.graphsEEG = [
            ax.plot(np.arange(self.m), np.zeros(self.m))[0]
            for ax in self.axesEEG
        ]
        plt.ion()
        self.canvasEEG = FigureCanvas(self, -1, self.figureEEG)
        bSizer57.Add(self.canvasEEG, 1, wx.TOP | wx.LEFT | wx.EXPAND)

        bSizer51.Add(bSizer57, 1, wx.EXPAND, 5)

        bSizer49.Add(bSizer51, 1, wx.EXPAND, 5)

        bSizer53 = wx.BoxSizer(wx.HORIZONTAL)

        self.m_staticText31 = wx.StaticText(self, wx.ID_ANY,
                                            u"Señal EMG", wx.DefaultPosition,
                                            wx.Size(700, 30), 0)
        self.m_staticText31.Wrap(-1)
        self.m_staticText31.SetFont(
            wx.Font(18, 70, 90, 90, False, wx.EmptyString))

        bSizer53.Add(self.m_staticText31, 0, wx.LEFT, 5)

        self.m_staticText32 = wx.StaticText(self, wx.ID_ANY,
                                            u"Señal EEG", wx.DefaultPosition,
                                            wx.Size(-1, 30), 0)
        self.m_staticText32.Wrap(-1)
        self.m_staticText32.SetFont(
            wx.Font(18, 70, 90, 90, False, wx.EmptyString))

        bSizer53.Add(self.m_staticText32, 0, 0, 5)

        bSizer49.Add(bSizer53, 1, 0, 5)

        bSizer8 = wx.BoxSizer(wx.HORIZONTAL)

        self.m_staticText33 = wx.StaticText(self, wx.ID_ANY,
                                            u"Tiempo:", wx.DefaultPosition,
                                            wx.Size(550, -1), 0)
        self.m_staticText33.Wrap(-1)
        self.m_staticText33.SetFont(
            wx.Font(18, 70, 90, 90, False, wx.EmptyString))
        bSizer8.Add(self.m_staticText33, 0, wx.ALL, 5)
        pos = wx.DefaultPosition
        size = wx.Size(1, 11)
        style = gizmos.LED_ALIGN_CENTER
        self.led = gizmos.LEDNumberCtrl(self, -1, pos, size, style)
        self.led.SetBackgroundColour("white")
        self.led.SetForegroundColour("black")
        bSizerTimmer = wx.BoxSizer(wx.VERTICAL)
        bSizerTimmer.Add(self.led, 1, wx.TOP | wx.LEFT | wx.EXPAND)
        bSizer49.Add(bSizerTimmer, 1, wx.EXPAND, 5)

        self.button_siguiente = wx.Button(self, wx.ID_ANY,
                                          u"Aceptar", wx.DefaultPosition,
                                          wx.Size(150, -1), 0)
        self.button_siguiente.SetFont(
            wx.Font(18, 70, 90, 90, False, wx.EmptyString))

        bSizer8.Add(self.button_siguiente, 0, wx.ALL, 5)

        self.button_salir = wx.Button(self, wx.ID_ANY, u"Salir",
                                      wx.DefaultPosition, wx.Size(150, -1), 0)
        self.button_salir.SetFont(
            wx.Font(18, 70, 90, 90, False, wx.EmptyString))

        bSizer8.Add(self.button_salir, 0, wx.ALL, 5)

        bSizer49.Add(bSizer8, 0, wx.TOP, 1)

        bSizer4.Add(bSizer49, 1, wx.EXPAND, 5)

        self.SetSizer(bSizer4)
        self.Layout()

        self.Centre(wx.BOTH)

        # Connect Events
        self.m_button32.Bind(wx.EVT_BUTTON, self.OnClickInicio)
        self.button_siguiente.Bind(wx.EVT_BUTTON, self.OnClickConcentimiento)
        self.button_salir.Bind(wx.EVT_BUTTON, self.OnClickSalir)
        # Arrancar conexion myo
        self.conexionMYO()

        def hiloMYOConexion(arg):
            hiloConexionMYO = threading.currentThread()
            while getattr(hiloConexionMYO, "do_run", True):
                print("working on %s" % arg)
                self.mainMYO()
            print("Stopping as you wish.")

        self.hiloConexionMYO = threading.Thread(target=hiloMYOConexion,
                                                args=("PLOT_EMG_MYO", ))
        self.hiloConexionMYO.setDaemon(True)
        self.hiloConexionMYO.start()
        # Arranca conexion UltraCortex
        self.datosEEG = []
        self.start_board()

        def hiloPlotUltracortex(arg):
            hiloPlotUltracortex = threading.currentThread()
            while getattr(hiloPlotUltracortex, "do_run", True):
                print("working on %s" % arg)
                time.sleep(3)
                self.mainplotUltracortex()
            print("Stopping as you wish.")

        self.hiloPlotUltracortex = threading.Thread(
            target=hiloPlotUltracortex, args=("PLOT_EEG_ULTRACORTEX", ))
        self.hiloPlotUltracortex.setDaemon(True)
        self.hiloPlotUltracortex.start()

    def __del__(self):
        pass


# Virtual event handlers, overide them in your derived class

    def OnClickInicio(self, event):
        self.GetSegundos(None)

    def OnClickConcentimiento(self, event):
        event.Skip()

    def OnClickSalir(self, event):
        self.Close()
        sys.exit()

    def GetSegundos(self, e):
        global segundos
        self.board.stop_stream()
        self.stopconexioUltracortexPlot = True
        self.hiloPlotUltracortex.do_run = False
        self.hiloPlotUltracortex.join()
        self.stopconexion = True
        self.hiloConexionMYO.do_run = False
        self.hiloConexionMYO.join()
        dlg = wx.TextEntryDialog(self.panel,
                                 'Ingrese los segundos a grabar el gesto:',
                                 "Captura del gesto",
                                 "",
                                 style=wx.OK)
        dlg.ShowModal()
        segundos = int(dlg.GetValue())

        def hiloRunTimmer(arg):
            hiloRunTimmer = threading.currentThread()
            while getattr(hiloRunTimmer, "do_run", True):
                print("working on %s" % arg)
                self.led.SetValue("00:00")
                self.OnTimer(None, e=segundos)
            print("Stopping as you wish.")

        self.hiloRunTimmer = threading.Thread(target=hiloRunTimmer,
                                              args=("RUN_Timmer", ))
        self.hiloRunTimmer.setDaemon(True)
        self.hiloRunTimmer.start()

        def hiloMYOSaved(arg):
            hiloMYOSaved = threading.currentThread()
            while getattr(hiloMYOSaved, "do_run", True):
                print("working on %s" % arg)
                self.mainSavedMYO()
            print("Stopping as you wish.")

        self.hiloMYOSaved = threading.Thread(target=hiloMYOSaved,
                                             args=("Saved_EMG_MYO", ))
        self.hiloMYOSaved.setDaemon(True)
        self.hiloMYOSaved.start()

        def hiloUltracortesConexion(arg):
            hiloUltracortesConexion = threading.currentThread()
            while getattr(hiloUltracortesConexion, "do_run", True):
                print("working on %s" % arg)
                self.mainULTRACORTEX()
            print("Stopping as you wish.")

        self.hiloUltracortesConexion = threading.Thread(
            target=hiloUltracortesConexion, args=("SAVE_EEG_ULTRACORTEX", ))
        self.hiloUltracortesConexion.setDaemon(True)
        self.hiloUltracortesConexion.start()

        dlg.Destroy()

    def OnTimer(self, event, e):
        print("OnTimmer Inicia")
        global i
        global c
        c = e
        if (i < c):
            i += 1
            time.sleep(1)
            self.TimerGo(None)

        else:
            print("Termino Timer")
            self.board.stop_stream()
            self.stopconexioUltracortex = True
            self.hiloUltracortesConexion.do_run = False
            self.hiloUltracortesConexion.join()
            self.hiloRunTimmer.do_run = False
            self.stopsaved = True
            self.hiloMYOSaved.do_run = False
            self.hiloMYOSaved.join()

    def TimerGo(self, event):
        global s
        global m
        global t
        global c
        s = int(s)
        m = int(m)
        if (s < 59):
            s += 1
        elif (s == 59):
            s = 0
            if (m < 59):
                m += 1
            elif (m == 59):
                m = 0
        if (int(s) < 10):
            s = str(0) + str(s)
        if (int(s) > 9):
            s = str(s)
        t = str(m) + ":" + str(s)
        self.led.SetValue(t)
        self.OnTimer(None, c)

    def conexionMYO(self):
        print("Realizando Conexión MYO")
        myo.init()
        self.hub = myo.Hub()
        self.listener = EmgCollector(512)
        self.stopconexion = False
        self.stopsaved = False
        print("Conexión MYO Establecida")
        self.Crear_carpetaMYO()

    def mainMYO(self):
        global data_total
        data_total = []
        with self.hub.run_in_background(self.listener.on_event):
            while True:
                self.plotMYO()
                time.sleep(0.1)
                if (self.stopconexion == True):
                    break

    def mainSavedMYO(self):
        global fila
        fila = 0
        with self.hub.run_in_background(self.listener.on_event):
            while True:
                self.SaveMYO()
                time.sleep(2.56)
                if (self.stopsaved == True):
                    break

    def plotMYO(self):
        global graphs
        emg_data = self.listener.get_emg_data()
        emg_data = np.array([x[1] for x in emg_data]).T
        for g, data in zip(self.graphs, emg_data):
            if len(data) < self.n:
                data = np.concatenate([np.zeros(self.n - len(data)), data])
            g.set_ydata(data)
        #plt.draw()

    def SaveMYO(self):
        global fila
        global data_total
        numMuestras = 512
        emg_data = self.listener.get_emg_data()
        emg_data = [x[1] for x in emg_data]
        with open(os.path.join(carpetaEMG, "datos %d.csv" % j),
                  'a') as fp:  # Guardar datos en el archivo csv
            for h in range(0, 512):
                for i in range(0, 8):
                    fp.write(str(emg_data[h][i]) + ";")
                fp.write("\n")

    ###########################################################################
    # Ultracortex
    def start_board(self):
        global fila
        fila = 0
        self.board = OpenBCICyton(port='COM8', daisy=False)
        self.stopconexioUltracortex = False
        self.stopconexioUltracortexPlot = False
        self.Crear_carpetaEEG()

    def mainULTRACORTEX(self):
        while (self.stopconexioUltracortex == False):
            self.board.start_stream(self.save_data)

        print("entro if")
        self.board.stop_stream()

    def mainplotUltracortex(self):
        while (self.stopconexioUltracortexPlot == False):
            time.sleep(0.1)
            self.board.start_stream(self.plot_eeg)
        print("entro if")
        self.board.stop_stream()

    def plot_eeg(self, sample):
        global datosEEG, bp_a, bp_b
        global graphsEEG
        self.datosEEG.append(
            [i * (SCALE_FACTOR) for i in sample.channels_data])
        datosEEGplot = np.array(self.datosEEG).T
        # for o in range (8):
        #    datosEEGplot[o] = signal.lfilter(bp_b, bp_a, datosEEGplot[o])
        for g, data in zip(self.graphsEEG, datosEEGplot):
            if len(data) < self.m:
                data = np.concatenate([np.zeros(self.m - len(data)), data])
            else:
                data = np.array(data[(len(data) - self.m):])
            # dy = (max(data) - min(data))*0.7
            # [(ax.set_ylim([min(data)-dy, max(data)+dy])) for ax in self.axesEEG]
            g.set_ydata(data)
        #plt.draw()>:V
        self.board.stop_stream()

    def save_data(self, sample):
        global fila
        global datosEEG, bp_a, bp_b
        self.datosEEG.append(
            [i * (SCALE_FACTOR) for i in sample.channels_data])
        datosEEGplot = np.array(self.datosEEG).T
        with open(os.path.join(carpetaEEG, "datos %d.csv" % j),
                  'a') as fp:  # Guardar datos en el archivo csv
            for i in range(0, 8):
                fp.write(str(self.datosEEG[fila][i]) + ";")
            fp.write("\n")
            fila += 1

    def Crear_carpetaEEG(self):
        global carpetaEEG
        global j
        global fila
        fila = 0
        Archivo = True
        j = 1
        Tipo = "PruebaUltracortex"
        carpetaEEG = f"Base_Datos_{Tipo}"  #Creacion de carpetas para guarda archivos si no existe
        if not os.path.exists(carpetaEEG):
            os.mkdir(carpetaEEG)

        while (Archivo == True
               ):  # Se crea un archivo csv en caso de que no exista
            if os.path.isfile(carpetaEEG + "/datos %d.csv" % j):
                print('El archivo existe.')
                j += 1
            else:
                with open(os.path.join(carpetaEEG, "datos %d.csv" % j),
                          'w') as fp:
                    [fp.write('CH%d ;' % i) for i in range(1, 9)]
                    fp.write("\n")
                    print("Archivo Creado")
                    Archivo = False

    def Crear_carpetaMYO(self):
        global carpetaEMG
        global j
        global fila
        fila = 0
        Archivo = True
        j = 1
        Tipo = "PruebaMYO"
        carpetaEMG = f"Base_Datos_{Tipo}"  #Creacion de carpetas para guarda archivos si no existe
        if not os.path.exists(carpetaEMG):
            os.mkdir(carpetaEMG)

        while (Archivo == True
               ):  # Se crea un archivo csv en caso de que no exista
            if os.path.isfile(carpetaEMG + "/datos %d.csv" % j):
                print('El archivo existe.')
                j += 1
            else:
                with open(os.path.join(carpetaEMG, "datos %d.csv" % j),
                          'w') as fp:
                    [fp.write('CH%d ;' % i) for i in range(1, 9)]
                    fp.write("\n")
                    print("Archivo Creado")
                    Archivo = False
def start_board():
    board = OpenBCICyton(port='COM8', daisy=False)

    board.start_stream(save_data)
Exemplo n.º 11
0
def start_board():  # Hilo configuracion cyton y lectura de datos
    board = OpenBCICyton("COM8",
                         daisy=False)  # LLamado de la clase OpenBCYCyton.
    board.start_stream(
        ui.save_data)  # Se llama el metodo de solicitud de datos.
Exemplo n.º 12
0
        np.squeeze(raw_data),
        NFFT,
        window=mlab.window_hanning,
        Fs=fs_Hz,
        noverlap=overlap)  # returns PSD power per Hz
    # convert the units of the spectral data
    spec_PSDperBin = spec_PSDperHz * fs_Hz / float(NFFT)


def plot_spectrum_avg_fft():

    # print("Generating power spectrum plot")

    spectrum_PSDperHz = np.mean(spec_PSDperHz, 1)
    plt.figure(figsize=(10, 5))
    plt.plot(spec_freqs, 10 * np.log10(spectrum_PSDperHz))  # dB re: 1 uV
    plt.xlim((0, 60))
    plt.ylim((-30, 50))
    # plotname = 'Channel '+str(self.channel)+' Spectrum Average FFT Plot'
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('PSD per Hz (dB re: 1uV^2/Hz)')

    # plt.title(self.plot_title("Power Spectrum"))
    # self.plotit(plt, self.plot_filename("Power Spectrum"))


board = OpenBCICyton(port='/dev/ttyUSB2', daisy=False)

board.start_stream(process_raw)

plt.close()
Exemplo n.º 13
0
    global rawBuffer, filterBuffer
    #print(rawBuffer)
    filterBuffer[:-window_size] = filterBuffer[window_size:]
    filterBuffer[-window_size:] = rawBuffer

    last64 = remove_dc_offset()
    notch_filter()
    bandpass()
    #plot(rawBuffer, last64)
    #plot2()
    #get_spectrum_data()
    #makePlot()
    plt.pause(0.0001)
    ax1.clear()
    #time.sleep(1)


plt.ion()
plt.show()
print("AFTER PYQT")

board = OpenBCICyton(port='/dev/ttyUSB0', daisy=False)
while (True):
    data = board.start_stream(1)
    print(data)
    acquire_raw(data[0])

#t1 = threading.Thread(target=board.start_stream, args=(acquire_raw,))
#board.start_stream(acquire_raw)
#t1.start()
Exemplo n.º 14
0
        keep_block = arr2D.shape[1] * (SAMPLES_PER_FRAME - 1)
        im_data = np.delete(im_data, np.s_[:-keep_block], 1)
        im_data = np.hstack((im_data, arr2D))
        im.set_array(im_data)
    return im,


#main program
arr2D, freqs, bins = get_specgram(streamedData.channels_data[0] * ((4.5)/24/(2**23-1)))
"""
   Setup the plot paramters
   """
extent = (bins[0], bins[-1] * SAMPLES_PER_FRAME, freqs[-1], freqs[0])
im = plt.imshow(arr2D, aspect='auto', extent=extent, interpolation="none",
                cmap='jet', norm=LogNorm(vmin=.01, vmax=1))
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')


plt.title('Real Time Spectogram')
plt.gca().invert_yaxis()
##plt.colorbar() #enable if you want to display a color bar

anim = animation.FuncAnimation(fig, update_fig, blit=False,interval=10)
                               # interval=mic_read.CHUNK_SIZE / 1000)
plt.show(block=False)

board = OpenBCICyton(port='/dev/ttyUSB0', daisy=False)
#call back fn
board.start_stream(get_data)