Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.47 KB | None | 0 0
  1. Script per l'acquisizione di dati dall'accelerometro MMA7361 collegato tramite Arduino(usato come ADC)
  2. #legge i dati dalla porta seriale(che genera uno sketch caricato sull'arduino
  3. #genera un file (ggmmaaaa.csv) con il tempo, il valore per x, y e z
  4. #Gnuplot crea un grafico utilizzando la prima colnna(il tempo)+[x+y+z]
  5. #A mezzanotte si genra un nuovo file
  6. #22/08/2017
  7.  
  8. import serial
  9. import csv
  10. import time
  11. import re
  12. import matplotlib.pyplot as plt
  13.  
  14.  
  15. portPath = "/dev/ttyACM0" # Must match value shown on Arduino IDE
  16. baud = 9600 # Must match Arduino baud rate
  17. timeout = 15 # Seconds
  18.  
  19. #filename = "data.csv"
  20.  
  21. max_num_readings = 100
  22. #num_signals = 1
  23.  
  24.  
  25.  
  26. # crea file di configurazione per gnuplot per l'utente diego;
  27. # l'utente dovra' creare un opportuno crontab per creare il grafico ogni minuto(???????)
  28. #Gnuplot deve generare tre grafici utizzando tempo+ x,tempo + y, tempo+z(???????????)
  29. def gpltconf(fileout):
  30. fgp=open("/home/diego/public_html/sismo.gplt","w",0)
  31. fgp.write("set style data dots"+"\n"+
  32. "set autoscale x"+"\n"+
  33. "set autoscale y"+"\n"+
  34. "set grid"+"\n"+
  35. "set term jpeg size 1024,768"+"\n"+
  36. "set output 'sismo_x.jpg'"+"\n"+
  37. "plot '"+fileout+"' using 1:2"+"\n"
  38. "set style data lines"+"\n"+
  39. "set output 'sismo_x_ultimora.jpg'"+"\n"+
  40. "plot '<tail -66000 "+fileout+"' us 1:2")
  41. fgp.close()
  42.  
  43. #orario
  44. dataora = time.asctime( time.localtime(time.time()) )
  45.  
  46. t=time.localtime()
  47. #prelevo l'ora
  48. torattuale=t[3]
  49. tt0=time.strftime("%Y%m%d-%H%M%S",t)
  50. # istante inizio registrazione
  51. s00=float(time.time())
  52.  
  53.  
  54. # file di output
  55. fileoutname="sismo_"+tt0+".dat"
  56. fileout="/home/diego/public_html/"+fileoutname
  57. print
  58. print "file di output: ",fileout
  59. gpltconf(fileout)
  60. print "registrato nel file di configurazione per gnuplot"
  61. print
  62. print "ricorda Ctrl-Z e poi bg per lasciarlo girare in background"
  63. print
  64.  
  65. # inizializzo conta righe:
  66. k=0
  67.  
  68. # apro il file di output; verra' cambiato alla mezzanotte:
  69. ff=open(fileout,"a",0)
  70.  
  71.  
  72. def create_serial_obj(portPath, baud_rate, tout):
  73. """
  74. Given the port path, baud rate, and timeout value, creates
  75. and returns a pyserial object.
  76. """
  77. return serial.Serial(portPath, baud_rate, timeout = tout)
  78.  
  79. def read_serial_data(serial):
  80. """
  81. Given a pyserial object (serial). Outputs a list of lines read in
  82. from the serial port
  83. """
  84. serial.flushInput()
  85.  
  86. serial_data = []
  87. readings_left = True
  88. timeout_reached = False
  89.  
  90. while readings_left and not timeout_reached:
  91. serial_line = serial.readline()
  92. if serial_line == '':
  93. timeout_reached = True
  94. else:
  95. serial_data.append(serial_line)
  96. if len(serial_data) == max_num_readings:
  97. readings_left = False
  98.  
  99. return serial_data
  100.  
  101. def is_number(string):
  102. """
  103. Given a string returns True if the string represents a number.
  104. Returns False otherwise.
  105. """
  106. try:
  107. float(string)
  108. return True
  109. except ValueError:
  110. return False
  111.  
  112. def clean_serial_data(data):
  113. """
  114. Given a list of serial lines (data). Removes all characters.
  115. Returns the cleaned list of lists of digits.
  116. Given something like: ['0.5000,33\r\n', '1.0000,283\r\n']
  117. Returns: [[0.5,33.0], [1.0,283.0]]
  118. """
  119. clean_data = []
  120.  
  121. for line in data:
  122. line_data = re.findall("\d*\.\d*|\d*",line) # Find all digits
  123. line_data = [float(element) for element in line_data if is_number(element)] # Convert strings to float
  124. if len(line_data) >= 2:
  125. clean_data.append(line_data)
  126.  
  127. return clean_data
  128.  
  129. def save_to_csv(data, filename):
  130. """
  131. Saves a list of lists (data) to filename
  132. """
  133. with open(filename, 'wb') as csvfile:
  134. csvwrite = csv.writer(csvfile)
  135. csvwrite.writerows(data)
  136.  
  137. def gen_col_list(num_signals):
  138. """
  139. Given the number of signals returns
  140. a list of columns for the data.
  141. E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3']
  142. """
  143. col_list = ['Time']
  144. for i in range(1,4 +1):#num_signals +1):
  145. col = 'Signal1'+str(i)
  146.  
  147. col_list.append(col)
  148.  
  149. return col_list
  150.  
  151.  
  152.  
  153. def map_value(x, in_min, in_max, out_min, out_max):
  154. return (((x - in_min) * (out_max - out_min))/(in_max - in_min)) + out_min
  155.  
  156.  
  157. def simple_plot(csv_file, columns, headers):
  158. plt.clf()
  159. plt.close()
  160. plt.plotfile(csv_file, columns, names=headers, newfig=True)
  161. plt.show()
  162.  
  163.  
  164.  
  165.  
  166. print "Creating serial object..."
  167. serial_obj = create_serial_obj(portPath, baud, timeout)
  168.  
  169. print "Reading serial data..."
  170. serial_data = read_serial_data(serial_obj)
  171. print len(serial_data)
  172.  
  173. print "Cleaning data..."
  174. clean_data = clean_serial_data(serial_data)
  175.  
  176. print "Saving to csv..."
  177. save_to_csv(clean_data, filename)
  178.  
  179. print "Plotting data..."
  180. #simple_plot(filename, (0,1,2), ['time (s)', 'voltage1', 'voltage2'])
  181. #simple_plot(filename, (0,1), ['time (s)', 'voltage1'])
  182. #plot_csv(filename, gen_col_list(num_signals))
  183.  
  184.  
  185. # ogni 100 righe salva l'immagine webcam.jpeg e chiude il file e subito lo riapre
  186. k=k+1
  187. if k==500:
  188. ff.flush()
  189. ff.close()
  190. cv2.imwrite("/home/diego/public_html/webcam.jpg",im)
  191. k=0
  192. t=time.localtime()
  193. #prelevo l'ora
  194. tora=t[3]
  195. # a mezzanotte cambia file di output
  196. if tora < torattuale:
  197. tt0=time.strftime("%Y%m%d-%H%M%S",t)
  198. s00=float(time.time())
  199. fileoutname="sismo_"+tt0+".dat"
  200. fileout="/home/diego/public_html/"+fileoutname
  201. gpltconf(fileoutname)
  202. ff=open(fileout,"a",0)
  203. torattuale=tora
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement