def update(self):
     if len(globalDataValues)==0:
         val = 0;
         self.data.append(val);
         self.time.append(0);
     else:
         val = globalDataValues[len(globalDataValues)-1];
         self.data.append(val);
         self.time.append(globalTimeValues[len(globalTimeValues)-1]);
     val_ = int(255*(val)/100);
     if val_<0:
         val_ = 0;
     if val_ > 255:
         val_ = 255;
     #print "presenting %s" %(val_);        
     cv2.rectangle(self.bg,(100,100),(200,200),(val_,val_,val_),-1);
     cv2.imshow("disp",self.bg);
     if cv2.waitKey(10)==27:
         return 0;
     drawnow(self.makeFig);
     plt.pause(0.00001);
     if (len(self.data)>100):
         self.data.pop(0);
         self.time.pop(0);
     return 1;
Exemple #2
0
def main(): 
    inData = serial.Serial('/dev/ttyACM0')
    plt.ion()
    BMSArr = [0] * 9
    sleep(0.2)  # Wait a bit for serial connection to stabilise

    while(1):
        while (inData.inWaiting() == 0):
            pass
        dataLine = inData.readline()
        dataArr = dataLine.split(",")  # Read in and split on comma delimiters
        if(len(dataArr) != 15): # Sanity check string
            continue
        
        # Sum the voltages from the inputs
        vTotal = 0.0
        try:
            for i in range(1, 9):
                vTotal += float(dataArr[i]);
            vTotalArr.append(vTotal)
        
            # Record and append timestamp
            timestamp = float(dataArr[0])
            print(dataLine)
            timeArr.append(timestamp)
        except:
            pass

        # Plot the figure and wait a tiny bit to stop drawnow crashing
        drawnow(drawFig)
        plt.pause(0.000001)
        
        if(float(timestamp - timeArr[0]) >= 15000): # 15 seconds max on the graph at once
            timeArr.pop(0)
            vTotalArr.pop(0)
Exemple #3
0
 def update(self, dThread):
     mutex.acquire();
     if len(dThread.dataArray)==0:
         val = 0;
         self.data.append(val);
         self.time.append(0);
     else:
         val = dThread.dataArray[len(dThread.dataArray)-1];
         self.data.append(val);
         self.time.append(dThread.timeArray[len(dThread.timeArray)-1]);
     mutex.release();
     val_ = int(255*(val+2)/10);
     print val_, val
     if val_<0:
         val_ = 0;
     if val_ > 255:
         val_ = 255;
     #print "presenting %s" %(val_);        
     cv2.rectangle(self.bg,(100,100),(200,200),(val_,val_,val_),-1);
     cv2.imshow("disp",self.bg);
     if cv2.waitKey(10)==27:
         return 0;
     drawnow(self.makeFig);
     plt.pause(0.00001);
     if (len(self.data)>100):
         self.data.pop(0);
         self.time.pop(0);
     return 1;
Exemple #4
0
def main():
	global depth,time,presentime,pasttime,prev_val
	rospy.init_node("depth_plot",anonymous=True)
	match=plotty()
	rate=rospy.Rate(100)
	count=0
	count1=0
	while not rospy.is_shutdown():
		#print match.depth
		if match.depth >1300 or match.depth<960:
			depth.append(prev_val)
		else:
			depth.append(float(match.depth))
			prev_val=match.depth
		time.append(count)
		try:
			drawnow(makefig)
		except:
			pass
			
		plt.pause(0.00001)
		count+=0.01
		count1+=1
		if count1>300 :
			depth.pop(0)
			time.pop(0)
Exemple #5
0
def plotGraph():
    while True:
        out=q.get()
        data = [float(val) for val in out.split()]
        if data:
            count=0
            while count<len(data):
                cpuLoad.append(data[count])
                count=count+1
        drawnow(makefig)
def tread(soc,event):
    while True:
        event.wait()
        #print 'event.wait()'
        event.clear()
        #print soc
        #print pltADC
        #print ADC1

        drawnow(makeFig)                       #Call drawnow to update our live graph
        plt.pause(.000001)                     #Pause Briefly. Important to keep drawnow from crashing
Exemple #7
0
def main():
    with serial.Serial() as ser:
        ser.baudrate = 9600
        ser.port = arduino_serial_port()
        ser.open()

        while True:
            data = waitForDataFromArduino(ser)
            current_temp_contact = float( data[0] )
            current_temp_ambient = float( data[1] )
            current_pwm = float( data[2] )
            temp_contact.append(current_temp_contact)
            temp_ambient.append(current_temp_ambient)
            #pwm.append(current_pwm)
            delta = current_temp_contact - current_temp_ambient
            print "pwm:{0} ambient:{1} contact:{2} delta:{3}".format(current_pwm, current_temp_ambient, current_temp_contact, delta)
            drawnow(figure)
            plt.pause(.000001)
            ++count
            if(count>50):
                temp_contact.pop(0)
                temp_ambient.pop(0)
Exemple #8
0
def main():
	global yaw, time
	rospy.init_node("yaw_plot",anonymous=True)
	match=plotty()
	rate=rospy.Rate(10)
	count=0
	count1=0
	while not rospy.is_shutdown():
		yaw.append(float(match.yaw))
		time.append(count)
		try:
			drawnow(makefig)
		except:
			pass
			
		plt.pause(0.00001)
		count+=0.1
		count1+=1
		if count1>300 :
			yaw.pop(0)
			time.pop(0)
		print count1
		rate.sleep()
    def plot(self):  # PROBLEMATICNA FUNKCIJA
        global values
        def plotValues():
            plt.title('Trenutna Temperatura')
            plt.grid(True)
            plt.ylim(25, 35)
            plt.ylabel('Temperatura [C]')
            plt.xlabel('Vreme [s/2]')
            plt.plot(values)

        def doAtExit():
            serialArduino.close()

        atexit.register(doAtExit)

        for i in range(0,1):
            values.append(0)

        while bulova == True:
            if (serialArduino.inWaiting()>0):
                pass
            valueRead = serialArduino.readline()
            try:
                valueInFloat=float(valueRead)
                if valueInFloat <= 1024.0:
                    if valueInFloat >= 0.0:
                        values.append(valueInFloat)
                        drawnow(plotValues)
                        #plt.pause(0.005)
                    else:
                        print("Invalid! negative number")
                else:
                    print("Invalid! too large")
            except ValueError:
                pass
            self.draw()
    #plt.plot(L)
    plt.title('Serial temperature from Arduino')
    plt.grid(True)
    plt.ylabel('Temperature')
    #plt.plot(tmpF, 'rx-', labl = 'values')
    plt.legend(loc = 'upper right')
    
    
while True:
    while(aD.inWaiting()==0):
        pass
    #aD.flushInput()
    aS = aD.readline()[:].decode('ascii')
    time.sleep(1)
    dataArray = aS.split(' ')
    tmp = dataArray[0]
    LED = dataArray[1]
    x = dataArray[2]
    y = dataArray[3]
    z = float(dataArray[4])
    tmpF.append(tmp)
    L.append(LED)
    df = pd.DataFrame(tmpF)
    df.to_csv('/home/makerghat/Anaconda/Temprature.csv')
    drawnow(plotVal)
    cnt = cnt+1
    if (cnt > 50):
        tmpF.pop(0)
        L.pop(0)
    print(tmp, LED, x, y, z)
Exemple #11
0
    plt2 = plt.twinx()
    plt2.plot(solar_v, "o-", color="orange", label="Solar_V")
    plt2.legend(loc="upper left")
    plt.ylim(
        0, 12
    )  #set the y limit of the solar panel to be 12V as the maximum voltage we can get from the solar panel is the open-circuit voltage which is equal to 10.65V
    plt2.set_ylabel("Solar Panel Voltage (V)")


while (wait):
    while (arduinoData.in_waiting == 0):
        pass  #if there is no data then WE DO NOTHING until data comes
    arduinostring_temp = arduinoData.readline(
    )  #we read data from the serial port and put them in arduinostring
    arduinostring = arduinostring_temp.decode("utf-8")
    #print (arduinostring)
    arduino_array = arduinostring.split(",")
    tempbat_v = float(arduino_array[0])
    tempsolar_v = float(arduino_array[1])
    print(tempbat_v, ",", tempsolar_v)
    bat_v.append(tempbat_v)  #an array which basically increases with time
    solar_v.append(tempsolar_v)  #an array which basically increases with time
    drawnow(makeFig)  #for plotting live data

    cnt += 1
    if (
            cnt >= 40
    ):  #this way we make sure that we are constatly plotting the newest 40 voltages
        bat_v.pop(0)
        solar_v.pop(0)
def draw_fig(board, lock, procs):
    print " PLOTTING PROCESS Initiated"
    print " PLOTTING PROCESS Running :" + str(len(onesec))
    if (len(onesec) >= 250):
        drawnow(draw_fg)
Exemple #13
0
    plt.show()  #display the radar data


theta = np.arange(70, 111) / 180 * np.pi
r = np.zeros(41)

temp = 200
while True:
    while (ser.inWaiting() == 0):  #Wait here until there is data
        pass  #do nothing
    #each line comprises of theta and corresponding radial distance
    data = ser.readline()  #read in data from serial port from arduino
    data = re.sub('[^0-9 ]+', ' ', data)
    data = data.split()
    data = [int(a) for a in data]  #extract the integers
    # print data
    data = np.array(data)
    # print len(data)

    try:
        if data[1] > 200:  #any reading exceeding 200cm
            data[1] = 200
        theta[data[0] - 70] = data[0] * np.pi / 180
        r[data[0] - 70] = (0.8 * data[1] + 0.2 * temp
                           )  #weighted average of r with the previous r value
        temp = data[
            1]  #storing the current r value to be used for weighted average in the next iter
        drawnow(fun)
        plt.pause(.0000001)  #sthash.JUzdSP5G.dpuf
    except ValueError and IndexError:
        print "oops"
		zeroPotCode = int(zeroPotLine[6:len(zeroPotLine)])

	heightLine = arduinoSer.readline()											#read in line containing force applicator height
	if heightLine[0:7] != "HEIGHT=":
		print heightLine #debug
		raise IOError("Invalid force applicator height received")
	else:
		height = int(heightLine[7:len(heightLine)])
	print "testing at " + str(height) + " mm above ground." #debug

	#------------------------------------
	#SAVE TEST DATA TO VARIABLES AND PLOT
	#------------------------------------
	lineReceived = arduinoSer.readline()										#read in first line of test data
	plt.ion()
	drawnow(makeFig)															#create live plotting window
	while lineReceived[0:3] != "END":
		lineReceived = lineReceived.split("/")[0]								#take first element after splitting by forward slash to strip special characters
		[loadReading, angleReading] = lineReceived.split(",")					#split load cell and potentiometer values using comma
		angleList.append(int(angleReading))										#append load and angle readings to lists
		loadList.append(int(loadReading))
		lineReceived = arduinoSer.readline()									#read in next line of test data
	drawnow(makeFig)
	plt.pause(0.000001)
	idLine = arduinoSer.readline()												#read in line following test end signal to get testID
	if idLine[0:7] != "TESTID=":
		raise IOError("Invalid test ID line received")
	elif int(idLine[7:len(idLine)]) != testId:									#check if same test ID received at beginning and end of test
		raise IOError("Different test ID supplied at beginning and end of test")
	print "test " + str(lastTestId + testId) + " ended" #debug
        
        xacc, yacc, zacc, xgyrodeg, ygyrodeg, zgyrodeg = input_data()

        dtx = -math.radians(xgyrodeg * T)
        dty = math.radians(ygyrodeg * T)
        dtz = -math.radians(zgyrodeg * T)
        
        
        x_comp_filter = my_x_comp_filter(Gyro_input=math.radians(xgyrodeg),
                        On_Axis_input=yacc, Off_Axis_input=xacc,Z_Axis_input=zacc)

        y_comp_filter = my_y_comp_filter(Gyro_input=math.radians(ygyrodeg),
                        On_Axis_input=xacc, Off_Axis_input=yacc,Z_Axis_input=zacc)

        compX.append(float(x_comp_filter))
        drawnow(makeFig)
        compY.append(y_comp_filter)

        print(compX[cnt])

        # There is no comp filter in yaw
        # Put a deadzone of about 1.5 LSB to supress drift (may not work in-flight)
        if abs(math.radians(zgyrodeg)) > 0.03:
            anglez += dtz

        cnt = cnt + 1
except KeyboardInterrupt:
    pass

datacnt = 0
def show_graphs():
    drawnow(plot_graphs)

while True:  #While loop that loops forever
    while (arduinoData.inWaiting() == 0):  #Wait here for data.
        pass  #do nothing
    #serial.read().decode()
    arduinoString = arduinoData.readline().decode()
    # Reads the data from the arduino serial.. as a string
    dataArray = arduinoString.split(',')
    # Stores the data string as an array using a comma delimiter
    print(arduinoString)
    temp = float(
        dataArray[0]
    )  #Converts the temp string into a float so we can do math and plots.
    humid = float(
        dataArray[1]
    )  # Converts the humidity string into a float so we can do math and plots
    tempF.append(temp)  #Add the data into the data array declared at the top
    humidity.append(humid)  # adds the data into the data array at the top.
    drawnow(make_figure)
    # Call drawnow to update the live graph
    plt.pause(0.000001)
    count = count + 1
    if (
            count > 50
    ):  # here is to plot the most recent data, removing old data to make the graph cooler.
        tempF.pop(0)
        # This removes the 0th element of the array
        humidity.pop(0)
        #this pops the first element
high_cut = 3.0
fs = 250

while(len(channel1_data) <= 1000):

    while(arduino.inWaiting() == 0):
        pass
    data_string = arduino.readline()
    if(isint(data_string)):
        channel1_data.append(int(data_string))
    else:
        pass

fil_data = bandpass_filter(channel1_data, high_cut, low_cut) 
old_filter = fil_data.tolist()
drawnow(filterplot)

while(True):
    i = 0
    if(len(channel1_data) >= 1000):
       while i<200:
            
            channel1_data.pop(0)
            old_filter.pop(0)
            i += 1

    while(len(channel1_data) <= 1000):

        data_string = arduino.readline()
        #parsed_data = data_string.split(" ")
        if (isint(data_string)):
Exemple #19
0
         break
        
    low = ord(SerialData.read())
    high = ord(SerialData.read())
    print(low)
    print(high)
    value = 256*high + low
    
    
    if (value > 511):
      value -= 1024                     # value = value - 1024
    V = 2.5 - value*5.0/(20.0*512.0)    # Voltage out (Vo) = R / (R + 10K) * Vcc = 2.5
    R = 10000.0/(5.0/V-1.0)
    B = 3950.0
    R25 =  10000.0
    T = 1.0/(log(R/R25)/B+(1/(25.0+273.15))) - 273.15
    filter = (1-eps)*filter + eps*T

    temp = float(filter)
    tempV.append("%.2f" % temp)         # Build our array by appending temperature readings
    print("%.2f" % temp)
    drawnow(makeGraph)                  # call drawnow to draw live graph
    plt.pause (.0001)
    cnt=cnt+1
    if(cnt>30):                         # delete the first item from the array
        tempV.pop(0)                    # this allows us to just see the last 30 data points
    



                    return_array.append(count)
            else:
                return_array.append(count)
        count = count + 1
    return return_array

#Main Functions
try:
    avg, maxThresh, minThresh = getAverageAccel()
    fig_count = 0
    while True:
        time.sleep(1)
        time2,paccZ = dataPull() #get data from log file
        accel_Time.extend(time2)
        accZ.extend(paccZ)
        drawnow(finalDemo)
        fig_count = fig_count + 1

        if (fig_count == 10):
            for x in xrange(3):
                avg = np.mean(accZ)
                accZ = accZ - avg


            plot_time = accel_Time
            plot_raw = accZ


            #clip the values that are too high or low 
            #low_values_indices = clipping_data < minThresh
            #clipping_data[low_values_indices] = minThresh 
Exemple #21
0
            # print(e)
            disk_used = 100 - e
            host_disk.append(disk_used)
            host_disk.insert(0, host_disk.pop())


    for i in f8:
        if "[GR] FPS" in i:
            print(1)
            j = i.split(':')
            s = j[4]
            print(s)
            fps.append(s)
            fps.insert(0, fps.pop())

    drawnow(fig)


    plt.pause(.000001)

    if (count > 60):
        x.pop(0),host_cpu.pop(0), y.pop(0), host_mem.pop(0), z.pop(0), host_disk.pop(0), fps.pop(0)


    count1 = 0
    count2 = 0
    count3 = 0
    count4 = 0


Exemple #22
0
    plt. plot( self_y[2], lnIndexer[2], label='Panic owerview' )
    plt. plot( self_y[8], lnIndexer[8], label='body temp' )
    plt. plot( self_y[9], lnIndexer[9], label='out temp' )
    plt. plot( self_y[10], lnIndexer[10], label='Panic range' )
    plt. plot( self_y[11], lnIndexer[11], label='Movement act.' )
    plt.legend(loc='upper left')  
    #plt.draw()

    #for i in range(couveNum):
        
        #plt. plot( self_y[i], lnIndexer[i] )  #25
        #plt.draw()
    if (counter > 40):
        map(lambda a: a.pop(0), self_y)
    counter+=1

while True:
    word = sys.stdin.readline().rstrip()

    value = word.split(',')

    drawnow(makeFig,show_once=False)
    plt.pause(.0001) 



sys.exit()



Exemple #23
0
while(1):
    p =0.03
    tensao_array = []
    
    tensao = np.random.rand(1)
    while(len(tensao_array)<256):
        if tensao > p:
            tensao = np.random.rand(1)
            tensao_array.append(tensao)
        else:
            np.random.rand(1)
            tensao = np.random.rand(1)
            tensao_array.append(tensao)
        
        
    x,signal=f(N)
    start = timer()
    dftz=DFT(signal,N)*2/N
    end = timer()
    dftz[0]=dftz[0]/2. # O primeiro termo da série é a0/2 

    ksample=np.linspace(0,N,N)
    wf=ksample*dpi/(N*h)
    Mxp=int(N/2.)

    drawnow(grafico)


            
    accelxin = data_array[1]
    accelyin = data_array[0]
    accelzin = data_array[2]
    speedin = data_array[4]
    rpmin = data_array[3]
    throttlein = data_array[5]

    #Appending the data to the nessacary lists.
    accel_x.append(float(accelxin))
    accel_y.append(float(accelyin))
    accel_z.append(float(accelzin))
    speed.append(float(speedin))
    rpm.append(float(rpmin))
    throttle.append(float(throttlein))
    #Drawing the graph.
    drawnow(make_fig)
    #Preventing an oof.
    plt.pause(.000001)
    #Increment the count.
    count = count + 1

    #Keeping that list manageable in size.
    if count > maxCount:
        accel_x.pop(0)
        accel_y.pop(0)
        accel_z.pop(0)
        speed.pop(0)
        rpm.pop(0)
        throttle.pop(0)

    #Creating a string to write to the file.

def makeLiveFigure():
    #plt.ylim(10,50)
    plt.title('Fluctuations in Humidity and Temperature')
    plt.grid(True)
    plt.plot(humidity, 'o-', label='Humidity')
    #plt2 = plt.twinx()
    plt.plot(tempc, 'o-', label='Temperature(C)')
    plt.legend()  # dynamically changes the location


while True:
    if arduinoDataStream.inWaiting() > 0:
        fluctuations = arduinoDataStream.readline()
        #print(fluctuations)

        dataStream = fluctuations.split(',')

        hum = float(dataStream[0])
        humidity.append(hum)
        temp = float(dataStream[1])
        tempc.append(temp)

        drawnow(makeLiveFigure)  # update the live graph
        plt.pause(.0001)  # delays the process

        count += 1
        if count > 35:
            humidity.pop(0)
            tempc.pop(0)
Exemple #26
0
        pass

    try:
        valueReadList = valueRead.split(" ")
        if not valueReadList[0]:
            valueRead=valueReadList[1]
        else:
            valueRead=valueReadList[0]
        #Get X Value
        valueRead = valueReadList[0]

        if float(valueRead)<maxEmptyParkingRangeVal and float(valueRead)>minEmptyParkingRangeVal:
            print("Parking Empty")
        else:
            print("Occupied")
    except:
        pass

    # check if valid value can be casted
    try:
        valueInInt = float(valueRead)
        #print(valueInInt)
        if valueInInt <= 500000:
            values.append(valueInInt)
            values.pop(0)
            drawnow(plotValues)
        else:
            print("Invalid! too large")
    except ValueError:
        print("Invalid! cannot cast"+ str(valueRead))
Exemple #27
0
plt.ion()  #Tell matplotlib to have interactive mode on to plot live data


def makeFigure():  #make a plotting function
    fig, axs = plt.subplot(2, 3)  #create subplots
    axs.ylim(0, 100)  #set y min and max
    axs.ylabel('Turbidity')  #set ylabels
    fig.suptitle('Turbidity Sensors')  #set figure title
    for i in range(0, 6):
        axs[i].plot(vars()['sensor' + str(i + 1)], 'r--',
                    label='Volts')  #plot each turbidity sensor


while True:  # Continuous loop while we are getting data
    while (arduinoSensorData.inWaiting() == 0):  #Wait until there is data
        pass  #do nothing

    arduinoString = arduinoSensorData.readline()  #Reads serial string data
    dataArray = arduinoString.split(
        ",")  #Put data into an arrays for each sensor
    for i in range(1, 7):
        vars()["turb" + str(i)] = float(dataArray[i -
                                                  1])  #store as float values

    for i in range(1, 7):
        vars()['sensor' + str(i)].append(
            vars()['turb' + str(i)])  #Update arrays with data stream

    drawnow(makeFigure)  #Call drawnow to plot live data
    plt.pause(0.000001)  #wait a small time before updating
            

                ##filtering 
                if(t>captureTime*timecount):
                    if (timecount == 1): 
                        my_x_comp_filter, my_y_comp_filter, accXavg, accYavg, accZavg, gyrXavg, gyrYavg, gyrZavg = initializeCompFilter(time,accX,accY,accZ,gyrX,gyrY,gyrZ) 
                        print "Intialization complete"
                        accX = []
                        accY = []
                        accZ = []
                        gyrX = []
                        gyrY = []
                        gyrZ = []
                    if (timecount > 1):
                        filteredX, filteredY = compFilter(my_x_comp_filter, my_y_comp_filter,time,accX,accY,accZ,gyrX,gyrY,gyrZ,gyrXavg, gyrYavg, gyrZavg)
                        drawnow(makeFigRaw)
                        accX = []
                        accY = []
                        accZ = []
                        gyrX = []
                        gyrY = []
                        gyrZ = []
                        #freqX, fftX, fftY = ourFFT(filteredX,filteredY,time2)
                        #W, ffTtime, cut_signal, cut_f_signal, f_signal = ourFFT2(filteredX,time2)
                        W, ffTtime, cut_signal, cut_f_signal, f_signal = ourFFT2(filteredX,time2)
                        W_x, ffTtime_x, cut_signal_x, cut_f_signal_x, f_signal_x = ourFFT2(paccX,time)
                        W_y, ffTtime_y, cut_signal_y, cut_f_signal_y, f_signal_y = ourFFT2(paccY,time)
                        W_z, ffTtime_z, cut_signal_z, cut_f_signal_z, f_signal_z = ourFFT2(paccZ,time)

                        peakCompX = detect_peaks(cut_signal)
                        peakaccX = detect_peaks(cut_signal_x)
Exemple #29
0
if not len(sys.argv) == 2:
	print "Usage: python %s PORT" %sys.argv[0];
	sys.exit(0);
port = sys.argv[1]
ser = serial.Serial(port, 115200)
temp = []
fig = plt.figure() 
fig.canvas.set_window_title("Oscilloscope")
fig.canvas.mpl_connect("close_event", handle_close)
# figtitle = "Voltage Monitor"
# plt.ion()

counter = 0
while True:
	try:
		read = ser.readline().rstrip()

		if not not read:
			voltage = map_to(int(read), 0, 1023, 0.0, 5.0)
			temp.append(voltage)
			drawnow(plotter)
			
			counter += 1
			if counter > 30:
				temp.pop(0)
	except ValueError:
		pass
	except KeyboardInterrupt:
		print '\nClosing...'
		sys.exit(0)
Exemple #30
0
        s = zeros_like(x[:,:,i])
        fill_diagonal(s, sigmas)

        color = u.dot(s).dot(v)
        y[:,:,i] = color
    i = argwhere(y > 1)
    y[i[:,0], i[:,1], i[:,2]] = 1
    return y

WIDTH = 7
figure(figsize=(WIDTH, WIDTH / 2))
def draw_fig():
    """ Uses Python's global scope """
    subplot(1, 2, 1)
    imshow(x, cmap='gray')
    title('Original')
    axis('off')

    subplot(1, 2, 2)
    imshow(x_hat, cmap='gray')
    title('Approx with $k=%d$' % k)
    axis('off')
    # show()

x = imread('mandrill.png')
k_values = around(logspace(0.1, log10(64), num=10))
for k in k_values:
    x_hat = approx(x, k)
    drawnow(draw_fig)
                        accZ = []
                        gyrX = []
                        gyrY = []
                        gyrZ = []
                        #freqX, fftX, fftY = ourFFT(filteredX,filteredY,time2)
                        #W, ffTtime, cut_signal, cut_f_signal, f_signal = ourFFT2(filteredX,time2)
                        W, ffTtime, cut_signal, cut_f_signal, f_signal = ourFFT2(filteredX,time2)
                        W_x, ffTtime_x, cut_signal_x, cut_f_signal_x, f_signal_x = ourFFT2(paccX,time)
                        W_y, ffTtime_y, cut_signal_y, cut_f_signal_y, f_signal_y = ourFFT2(paccY,time)
                        W_z, ffTtime_z, cut_signal_z, cut_f_signal_z, f_signal_z = ourFFT2(paccZ,time)

                        peakCompX = detect_peaks(cut_signal)
                        peakaccX = detect_peaks(cut_signal_x)
                        peakaccY = detect_peaks(cut_signal_y)
                        peakaccZ = detect_peaks(cut_signal_z)
                        drawnow(demoFig)
                        #drawnow(makeFig)
                        #drawnow(makeSignalFig)
                        #drawnow(makeFftFig)
                        #drawnow(makeFigRaw)
                        #drawnow(makeFigAccFFT)
                        #drawnow(makeFigAccPostFFT)
                        #drawnow(makeBreathingRate)
                    timecount=timecount+1
            cnt = cnt + 1
except KeyboardInterrupt:
    pass


with open(savepath+file_name+'.csv', 'wb') as csvfile:
    print 'Saving Data...'
voltage = []
amperage = []
resistance = float(input(
    "What is the Resistance of Load    "))  # used to approximate current draw
csv_file = open("voltage.csv", "w", newline="")
writer = csv.writer(
    csv_file,
    dialect="excel",
)  # define parameters for excel output
plt.ion()

startTime = time.time()
# voltage output loop
while True:
    if keyboard.is_pressed('ctrl+c'):  # break cycle on key press command
        plt.savefig('voltage.pdf')
        plt.close()
        break
    drawnow(graphOutput)
    plt.pause(0.0001)
    volt_reading = float(voltage_reader.read(6).strip())
    writer.writerow([volt_reading])
    voltage.append(volt_reading)
    amperage.append(volt_reading / resistance)

# Find total time
endTime = time.time()
duration = endTime - startTime
sum = sum(amperage)
print(duration)
                print("D5 : ", D5)
                print("D6 : ", D6)
                print("D7 : ", D7)
                print("D8 : ", D8)
                
                # Her zaman dizide 25 karakter kalması için ilk dizi değeri silinir daha sonrasında append ile yeni değer aktarılır.         
                values_Distance.pop(0)
                values_firstPath.pop(0)
                values_firstPathAmp1.pop(0)
                values_firstPathAmp2.pop(0)
                values_firstPathAmp3.pop(0)
                values_maxGrowthCIR.pop(0)
                values_rxPreamCount.pop(0)
                values_maxNoise.pop(0)
                values_stdNoise.pop(0)
    
                values_Distance.append(D0)
                values_firstPath.append(D1)
                values_firstPathAmp1.append(D2)
                values_firstPathAmp2.append(D3)
                values_firstPathAmp3.append(D4)
                values_maxGrowthCIR.append(D5)
                values_rxPreamCount.append(D6)
                values_maxNoise.append(D7)
                values_stdNoise.append(D8)

                time.pop(0)
                time.append(datetime.datetime.now())

                drawnow(plotValues)
    plt.xticks(unixtimeArray, timestampArray, rotation='70')
    plt.margins(0.2)
    plt.subplots_adjust(bottom=0.15)
    plt.plot(unixtimeArray, uvArray)

while True:
    data = ser.readline()
    print data
    if data.split(":")[0] == "Pressure":
        timestamp = (time.strftime("%H:%M:%S"))
        pressure_log.write('{0},{1}\n'.format(timestamp, data.split(":")[1]))
        unixtime = time.mktime(time.localtime())
        unixtimeArray.append(float(unixtime))
        timestampArray.append(str(timestamp))
        pressureArray.append(float(data.split(":")[1].rstrip()))
        drawnow(pressureFig)
        plt.pause(.00001)
        count=count+1
        if(count>29):
            unixtimeArray.pop(0)
            timestampArray.pop(0)
            pressureArray.pop(0)
    elif data.split(":")[0] == "Temperature":
        timestamp = (time.strftime("%H:%M:%S"))
        temperature_log.write('{0},{1}\n'.format(timestamp, data.split(":")[1]))
    elif data.split(":")[0] == "Humidity":
        timestamp = (time.strftime("%H:%M:%S"))
        humidity_log.write('{0},{1}\n'.format(timestamp, data.split(":")[1]))
    elif data.split(":")[0] == "UV":
        timestamp = (time.strftime("%H:%M:%S"))
        uv_log.write('{0},{1}\n'.format(timestamp, data.split(":")[1]))
Exemple #35
0
    x1,y1=m(x,y)
    xarray.append(x1)
    yarray.append(y1)


    m.drawcoastlines()
    im = plt.imread("map.png")
    m.imshow(im, origin='upper')
    m.scatter(xarray,yarray,c='b',marker=".",alpha=1.0)
while(1):
    #X AND Y ARE THE RECEIVED DATA FROM THE GPS SENSOR
    #for now they have just been set to random numbers between the limits
    pos = open(const_pos_sharefile,'r')
    last_line = pos.readline()
    while(last_line!=""):
        x = float(last_line.split(",")[0])
        print x
        print 'Y:'
        y = float(last_line.split(",")[1])
        print y
        print '-----'
        last_line = pos.readline()
    drawnow(makeFigs)
    time.sleep(0.1)

    #SYSTEM TO START DUMPING OLD DATA - might be completely useless?
    threshold = 30 #maximum pieces of data
    if len(xarray) > threshold:
        xarray.pop(0)
        yarray.pop(0)
Exemple #36
0
def ppt():
    drawnow(the_thread)
Exemple #37
0
def findlength():
    if len(temperature) == 0:
        return float(1)
    else:
        return float(len(temperature))


try:
    file = open("log.txt", "w+")
    while True:
        data = ser.readline().decode('utf-8')
        nodigit = data.translate(string.digits)
        currenttemp = float(nodigit)
        print(" current:{} average:{}".format(currenttemp,
                                              sum(temperature) / findlength()))
        file.write("time={} current:{} average:{}\n".format(
            datetime.datetime.now(), currenttemp,
            sum(temperature) / findlength()))
        temperature.append(currenttemp)
        average.append(sum(temperature) / findlength())
        drawnow(plotdata)
        if temperature.__len__() > 50:
            temperature.pop(0)
            average.pop(0)
except KeyboardInterrupt:
    print("finished")
finally:
    closingports()
    file.close()
#create the serial port object
port = serial.Serial('COM4', 115200, timeout=0.5)
plt.ion()


#create the figure function
def makeFig():
    plt.ylim(-1023, 1023)
    plt.title('Osciloscope')
    plt.grid(True)
    plt.ylabel('data')
    plt.plot(val, 'ro-', label='Channel 0')
    plt.legend(loc='lower right')


while (True):
    port.write(b's')  #handshake with Arduino
    if (port.inWaiting()):  # if the arduino replies
        value = port.readline()  # read the reply
        print(value)  #print so we can monitor it
        number = int(value)  #convert received data to integer
        print('Channel 0: {0}'.format(number))
        # Sleep for half a second.
        time.sleep(0.01)
        val.append(int(number))
        drawnow(makeFig)  #update plot to reflect new data input
        plt.pause(.000001)
        cnt = cnt + 1
    if (cnt > 50):
        val.pop(0)  #keep the plot fresh by deleting the data at position 0
            

                ##filtering 
                if(t>captureTime*timecount):
                    if (timecount == 1): 
                        my_x_comp_filter, my_y_comp_filter, accXavg, accYavg, accZavg, gyrXavg, gyrYavg, gyrZavg = initializeCompFilter(time,accX,accY,accZ,gyrX,gyrY,gyrZ) 
                        print "Intialization complete"
                        accX = []
                        accY = []
                        accZ = []
                        gyrX = []
                        gyrY = []
                        gyrZ = []
                    if (timecount > 1):
                        filteredX, filteredY = compFilter(my_x_comp_filter, my_y_comp_filter,time,accX,accY,accZ,gyrX,gyrY,gyrZ,gyrXavg, gyrYavg, gyrZavg)
                        drawnow(makeFigRaw)
                        accX = []
                        accY = []
                        accZ = []
                        gyrX = []
                        gyrY = []
                        gyrZ = []
                        #freqX, fftX, fftY = ourFFT(filteredX,filteredY,time2)
                        W, ffTtime, cut_signal, cut_f_signal, f_signal = ourFFT2(filteredX,time2)
                        peakX = detect_peaks(cut_signal)
                        print peakX
                        drawnow(makeFig)
                        drawnow(makeSignalFig)
                        drawnow(makeFftFig)
                        #peakY = detect_peaks(filteredY)
                        #if (len(peakX)>=1 & len(peakY)>=1):
Exemple #40
0
def makeFigure():
    plt.ylim(
        -1023, 1023
    )  #this is the drawing function of the plot while its getting data , and its->
    plt.title(
        'Osciloscope'
    )  # -1023 upto 1023  becuase of arduino upper and down limit of ADC
    plt.grid(True)
    plt.ylabel('data')
    plt.plot(val, 'ro', label='output')
    plt.legend(loc='lower right')


while (True):
    port.write(
        b's'
    )  # also in arduino the condition of writing data throw serial is data=='s'
    if (port.inWaiting()):  #and the condition of replying arduino is to...
        value = port.readline()  # read
        number = int(
            float(value)
        )  #convert received data to integer  #not necessary float but if you use python 3.7 , you'll get error
        print('output: {0}'.format(number))  #and write
        time.sleep(0.01)
        val.append(int(number))  #adding another data to our data array
        drawnow(makeFigure)  # and we should update the plot for new data
        plt.pause(.000001)
        cnt = cnt + 1  #after 50 counting , our first element of data array will be deleted
    if (cnt > 50):
        val.pop(0)
updownA=[]
ser = serial.Serial('/dev/ttyACM0', 115200, timeout=2, xonxoff=False, rtscts=False, dsrdtr=False) 
ser.flushInput()
ser.flushOutput()
plt.ion()

def dataPlot():
	plt.title("X-Y Co-ordinate data from Joystick")
	plt.grid(True)
	plt.ylabel("ASCII Values")
	plt.plot(leftrightA, 'ro-', label="ASCII")
	plt.legend(loc='upper left')
	plt2=plt.twinx()
	plt2.plot(updownA)

while True:
	while (ser.inWaiting()==0):
		pass
	dataStream = ser.readline();
	#ser.read(dataStream)
	#print dataStream
	dataArray = dataStream.split(',')
	#print dataArray[0]
	#print dataArray[1]
	leftright = float ( dataArray[0] )
	updown = float( dataArray[1] )
	#print leftright,",",updown
	leftrightA.append(leftright)
	updownA.append(updown)
	drawnow(dataPlot)
def readSerial():
    #global file
    global writer1
    while True:
        c = ser.read()  # attempt to read a character from Serial
        #was anything read?
        if len(c) == 0:
            break
            # get the buffer from outside of this function
        global serBuffer
        # check if character is a delimeter
        if c == '\r':
            c = ''  # don't want returns. chuck it

        if c == '\n':
            #serBuffer += "\n" # add the newline to the buffer
            #print serBuffer
            #add the line to the TOP of the log
            log.insert('0.0', serBuffer)
            print(serBuffer + "\n\n\n")
            log.insert('0.0', "\n")
            #print serBuffer
            if serBuffer.find(':') > 0:
                name, value = serBuffer.split(':', 1)
                name = name.strip()
                value = value.strip()
                value1 = re.findall(r"[-+]?\d*\.\d+|\d+", value)
                value2 = [float(i) for i in value1]
                temp = value2
                #l1 = [elem.strip().split(';') for elem in l]
                #value2 = [float(n) for n in value1.split()]
                #print value2
                #print temp
                if name == "Temperature":
                    currentDT = str(datetime.datetime.now().time())
                    writer1.writerow([currentDT, name, temp])
                    if graphbuffer[0] == 1:
                        print 'hi'
                        dateF.append(currentDT)
                        tempF.append(temp)
                        drawnow(makegraphs)
                        plt.pause(0.000001)
                if name == "Humidity":
                    currentDT = str(datetime.datetime.now().time())
                    writer1.writerow([currentDT, name, temp])
                    if graphbuffer[1] == 1:
                        date2.append(currentDT)
                        Humi.append(temp)
                        drawnow(makegraphs1)
                        plt.pause(0.000001)
                if name == "Pressure":
                    currentDT = str(datetime.datetime.now().time())
                    writer1.writerow([currentDT, name, temp])
                    if graphbuffer[2] == 1:
                        date3.append(currentDT)
                        press.append(temp)
                        drawnow(makegraphs2)
                        plt.pause(0.000001)
                if name == "Accelerometer X":
                    print graphbuffer[3]
                    currentDT = str(datetime.datetime.now().time())
                    writer1.writerow([currentDT, name, temp])
                    if graphbuffer[3] == 1:
                        print graphbuffer[3]
                        date4.append(currentDT)
                        x1.append(temp)
                        drawnow(makegraphs3)
                        plt.pause(0.000001)
                if name == "Accelerometer Y":
                    print graphbuffer[3]
                    currentDT = str(datetime.datetime.now().time())
                    writer1.writerow([currentDT, name, temp])
                    if graphbuffer[4] == 1:
                        date5.append(currentDT)
                        y1.append(temp)
                        drawnow(makegraphs4)
                        plt.pause(0.000001)
                if name == "Accelerometer Z":
                    print graphbuffer[3]
                    currentDT = str(datetime.datetime.now().time())
                    writer1.writerow([currentDT, name, temp])
                    if graphbuffer[5] == 1:
                        date6.append(currentDT)
                        z1.append(temp)
                        drawnow(makegraphs5)
                        plt.pause(0.000001)
            serBuffer = ""  # empty the buffer
            #print serBuffer
        else:
            serBuffer += c  # add to the buffer
    master.after(10, readSerial)  # check serial again soon
        if (lastAverageBPM >2+averageBPM):
            print "Exacerbation risk is high"
        print bpm[-2:]
        print lastAverageBPM
    print averageBPM

#######################################################################
#Main Functions
try:
    while True:
        time.sleep(10)
        time2,paccZ = dataPull()
        W_z, ffTtime_z, cut_signal_z, cut_f_signal_z, f_signal_z = ourFFT(paccZ,time2) #variables from Ravi
        peakaccZ = detect_peaks(cut_signal_z)
        breaths = len(peakaccZ)
        drawnow(demoFig6)
        drawnow(demoFig1)
        bpm.append(breaths)

        if (len(bpm)>2*bpmcount):
            checkAverageBPM(bpm)
            print(bpm)
            bpmcount = bpmcount+1
except KeyboardInterrupt:
    pass

with open(savepath+file_name+'.csv', 'wb') as csvfile:
    print 'Saving Data...'
    datacnt = 0
    while(datacnt<len(W)):
        dataWriter = csv.writer(csvfile)
#count = 0;	

while True:
	while (ser.inWaiting()==0):
		pass
	#dataStream = ser.readline();
	dataStream = ser.readline().decode('ascii');
	#print(dataStream);
	#if dataStream != '\n':
	dataArray = dataStream.split(',');
	print(dataArray);
	if len(dataArray) != 2:
		continue;
	if (dataArray[0] != '' and dataArray[1] != '' ) :			
		#print (dataArray[0][0:6])
		#print (dataArray[1][0:4])
		leftright = int(dataArray[0]) 
		updown = int(dataArray[1][0:4])
		#print (leftright,",",updown)

		#leftrightA = leftright
		#updownA = updown

		drawnow(dataPlot)

		#time.sleep(1) #delay

		#ser.flush() #flush the buffer
		ser.flushInput()
		#ser.flushOutput()
Exemple #45
0
def _iterator(intf):
    while True:
        '''cpu utilization percent'''
        per_util_cpu = psutil.cpu_percent(interval=True)
        '''core count'''
        core_count_cpu = psutil.cpu_count(logical=True)
        '''free memory percent'''
        per_util_mem = psutil.virtual_memory().percent
        '''free storage percent'''
        per_util_disk = psutil.disk_usage('/').percent
        '''Network Utilization percent'''
        time_quanta = 3
        if_name = intf  #list(psutil.net_if_stats().keys())[0]
        #if if_name == 'lo':
        #if_name = list(psutil.net_if_stats().keys())[1]
        nic_speed = psutil.net_if_stats()[if_name][2]  # get(if_name).speed
        if nic_speed == 0:
            nic_speed = 100
        r_byte_1 = psutil.net_io_counters(pernic=True).get(if_name).bytes_recv
        s_byte_1 = psutil.net_io_counters(pernic=True).get(if_name).bytes_sent
        time.sleep(time_quanta)
        r_byte_delta = int(
            psutil.net_io_counters(
                pernic=True).get(if_name).bytes_recv) - int(r_byte_1)
        s_byte_delta = int(
            psutil.net_io_counters(
                pernic=True).get(if_name).bytes_sent) - int(s_byte_1)
        byte_per_sec = (r_byte_delta + s_byte_delta) / time_quanta
        per_util_nic = (byte_per_sec * 100 / (nic_speed * 2**17))
        print(byte_per_sec)
        print(per_util_nic)
        ''' Battery Remaining'''
        bat = psutil.sensors_battery()
        if bat == None:
            per_remian_berrty = 100
        else:
            per_remian_berrty = bat.percent
        '''Z function calculation'''
        #z_val = (core_count_cpu / 8) * per_util_cpu + per_util_mem + per
        '''
        print('CPU Utilization      : ', per_util_cpu)
        print('CPU Core             : ', core_count_cpu)
        print('Memory Utilization   : ', per_util_mem)
        print('Storage Utilization  : ', per_util_disk)
        print('Network Utilization  : ', per_util_nic)
        print('Battery Remaining    : ', per_remian_berrty)
        '''
        cpu_list.append(per_util_cpu * core_count_cpu)
        mem_list.append(per_util_mem)
        bat_list.append(per_remian_berrty)
        nw_list.append(per_util_nic * 8)
        sto_list.append(per_util_disk)

        z_val = per_util_cpu * core_count_cpu + per_util_mem + per_util_disk + 8 * per_util_nic + (
            100 - per_remian_berrty)

        # Timestamp & Datestamp calculation
        ts = time.time()
        ds = str(
            datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
        '''
            ip & mac address
        '''
        #ip = psutil.net_if_addrs()[if_name][0][1]
        cmd_ip = "temp=`ifconfig wlan0 | grep inet | head -1` ; echo $temp | cut -d ' ' -f2 "
        #cmd_ip="ifconfig wlan0 | grep 'inet addr' | cut -d ':' -f2 | cut -d ' ' -f1"
        ip = os.popen(cmd_ip).read().rstrip()
        #mac = psutil.net_if_addrs()[if_name][1][1]
        cmd_mac = "temp=`ifconfig wlan0 | grep ether | head -1` ; echo $temp | cut -d ' ' -f2 "
        #cmd_mac="x=`ifconfig wlan0 | grep 'HWaddr'` ; echo $x | cut -d ' ' -f5"
        mac = os.popen(cmd_mac).read().rstrip()

        insert_data(ip, mac, ts, ds, per_util_cpu, core_count_cpu,
                    per_util_mem, per_util_disk, 8 * per_util_nic, z_val)

        z_list.append(z_val)
        if z_list.__len__() > 100:
            z_list.__delitem__(0)
        print('ip: ', ip, ' mac: ', mac, ' Z_Val:  ', z_val, '\t @ ', ds)
        drawnow(myplot)
def show_graphs():
    print('showing graphs')
    drawnow(plot_graphs)
Exemple #47
0
                projection='merc')
    x1, y1 = m(x, y)
    xarray.append(x1)
    yarray.append(y1)
    m.drawcoastlines()
    im = plt.imread("map.png")
    m.imshow(im, origin='upper')
    print xarray
    print yarray
    print "======"
    m.scatter(xarray, yarray, c='b', marker=".", alpha=1.0)


while (1):
    #X AND Y ARE THE RECEIVED DATA FROM THE GPS SENSOR
    #for now they have just been set to random numbers between the limits
    pos = open(const_pos_sharefile, 'r')
    last_line = pos.readline()
    while (last_line != ""):
        y = float(last_line.split(",")[0])
        x = float(last_line.split(",")[1])
        last_line = pos.readline()
    drawnow(makeFigs)
    time.sleep(0.1)

    #SYSTEM TO START DUMPING OLD DATA - might be completely useless?
    threshold = 1500  #maximum pieces of data
    if len(xarray) > threshold:
        xarray.pop(0)
        yarray.pop(0)
Exemple #48
0
    plt2.plot(h, 'b^-', label='Humidity in %')
    plt2.legend(loc='upper right')

    ax2 = plt.subplot(212, sharex=ax1)
    plt.ylim(0, 100)

    plt.grid(True)
    plt.ylabel('Intensity in Lux')
    plt.plot(l, 'ro-', label='Lux')
    plt.legend(loc='upper left')


while True:
    while (arduinoData.inWaiting() == 0):
        pass
    arduinoString = arduinoData.readline()
    dataArray = arduinoString.split(',')
    lux = float(dataArray[0])
    humd = float(dataArray[1])
    temp = float(dataArray[2])
    t.append(temp)
    h.append(humd)
    l.append(lux)
    drawnow(makeFig)
    plt.pause(.000001)
    count = count + 1
    if (count > 60):
        t.pop(0)
        h.pop(0)
        l.pop(0)
Exemple #49
0
    plt.title('ECG')
    plt.ylabel(' voltage value')
    plt.axis([0,40,0,4])
    plt.grid(True)
##    plt.show()
    

##################################################################

while True:
    if (GPIO.input(lopluse)== GPIO.HIGH | GPIO.input(lominus) == GPIO.HIGH):
        print("!")


    else:
        analogValue = analogRead(0)
        volts = round(((analogValue * 3.3) / 4096.0), 2)
        temp.append(volts)
        temp.pop(0)
        print(analogValue)
        print(volts)
##        print(temp)
        drawnow(graph)
        plt.pause(0.000001)





GPIO.cleanup()
fig = plt.figure()
ax = plt.axes(projection='3d')

ax.scatter3D(servo1, servo2, distance)
#//////////////////////////////////////////////////////////////////////////////

while True:
    while (arduinoData.inWaiting() == 0):  #Wait here until there is data
        pass
#
    arduinoString = arduinoData.readline()
    dataArray = arduinoString.decode().split(',')
    # print(type(dataArray))
    # print(len(dataArray))
    # print(dataArray)
    try:
        s1 = int(dataArray[0])
        s2 = int(dataArray[1])
        sensor = int(dataArray[2])
        dist = 0.0000196 * pow(sensor, 3) + 0.0251 * pow(
            sensor, 2) - 7.3743 * sensor + 678.303
        servo1.append(s1)
        servo2.append(s2)
        distance.append(dist)
        if dist < 40:
            drawnow(makefig)
            plt.pause(.000001)
            cnt = cnt + 1
    except ValueError:
        pass
Exemple #51
0
def drawFig():
    while True:
        drawnow(makeFig)
        plt.pause(.001)
    plt.plot(X, 'ro-', label='X VALUES', c='BLUE')  # plot the xvalues
    plt.plot(Z, 'ro-', label='Z VALUES', c='YELLOW')  #plot the Y values
    plt.legend(loc='upper left')  # plot the legend
    plt.plot(Y, 'ro-', label='Y VALUES', c='RED')  # plot the temperature


while True:  # While loop that loops forever
    while (arduinoData.inWaiting() == 0):  # Wait here until there is data
        pass  # do nothing
    arduinoString = arduinoData.readline(
    )  # read the line of text from the serial port
    dataArray = arduinoString.decode("utf-8").split(
        ',')  # Split it into an array called dataArray
    P = float(
        dataArray[0])  # Convert second element to floating number and put in P
    S = float(dataArray[1])
    Q = float(dataArray[2])
    X.append(P)  # Build our tempF array by appending temp readings
    Z.append(Q)
    Y.append(S)  # Building our pressure array by appending P readings
    drawnow(makeFig)  # Call drawnow to update our live graph
    plt.pause(
        .000001)  # Pause Briefly. Important to keep drawnow from crashing
    cnt = cnt + 1
    if (
            cnt > 50
    ):  # If you have 50 or more points, delete the first one from the array
        X.pop(0)  # This allows us to just see the last 50 data points
        Y.pop(0)
        Z.pop(0)
    plt.grid(True)
    plt.ylabel('Analog Signal AD0')
    plt.plot(Data1, 'r', label='Digital Signal')
    plt.legend(loc='upper right')


if __name__ == '__main__':

    ser = serial.Serial('COM4', 9600)
    plt.ion()
    dCounter = 0
    ser.flush()

    while True:
        while ser.inWaiting() == 0:
            pass  # do nothing if no incoming data

        ardData = ser.readline().decode('utf-8')
        InputData = ardData.split(',')
        temp = float(InputData[0])
        Data1.append(temp)

        drawnow(PlotSignal)
        plt.pause(0.000001)
        dCounter = dCounter + 1
        if dCounter > 60:
            dCounter = 0
        Data1.pop(0)

    ser.close()
Exemple #54
0
        level = int(words[5])
    
        STEP += 1
        STEParray.append(STEP)
        STEPLENGTH = 3.6*math.sin(gyroangle/2/180*math.pi)
        STEPLENGTHarray.append(STEPLENGTH)
        POSITIONX += STEPLENGTH*math.cos(gyroangle1/180*math.pi)
        XARRAY.append(POSITIONX)
        POSITIONY+= STEPLENGTH*math.sin(gyroangle1/180*math.pi)
        YARRAY.append(POSITIONY)
        X_offset = POSITIONX
        Y_offset = POSITIONY
        distance0 = sum(STEPLENGTHarray) ##LINE
        distance1 = math.sqrt(POSITIONX*POSITIONX+POSITIONY*POSITIONY) ##WALK
        ##drawnow(makeFig)
        thread = Thread(drawnow(makeFig))
        thread.start()
        thread.join()
        print(STEPLENGTHarray)
        

        
 

        ##time.sleep(0.00001)    
        ##plt.pause(.000001)#sthash.l3R0774z.dpuf
        #cnt = cnt + 1
        #if(cnt>200):
         #   STEParray.pop(0)
          #  STEPLENGTHarray.pop(0)
           # XARRAY.pop(0)
def makegraph():
    plt.ylim(0, 300)
    plt.title("Sensor Tensão X Corrente")
    plt.grid(True)
    plt.ylabel('Tensão (V)')
    plt.plot(voltage, 'ro-', label='Tensão (V)')
    plt.legend(loc='upper left')
    plt2 = plt.twinx()
    plt.ylim(0, 2)
    plt2.plot(amps, 'b^-', label='Corrente (A)')
    plt2.set_ylabel('Corrente (A)')
    plt2.ticklabel_format(useOffset=False)
    plt2.legend(loc='upper right')


while True:
    while (arduino.inWaiting() == 0):
        pass
    arduinoString = arduino.readline()
    dataArray = arduinoString.decode().split(',')
    volt = float(dataArray[0])
    amp = float(dataArray[1])
    voltage.append(volt)
    amps.append(amp)
    drawnow(makegraph)
    plt.pause(.000001)
    cnt = cnt + 1
    if (cnt > 50):
        voltage.pop(0)
        amps.pop(0)
Exemple #56
0
        u, sigmas, v = svd(x[:,:,i])
        sigmas[k:] = 0

        s = zeros_like(x[:,:,i])
        fill_diagonal(s, sigmas)

        color = u.dot(s).dot(v)
        y[:,:,i] = np.clip(color, 0, 1)
    return y

WIDTH = 7
figure(figsize=(WIDTH, WIDTH / 2))
def draw_fig():
    """ Uses Python's global scope """
    subplot(1, 2, 1)
    imshow(x, cmap='gray')
    title('Original')
    axis('off')

    subplot(1, 2, 2)
    imshow(x_hat, cmap='gray')
    title('Approx with $k=%d$' % k)
    axis('off')
    # show()

x = imread('test-data/mandrill.png')
k_values = around(logspace(0.1, log10(64), num=10)).astype('int')
for k in k_values:
    x_hat = approx(x, k)
    drawnow(draw_fig, stop_on_close=True)
def main():
    global record
    global client_id_
    global seq

    os.system('clear')
    print("================== Welcome to Client Platform ===================")
    get_mec_details()
    client_id_ = client_id(ip_address())
    '''
    thread_record.append(Thread(target=receive_tasks))
    thread_record[-1].daemon = True
    thread_record[-1].start()
    '''
    redeem_task = Thread(target=receive_mec_start)
    redeem_task.daemon = True
    redeem_task.start()
    while True:
        time.sleep(1)
        if len(hosts) > 0:
            break
    print('Client is connected to servers: {}'.format(hosts))
    while True:
        try:
            x = input('Enter "y" to start and "stop" to exit: ').strip().lower()
            if x == 'y':
                for i in range(600):
                    seq = i
                    rand_host = hosts[gosh_dist(len(hosts))]      # randomly selecting a host to send task to
                    _task_ = get_tasks()                 # tasks, waiting time
                    _tasks_list = name_task(_task_, client_id(rand_host), i)   # id's tasks => ({tasks}, {waiting time})

                    record.append([_tasks_list, host_dict[rand_host]])
                    for task in _tasks_list[0]:
                        if i not in task_record:   # task_record= {seq_no:{task:[duration,start_time,finish_time]}}
                            task_record[i] = {task: [_task_[1][task[:2]][1], get_time()]}
                        else:
                            task_record[i][task] = [_task_[1][task[:2]][1], get_time()]
                    # client(_tasks_list, rand_host)
                    task_client.publish(client_id(rand_host), "t {}".format(_tasks_list))
                    print("Sent {} to {} node_id {} \n\n".format(_tasks_list, rand_host, client_id(rand_host)))
                    drawnow(plot_performance)
                    time.sleep(3)
            elif x == 'stop':
                print('\nProgramme terminated')

                result = f"timely{get_hostname()[-1]}_{algo_id}_{len(hosts)} = {tasks_executed_on_time} " \
                         f"\nuntimely{get_hostname()[-1]}_{algo_id}_{len(hosts)} = {tasks_not_executed_on_time}" \
                         f"\nrecord{len(hosts)} = {record} \nhost_names{len(hosts)} = {host_dict}"
                list_result = [
                    f"timely{get_hostname()[-1]}_{algo_id}_{len(hosts)} = {tasks_executed_on_time} ",
                    f"\nuntimely{get_hostname()[-1]}_{algo_id}_{len(hosts)} = {tasks_not_executed_on_time}",
                    f"\nrecord{len(hosts)} = {record} ",
                    f"\nhost_names{len(hosts)} = {host_dict}"
                ]
                for i in list_result:
                    cmd = 'echo "{}" >> data.py'.format(i)
                    os.system(cmd)

                send_result(ho['osboxes-0'], list_result)
                send_email(result)

                task_client.loop_stop()
                print('done')
                time.sleep(1)
                break

        except KeyboardInterrupt:
            print('\nProgramme terminated')
            task_client.loop_stop()
            break
 moistureArray = array('f')              #declares an array of floats
 luxArray = array('f')                   #declares an array of floats (yes! you need to store the data somewhere right ? don't play a *f iDiot with me! Ok ?)
 dataArrayA.append(fa)                   #appends a value to the float array (here the data is stored to each array! Sure I could have used arrays of objects! But I'm not in the mood!
 dataArrayB.append(fb)                   #appends a value to the float array (and since you noticed that, bring me some coffee!)
 tempArrayA.append(fha)                  #appends a value to the float array
 tempArrayB.append(fhb)                  #appends a value to the float array
 moistureArray.append(fhs)               #appends a value to the float array
 luxArray.append(fl)                     #appends a value to the float array
 temp = dataArrayA[0]                    #Convert first element to floating number and put in temp
 temp2 = dataArrayB[0]                   #Convert first element to floating number and put in temp2
 hum1 = tempArrayA[0]                    #Convert first element to floating number and put in hum1 (the humidity array for sensor one)
 hum2 = tempArrayB[0]                    #Convert first element to floating number and put in hum1 (the humidity array for sensor one)
 moisture = moistureArray[0]             #...
 lumen = luxArray[0]                     #Convert first element to floating number and put in hum2 (if you got this far and understood, this line does not need explanations!)
 tempF.append(temp)                      #Build the tempFf array by appending temp readings
 tempF2.append(temp2)                    #Build the tempF2 array by appending temp2 readings
 humF1.append(hum1)                      #Build the humF1 array by appending hum1 readings
 humF2.append(hum2)                      #Build the humF2 array by appending hum2 readings
 moist.append(moisture)                  #Build the moistureArray array by appending  readings
 lum.append(lumen)                       #don't play dumb again! And if you do increment the following counter in 1 ApplePhoneCounter = 0
 drawnow(makeFig)                        #Call drawnow to update our live graph
 plt.pause(.000001)                      #Pause Briefly. Important to keep drawnow from crashing
 cnt=cnt+1                                #increments counter
 if(cnt>50):                             #If you have 50 or more points, delete the first one from the array
     tempF.pop(0)                        #This allows us to just see the last 50 data points and of clears the *f mess that is done before
     tempF2.pop(0)                       #...
     humF1.pop(0)                        #...
     humF2.pop(0)                        #...
     moist.pop(0)                        #...
     lum.pop(0)                          #...
     #don't read my *f code! you fricking iDiot!
Exemple #59
0
#pre-load dummy data
for i in range(0,26):
    values.append(0)
    
while True:
    while (serialArduino.inWaiting()==0):
        pass
    print("readline()")
    valueRead = serialArduino.readline(500)

    #check if valid value can be casted
    try:
        valueInInt = int(valueRead)
        test_val = valueInInt*5.0/1024.0
        print(valueInInt)
        if valueInInt <= 1024:
            if valueInInt >= 0:
                #values.append(valueInInt)
                values.append(test_val)
                values.pop(0)
                drawnow(plotValues,show_once=True)
                plt.pause(.000001)
                #plt.pause(.0001)
            else:
                print("Invalid! negative number")
        else:
            print("Invalid! too large")
    except ValueError:
        print("Invalid! cannot cast")