write_serail.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python
  2. import time
  3. import serial
  4. import sys, tty, termios
  5. class _Getch:
  6. """Gets a single character from standard input. Does not echo to the screen."""
  7. def __init__(self):
  8. try:
  9. self.impl = _GetchWindows()
  10. except ImportError:
  11. self.impl = _GetchUnix()
  12. def __call__(self): return self.impl()
  13. class _GetchUnix:
  14. def __init__(self):
  15. import tty, sys
  16. def __call__(self):
  17. import sys, tty, termios
  18. fd = sys.stdin.fileno()
  19. old_settings = termios.tcgetattr(fd)
  20. try:
  21. tty.setraw(sys.stdin.fileno())
  22. ch = sys.stdin.read(1)
  23. finally:
  24. termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
  25. return ch
  26. class _GetchWindows:
  27. def __init__(self):
  28. import msvcrt
  29. def __call__(self):
  30. import msvcrt
  31. return msvcrt.getch()
  32. def getChar() :
  33. fd = sys.stdin.fileno()
  34. old_settings = termios.tcgetattr(fd)
  35. try:
  36. tty.setraw(sys.stdin.fileno())
  37. ch = sys.stdin.read(1)
  38. finally:
  39. termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
  40. return ch
  41. ser = serial.Serial(
  42. port='/dev/ttyACM2',
  43. baudrate = 9600,
  44. parity=serial.PARITY_NONE,
  45. stopbits=serial.STOPBITS_ONE,
  46. bytesize=serial.EIGHTBITS,
  47. timeout=1)
  48. counter=0
  49. #while 1:
  50. #getch = _Getch()
  51. #/*ser.write('Write counter: %d \n'%(counter))*/
  52. #ser.write(getch)
  53. # data=bytes([0x0c,0x80,0x09,0x00,0xf0,0xce,0x61,0x9d,0x01,0x00,0x01,0x00,0x00,0x00])
  54. # ser.write(data)
  55. # time.sleep(1)
  56. # counter += 1
  57. while 1 :
  58. # get keyboard input
  59. #input = raw_input(">> ")
  60. input = getChar()
  61. # Python 3 users
  62. # input = input(">> ")
  63. if input == 'o':
  64. ser.close()
  65. exit()
  66. else:
  67. # send the character to the device
  68. # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
  69. ser.write(input + '\r\n')
  70. out = ''
  71. # let's wait one second before reading output (let's give device time to answer)
  72. time.sleep(0.2)
  73. while ser.inWaiting() > 0:
  74. out += ser.read(1)
  75. if out != '':
  76. print ">>" + out