Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.44 KB | None | 0 0
  1. import sys
  2. import pygame
  3. from subprocess import call
  4. import glob
  5. import serial
  6. from threading import Thread
  7. import time
  8.  
  9. tasti_input = {3:'Quadrato',0:'Triangolo',1:'Cerchio',2:'X',5:'R1',4:'L1',9:'Start',8:'Select',7:'R2',6:'L2'}
  10. tasti_frecce = { (0,0):'Stop',(0,1):'Su' , (-1,0):'Sinistra',(0,-1):'Giu',(1,0):'Destra'}
  11. keyboard_pressed = 2
  12. keyboard_released = 3
  13. EXIT = 27
  14. done = False
  15. key=0
  16. #stop_frecce = (0,0)
  17. in_reading = False
  18.  
  19. speed = 1
  20. max_speed = 4
  21. stop_speed = 0
  22. speed_vector = ['0','1','2','3']
  23.  
  24.  
  25. def serial_ports():
  26.     """ Lists serial port names
  27.  
  28.        :raises EnvironmentError:
  29.            On unsupported or unknown platforms
  30.        :returns:
  31.            A list of the serial ports available on the system
  32.    """
  33.     if sys.platform.startswith('win'):
  34.         ports = ['COM%s' % (i + 1) for i in range(256)]
  35.     elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  36.         # this excludes your current terminal "/dev/tty"
  37.          ports = glob.glob('/dev/tty.usb[A-Za-z]*')
  38.       #  ports = glob.glob('/dev/tty[A-Za-z]*')
  39.     elif sys.platform.startswith('darwin'):
  40.        # ports = glob.glob('/dev/tty')
  41.          ports = glob.glob('/dev/tty.usb*')
  42.     else:
  43.         raise EnvironmentError('Unsupported platform')
  44.  
  45.     result = []
  46.     for port in ports:
  47.         try:
  48.             s = serial.Serial(port)
  49.             s.close()
  50.             result.append(port)
  51.         except (OSError, serial.SerialException):
  52.             pass
  53.     return result
  54.  
  55. def get_port(bR,check=False):
  56.  
  57.     name_port = serial_ports()
  58.  
  59.     if len(name_port) ==0:
  60.  
  61.         print("ATTENZIONE STM NON COLLEGATO")
  62.         return None
  63.  
  64.     else:
  65.         ser = serial.Serial(name_port.pop(), baudrate=bR)  # open serial port
  66.         # ser.open()
  67.         if check:
  68.             print(ser)
  69.  
  70.     return ser
  71.  
  72. def read(ser,data_r):
  73.  
  74.     global in_reading
  75.  
  76.     while in_reading :
  77.         tmp = ser.read(1)
  78.  
  79.         if (tmp != '\n'):
  80.             data_r = data_r + tmp
  81.         else:
  82.             print(data_r)
  83. #            time.sleep(1)
  84.             data_r = ""
  85.  
  86. def read_on(tr):
  87.  
  88.     tr.start()
  89.  
  90. def read_off(tr):
  91.  
  92.     tr._stop()
  93.  
  94. """Configurazione joystick"""
  95.  
  96. pygame.init()
  97. pygame.joystick.init()
  98.  
  99. joystick_count = pygame.joystick.get_count()
  100. joystick_init = pygame.joystick.get_init()
  101.  
  102. print("Numero joystick = : "+str(joystick_count))
  103.  
  104. if joystick_count>=1:
  105.     print("Joystick inizializzato = : " + str(joystick_init))
  106.     stick = pygame.joystick.Joystick(0)
  107.     stick.init()
  108.  
  109. clock = pygame.time.Clock()
  110.  
  111. """Configurazione UART"""
  112.  
  113. ser = get_port(115200, True)
  114.  
  115. """data_r = ""
  116. tr = Thread(target=read, args=(ser, data_r))"""
  117.  
  118.  
  119.  
  120. while not done:
  121.  
  122.     for event in pygame.event.get():
  123.  
  124.         # pulsanti joystick premuti
  125.  
  126.         if event.type == pygame.JOYBUTTONDOWN:
  127.  
  128.             button_key = event.button
  129.  
  130.             if(tasti_input.has_key(button_key)):
  131.  
  132.                 print("Joystick button pressed :    " + tasti_input[event.button])
  133.  
  134.                 if tasti_input[button_key] == 'Start':
  135.  
  136.                     print("Uscita in corso...")
  137.  
  138.                     done = True
  139.  
  140.                 elif tasti_input[button_key] == 'Select':
  141.  
  142.                     if not in_reading:
  143.                         in_reading = True
  144.                         data_r = ""
  145.                         tr = Thread(target=read, args=(ser, data_r))
  146.                         read_on(tr)
  147.                     else:
  148.                         in_reading = False
  149.  
  150.  
  151.                 elif tasti_input[button_key] == 'R1' and speed < max_speed - 1 :
  152.  
  153.                     speed = speed + 1
  154.                   #  ser.write(speed_vector[speed])
  155.  
  156.  
  157.                 elif tasti_input[button_key] == 'L1' and speed > 1 :
  158.  
  159.                     speed = speed - 1
  160.                  #   ser.write(speed_vector[speed])
  161.  
  162.  
  163.             else:
  164.                 print("Joystick button pressed :    " + str(event.button))
  165.  
  166.         # freccette direzionali premute
  167.  
  168.         elif event.type == pygame.JOYHATMOTION:
  169.  
  170.             button_key = event.value
  171.  
  172.             if (tasti_frecce.has_key(event.value)):
  173.  
  174.                 print("Joystick button pressed :    " + tasti_frecce[button_key])
  175.  
  176.                 if tasti_frecce[button_key] == 'Su':
  177.  
  178.                     ser.write(speed_vector[speed])
  179.  
  180.                 elif tasti_frecce[button_key] == 'Giu' or tasti_frecce[button_key] == 'Stop':
  181.  
  182.                     ser.write(speed_vector[stop_speed])
  183.  
  184.  
  185.             else:
  186.                 print("Joystick button pressed :    " + str(event.value))
  187.  
  188.         # Comandi da tastiera
  189.  
  190.         elif event.type == keyboard_pressed:
  191.  
  192.             key_pressed = event.key
  193.  
  194.             if key_pressed == EXIT:
  195.  
  196.                 print("Uscita in corso...")
  197.  
  198.                 done = True
  199.  
  200.             elif not key_pressed < 0 and not key_pressed >= 127:
  201.  
  202.                 char_key = chr(key_pressed)
  203.  
  204.                 print("Pressed keyboard button   " + str(char_key))
  205.  
  206.                 if char_key == 'r' and not in_reading:
  207.  
  208.                     in_reading = True
  209.                     data_r = ""
  210.                     tr = Thread(target=read, args=(ser, data_r))
  211.                     read_on(tr)
  212.  
  213.                 elif char_key == 'r' and in_reading:
  214.  
  215.                     in_reading = False
  216.  
  217.             else:
  218.  
  219.                 print(event)
  220.  
  221.        # else:
  222.        #     print(event)
  223.  
  224.     clock.tick(600)
  225.  
  226. pygame.joystick.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement