def read_data():
    data = ser.readline().decode()
    while data.isspace():  # if faulty reading (whitespace), keep trying
        data = ser.readline().decode()
    millis = str(round(time.time() * 1000))
    datafile.write(data + ',' + millis)
    return list(map(int, data.split(",")))
Exemple #2
0
def update():
    global sample_plot, samples, sample_count, start_time_ms
   
    line = raw.readline().strip()
    if (chr(line[0]) == "#"):
        print(line)
        return
    line_list = line.decode('ascii').split(' ')
    samples.extend(list(map(int, line_list)))
    sample_count = sample_count + len(line_list)
    
    if (len(samples) > samples_to_show):
        del samples[0:4]
        
    if (sample_count % (samples_to_show / 2) == 0):
        delta_time_s = (time.time() - start_time_s)
        print("Sample rate = " + str(sample_count/delta_time_s))
        
    np_samples = np.array(samples, dtype='uint32')
    sample_plot.setData(np_samples)
    app.processEvents()
Exemple #3
0
def update():
    global curve, data
    line = ser.readline()
    try:
        # 188uV per bit is ADS1115 16-bit ADC scaling (5V)
        # 3.223mV per bit is Arduino Yun Mini 10-bit ADS scaling (3.3V)
        data.append(float(line) * 3.223)  # Scaling factor
        t.append(time.time() - start_time)
        curve.setData(t, data)
        # data_filtered = f.butter_lowpass_filter(rate=100, data=data, freqHighCutoff=45, order=5)
        # curve.setData(t, data_filtered)
        p.setXRange(t[-1] - 5, t[-1] + 1)
        app.processEvents()
        # print('time taken = ' + str((t[-1]-t[-2])*1000) + 'ms')
        # print('bits waiting=' + str(ser.in_waiting), 'mseconds=' + str((t[-1] - t[-2])*1000), 'data=' + str(data[-1]))
        if len(data) > 5000:
            del data[0:-2]
            del t[0:-2]
        if ser.in_waiting > 100:
            print('queue buffer is incresing', ser.in_waiting)
    except ValueError:
        print('!!! VALUE ERROR', line)
def update():
    global curve, data

    bytesR_H = raw.read()
    bytesR_L = raw.read()
    valueR = (ord(bytesR_H) << 5) + ord(bytesR_L)
    # raw.flushInput()
    # raw.flushOutput()

    global i

    elapsedtime = time.time() - start_time

    datax.append(elapsedtime)
    datay.append(valueR)
    xdata = datax
    ydata = datay

    # filtering
    i += 1
    data_filter.append(
        sum([x * y for x, y in zip(filter_coef, ydata[i:i + 18])]))

    # print(data_filter[i])

    # display filtered data
    if (i % 2) == 0:
        curve1.setData(xdata, ydata)
        # app.processEvents()
        p1.setXRange(elapsedtime - 3, elapsedtime)

        curve2.setData(xdata, data_filter)
        # app.processEvents()
        p2.setXRange(elapsedtime - 3, elapsedtime)

    #record data
    now = datetime.now()
    current_time = now.strftime("%y%m%d_%H%M%S")
    print(current_time, ',', valueR, file=record)
def update():
    global curve, data
    line = ser.readline()

    try:
        data = float(line)
        angle.append(180 - (data - arm_straight) /
                     (arm_bent - arm_straight) * 135)
        t.append(time.time() - start_time)
        # curve.setData(t, angle)
        angle_filtered = f.butter_lowpass_filter(rate=100,
                                                 data=angle,
                                                 freqHighCutoff=45,
                                                 order=5)
        curve.setData(t, angle_filtered)
        p.setXRange(t[-1] - 5, t[-1] + 1)
        app.processEvents()
        # print('time taken = ' + str((t[-1]-t[-2])*1000) + 'ms')
        # print('bits waiting=' + str(ser.in_waiting), 'mseconds=' + str((t[-1] - t[-2])*1000), 'data=' + str(data[-1]))
        if ser.in_waiting > 100:
            print('queue buffer is incresing', ser.in_waiting)
    except ValueError:
        print('!!! VALUE ERROR', line)
Exemple #6
0
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
import serial
import time
import software.signal_filters as f

app = QtGui.QApplication([])

start_time = time.time()

p = pg.plot()
p.setWindowTitle('live plot from serial')
p.setLabels(left=('millivolts', 'mV'))
curve = p.plot()

data = [0]
ser = serial.Serial("COM6", 9600, timeout=0.5)
t = [0]


def update():
    global curve, data
    line = ser.readline()
    try:
        # 188uV per bit is ADS1115 16-bit ADC scaling (5V)
        # 3.223mV per bit is Arduino Yun Mini 10-bit ADS scaling (3.3V)
        data.append(float(line) * 3.223)  # Scaling factor
        t.append(time.time() - start_time)
        curve.setData(t, data)
Exemple #7
0
        return
    line_list = line.decode('ascii').split(' ')
    samples.extend(list(map(int, line_list)))
    sample_count = sample_count + len(line_list)
    
    if (len(samples) > samples_to_show):
        del samples[0:4]
        
    if (sample_count % (samples_to_show / 2) == 0):
        delta_time_s = (time.time() - start_time_s)
        print("Sample rate = " + str(sample_count/delta_time_s))
        
    np_samples = np.array(samples, dtype='uint32')
    sample_plot.setData(np_samples)
    app.processEvents()

if __name__ == '__main__':
    plt = pg.plot()
    plt.setWindowTitle("ADPD4000Z-PPG Eval Board Data Plot")
    sample_plot = plt.plot(pen='r')
    samples = []
    raw = serial.Serial(com_port, 115200)
    
    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.start(0)
    
    start_time_s = time.time()
    
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Exemple #8
0
p.addLegend()
#p.showGrid(True, True, 0.1)

curve = p.plot(name='my black curve')

pen = pg.mkPen(color='k')
curve.setPen(pen)

another_curve = p.plot(name='my red curve')
another_curve.setPen(pg.mkPen(color='r'))

print p.listDataItems()

x = np.arange(10**5)
y = np.random.random(10**5)
itr = 0
import time
t = time.time()
app.processEvents()  ## force complete redraw for every plot
while True:
    itr += 1
    curve.clear()
    another_curve.clear()
    curve.setData(x[0:itr], y[0:itr])
    another_curve.setData(x[0:itr], 5 + y[0:itr])
    app.processEvents()  ## force complete redraw for every plot

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Exemple #9
0
def runEpoch(mmc,device,rep):
    import time
    
    global epoch_seq #epochs items as list (name,exp,led,odor,duration,noRec)
    global meta_index # list: epoch name, start frame, end frame
    
    namep=window.path.text()
    print "create hdf5" 
    hdfpath = createHdf5andClose(namep,savepath)
    
    
    n_epoch=len(epoch_seq)
    total =0
    epoch_times =[]
    
    eps = 0.005 #delay... error in time passed
    lj_delay = 0#0.012
    count = 1 #epoch 0 effectuated before loop
    m=0 #tiff saving index
    namep=window.path.text()
    print "namep..."+str(namep)

    window.progressBar.setMinimum(0)
    
    window.progressBar.setMaximum(n_epoch+(rep-1)*n_epoch)

    print str(n_epoch)
    for i in range(n_epoch):
        total += epoch_seq[i][4]
        epoch_times.append(total)
    print str(n_epoch)+" epochs"
    print "should take "+str(total)+"s and repeated "+str(rep)+" time(s)"

    mmc.prepareSequenceAcquisition('Zyla')
    #print "preparing sequence acquisition took", time.clock()-start, "seconds"                                         
    
#    cv2.namedWindow('Video')
    
    text_file_globalTime = open(savepath+"/globalTime"+namep+".txt", 'w')
    #text_file_globalTime.write(str(time.clock()-start)+",  "+ser.readline()+"\n")
    
    
    for i in range(rep): #LOOP FOR TRIALS
            print "trial "+str(i+1)
            text_file = open(savepath+"/respi"+namep+"_trial_"+str(i+1)+".txt", 'w')
            text_file_globalTime.write( str(time.time())+",  "+str(i+1)+"\n")
            frame_i=0
                         
            #mmc.setProperty(DEVICE[0], 'Exposure', epoch_seq[0][1])
            setLed(device,epoch_seq[0][2])
            setOdor(device,epoch_seq[0][3])
            mmc.initializeCircularBuffer()                          
            mmc.startContinuousSequenceAcquisition(10)
            
            start=time.clock()  

            while time.clock()-start < total:
                if  mmc.getRemainingImageCount()>0 :
                    im = mmc.popNextImage()
                    #im = mmc.getLastImage()
                    #cv2.imshow('Video', im)  
                    #raw_input("pause")   
                    frames.append(im)
                    timestamps.append(time.clock()-start) #0.6s from start !!!
                    meta.append( (epoch_seq[count-1], i)) 
                
                if  (count < n_epoch) and (time.clock()-start+eps > epoch_times[count-1]) :
                    print "count "+str(count)
                    print epoch_seq[count-1][0]

                    print frame_i
                    print len(frames)-1
                    #mmc.setProperty(DEVICE[0], 'Exposure', epoch_seq[count][1])
                    setLed(device,epoch_seq[count][2])
                    setOdor(device,epoch_seq[count][3])
                    window.progressBar.setValue(count+i*n_epoch)
                    
#                 #saving index of previous epoch (name,start frame, end frame)
#                    frame_f=len(frames)-1
#                    meta_index.append((epoch_seq[count-1][0],frame_i,frame_f))
#                    frame_i=len(frames)
                    
                    if epoch_seq[count-1][5] == 0 :
                        frame_f=len(frames)-1
                        meta_index.append((epoch_seq[count-1][0],frame_i,frame_f))
                        frame_i=len(frames)
#                        nrec = 0
#                        mmc.stopSequenceAcquisition()
#                        mmc.clearCircularBuffer() 
                    if (epoch_seq[count][5] == 1):
                        print "stop recording "+str(epoch_seq[count][4])+ "sec"
                        time.sleep(epoch_seq[count][4])
                        mmc.clearCircularBuffer()
                        #meta_index.pop()

#                        if epoch_seq[count-1][5] == 1:
#                            mmc.initializeCircularBuffer()   
#                            mmc.startContinuousSequenceAcquisition(10)
#                            nrec=1                    
                    count += 1
                if ser.inWaiting() :
                            text_file.write(str(time.clock()-start)+",  "+ser.readline()+"\n")
#                if cv2.waitKey(1) >= 0:
#                    break
            frame_f=len(frames)-1
            meta_index.append((epoch_seq[count-1][0],frame_i,frame_f))
            frame_i=len(frames)
            
            m_i_trial.append(meta_index)
            meta_index=[]
            
            window.progressBar.setValue(n_epoch+i*n_epoch)
            #reset
            device.setFIOState(green_lj, 0)
            device.setFIOState(red_lj, 1)
            #device.setFIOState(v1_lj, 0)
            #device.setFIOState(v2_lj, 0)
            DAC0_VALUE = device.voltageToDACBits(0, dacNumber = 0, is16Bits = False)
            device.getFeedback(u3.DAC0_8(DAC0_VALUE))        
            DAC1_VALUE = device.voltageToDACBits(0, dacNumber = 1, is16Bits = False)
            device.getFeedback(u3.DAC1_8(DAC1_VALUE))       
                      
            print str(total)+"s acquisition took", time.clock()-start, "seconds"
            
            mmc.stopSequenceAcquisition()
            mmc.clearCircularBuffer() 
            if i < rep: #end of an epoch
                    #time spent savong files
                    savingTime=time.time()
                    #print "saving tiff.."+str(len(frames))+" frames"
                    #namep=window.path.text()
                    framesnp = np.asarray(frames)
                    
                    #display avg green
                    print "save green"+str(i)+" in "+savepath
                    scipy.misc.imsave(savepath+'/green'+str(i)+'.jpg', np.mean(framesnp[0:20],axis=0))
                    #plt.imshow(np.mean(framesnp[0:20],axis=0))
                    
                    #saveAsMultipageTif(framesnp,savepath,namep,meta,k=512)#
                    #m = saveAsMultipageTif_inter(framesnp,savepath,namep,m)
                    #print "number of tiff files :"+str(m)
                    print "save trial hdf5"
                    print m_i_trial[-1]
                    print i+1
                    hdfs=saveTrialHdf5andClose(hdfpath,framesnp,m_i_trial[-1],i+1,epoch_seq) #modified added epoch
                    print "closing hdfs"
                    hdfs.close()
                    print "closed"
                    #print "save respiratory signal"
                    # text_file = open("respi"+".txt", 'w')
                    print "empty frames list.."
                    frames[:]=[]
                    text_file.close()
                    timeSpentSaving=time.time()-savingTime
                    newDelay=window.dur_2.value()-timeSpentSaving
                    print "in total wating for "+str(window.dur_2.value())+" s"
                    print "after time spent saving wating for "+str(newDelay)+" s"
                    if (newDelay>0):
                        time.sleep(newDelay)
            count =1
    
    #cv2.destroyAllWindows()
                                

    
    #print "nOfFrames :"+str(len(frames)) 
    print "exposure was", mmc.getProperty('Zyla','Exposure')                                               
    print "Framerate was", mmc.getProperty('Zyla','FrameRate')             
    print "saving metadata, timestamps and comments"
    
    if not os.path.exists(savepath+"/"+namep):
        os.makedirs(savepath+"/"+namep)
    
    with open(savepath+"/"+namep+"/epoch.p", "wb") as fp:   #Pickling
        pickle.dump(epoch_seq, fp)
    with open(savepath+"/"+namep+"/comment.p", "wb") as fpp:   #Pickling
        pickle.dump(window.comment.toPlainText(), fpp)
    with open(savepath+"/"+namep+"/timestamps.p", "wb") as fppp:   #Pickling
        pickle.dump(timestamps, fppp)
    with open(savepath+"/"+namep+"/meta.p", "wb") as fppp:   #Pickling
        pickle.dump(meta, fppp)
    with open(savepath+"/"+namep+"/m_i_trial.p", "wb") as fppp:   #Pickling
        pickle.dump(m_i_trial, fppp)

    print "restart kernel to be safe"
    
    text_file_globalTime.close()
    print "global time txt closed"

    
    window.progressBar.setValue(0)       
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
import serial
import time
import software.signal_filters as f
import sys

data = [0]
ser = serial.Serial("COM4", 9600, timeout=0.5)
t = [0]

start_time = time.time()
time2 = []
while time.time() - start_time < 3:
    line = ser.readline()
    print('data: ', float(line))

# Calibration
print('Beginning calibration')
print('Please make your arm straight for 3 seconds...')
time.sleep(3)
ser.reset_input_buffer()
ser.reset_output_buffer()
arm_straight = float(ser.readline())  # Voltage for ~180 degrees
print('Done')

print('Please bend your arm for 3 seconds...')
time.sleep(3)
ser.reset_input_buffer()