Advertisement
Guest User

Untitled

a guest
Feb 27th, 2011
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. #-*- coding:utf-8 -*-
  3.  
  4. '''
  5.     Autor: Joao Bernardo Vianna
  6.     Data: 26/02/2011
  7. '''
  8.  
  9. import serial
  10. import sys
  11. import time
  12.  
  13. ucontr = 'Arduino'
  14. base_porta = '/dev/ttyUSB'
  15. taxa = 115200
  16. tempo = 5   #Timeout da conexao
  17.  
  18.  
  19. #########################################################################
  20. def procura_serial(porta, taxa, tempo):
  21.     s = None
  22.     for i in range(32):
  23.         try:
  24.             s = serial.Serial(porta + str(i), taxa, timeout=tempo)
  25.         except serial.SerialException:
  26.             continue
  27.         else:
  28.             break
  29.     return s
  30.  
  31. #########################################################################
  32. def sair(obj_serial):
  33.     obj_serial.close()
  34.     exit()
  35.  
  36. #########################################################################
  37. def _data():
  38.     return time.strftime('%d/%m/%Y %H:%M:%S')
  39.  
  40. #########################################################################
  41. def amostragem(obj_serial, num):
  42.     amostras = []
  43.     try:
  44.         for i in range(num):
  45.             amostras.append(str(obj_serial.readline().rstrip(), 'utf8'))
  46.     except KeyboardInterrupt:
  47.         pass
  48.    
  49.     return amostras
  50.  
  51. #########################################################################
  52.  
  53. if __name__ == '__main__':
  54.     s = procura_serial(base_porta, taxa, tempo)
  55.  
  56.     if not s:
  57.         print('Impossível encontrar %s...' % ucontr)
  58.         exit()
  59.     else:
  60.         print(ucontr + 'na porta' + str(s.port))
  61.  
  62.  
  63.     arg = sys.argv[1:]
  64.  
  65.     arquivo = ''
  66.     if len(arg) == 2:
  67.         arquivo = arg[-1]
  68.  
  69.     if arg:
  70.         arg = arg[0]
  71.     else:
  72.         print('Colocar número de amostras como argumento...')
  73.         sair(s)
  74.  
  75.     try:
  76.         leituras = int(arg)
  77.         if leituras == 0:
  78.             leituras = 2**64    #leitura 'infinita'
  79.     except ValueError:
  80.         print('Colocar número válido como argumento...')
  81.         sair(s)
  82.  
  83.  
  84.     print('Amostragem iniciada em ' + _data())
  85.  
  86.     amostras = amostragem(s, leituras)
  87.  
  88.     print('Amostragem terminada em ' + _data())
  89.  
  90.     if arquivo:
  91.         open(arquivo, 'w').write(str(amostras))
  92.         print(str(len(amostras)) + ' pontos salvos em ' + arquivo)
  93.  
  94.     sair(s)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement