Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Script per l'acquisizione di dati dall'accelerometro MMA7361 collegato tramite Arduino(usato come ADC)
- #legge i dati dalla porta seriale(che genera uno sketch caricato sull'arduino
- #genera un file (ggmmaaaa.csv) con il tempo, il valore per x, y e z
- #Gnuplot crea un grafico utilizzando la prima colnna(il tempo)+[x+y+z]
- #A mezzanotte si genra un nuovo file
- #22/08/2017
- import serial
- import csv
- import time
- import re
- import matplotlib.pyplot as plt
- portPath = "/dev/ttyACM0" # Must match value shown on Arduino IDE
- baud = 9600 # Must match Arduino baud rate
- timeout = 15 # Seconds
- #filename = "data.csv"
- max_num_readings = 100
- #num_signals = 1
- # crea file di configurazione per gnuplot per l'utente diego;
- # l'utente dovra' creare un opportuno crontab per creare il grafico ogni minuto(???????)
- #Gnuplot deve generare tre grafici utizzando tempo+ x,tempo + y, tempo+z(???????????)
- def gpltconf(fileout):
- fgp=open("/home/diego/public_html/sismo.gplt","w",0)
- fgp.write("set style data dots"+"\n"+
- "set autoscale x"+"\n"+
- "set autoscale y"+"\n"+
- "set grid"+"\n"+
- "set term jpeg size 1024,768"+"\n"+
- "set output 'sismo_x.jpg'"+"\n"+
- "plot '"+fileout+"' using 1:2"+"\n"
- "set style data lines"+"\n"+
- "set output 'sismo_x_ultimora.jpg'"+"\n"+
- "plot '<tail -66000 "+fileout+"' us 1:2")
- fgp.close()
- #orario
- dataora = time.asctime( time.localtime(time.time()) )
- t=time.localtime()
- #prelevo l'ora
- torattuale=t[3]
- tt0=time.strftime("%Y%m%d-%H%M%S",t)
- # istante inizio registrazione
- s00=float(time.time())
- # file di output
- fileoutname="sismo_"+tt0+".dat"
- fileout="/home/diego/public_html/"+fileoutname
- print
- print "file di output: ",fileout
- gpltconf(fileout)
- print "registrato nel file di configurazione per gnuplot"
- print
- print "ricorda Ctrl-Z e poi bg per lasciarlo girare in background"
- print
- # inizializzo conta righe:
- k=0
- # apro il file di output; verra' cambiato alla mezzanotte:
- ff=open(fileout,"a",0)
- def create_serial_obj(portPath, baud_rate, tout):
- """
- Given the port path, baud rate, and timeout value, creates
- and returns a pyserial object.
- """
- return serial.Serial(portPath, baud_rate, timeout = tout)
- def read_serial_data(serial):
- """
- Given a pyserial object (serial). Outputs a list of lines read in
- from the serial port
- """
- serial.flushInput()
- serial_data = []
- readings_left = True
- timeout_reached = False
- while readings_left and not timeout_reached:
- serial_line = serial.readline()
- if serial_line == '':
- timeout_reached = True
- else:
- serial_data.append(serial_line)
- if len(serial_data) == max_num_readings:
- readings_left = False
- return serial_data
- def is_number(string):
- """
- Given a string returns True if the string represents a number.
- Returns False otherwise.
- """
- try:
- float(string)
- return True
- except ValueError:
- return False
- def clean_serial_data(data):
- """
- Given a list of serial lines (data). Removes all characters.
- Returns the cleaned list of lists of digits.
- Given something like: ['0.5000,33\r\n', '1.0000,283\r\n']
- Returns: [[0.5,33.0], [1.0,283.0]]
- """
- clean_data = []
- for line in data:
- line_data = re.findall("\d*\.\d*|\d*",line) # Find all digits
- line_data = [float(element) for element in line_data if is_number(element)] # Convert strings to float
- if len(line_data) >= 2:
- clean_data.append(line_data)
- return clean_data
- def save_to_csv(data, filename):
- """
- Saves a list of lists (data) to filename
- """
- with open(filename, 'wb') as csvfile:
- csvwrite = csv.writer(csvfile)
- csvwrite.writerows(data)
- def gen_col_list(num_signals):
- """
- Given the number of signals returns
- a list of columns for the data.
- E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3']
- """
- col_list = ['Time']
- for i in range(1,4 +1):#num_signals +1):
- col = 'Signal1'+str(i)
- col_list.append(col)
- return col_list
- def map_value(x, in_min, in_max, out_min, out_max):
- return (((x - in_min) * (out_max - out_min))/(in_max - in_min)) + out_min
- def simple_plot(csv_file, columns, headers):
- plt.clf()
- plt.close()
- plt.plotfile(csv_file, columns, names=headers, newfig=True)
- plt.show()
- print "Creating serial object..."
- serial_obj = create_serial_obj(portPath, baud, timeout)
- print "Reading serial data..."
- serial_data = read_serial_data(serial_obj)
- print len(serial_data)
- print "Cleaning data..."
- clean_data = clean_serial_data(serial_data)
- print "Saving to csv..."
- save_to_csv(clean_data, filename)
- print "Plotting data..."
- #simple_plot(filename, (0,1,2), ['time (s)', 'voltage1', 'voltage2'])
- #simple_plot(filename, (0,1), ['time (s)', 'voltage1'])
- #plot_csv(filename, gen_col_list(num_signals))
- # ogni 100 righe salva l'immagine webcam.jpeg e chiude il file e subito lo riapre
- k=k+1
- if k==500:
- ff.flush()
- ff.close()
- cv2.imwrite("/home/diego/public_html/webcam.jpg",im)
- k=0
- t=time.localtime()
- #prelevo l'ora
- tora=t[3]
- # a mezzanotte cambia file di output
- if tora < torattuale:
- tt0=time.strftime("%Y%m%d-%H%M%S",t)
- s00=float(time.time())
- fileoutname="sismo_"+tt0+".dat"
- fileout="/home/diego/public_html/"+fileoutname
- gpltconf(fileoutname)
- ff=open(fileout,"a",0)
- torattuale=tora
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement