#!/usr/bin/env python import time import serial import sys, tty, termios class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() def getChar() : fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch ser = serial.Serial( port='/dev/ttyACM2', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1) counter=0 #while 1: #getch = _Getch() #/*ser.write('Write counter: %d \n'%(counter))*/ #ser.write(getch) # data=bytes([0x0c,0x80,0x09,0x00,0xf0,0xce,0x61,0x9d,0x01,0x00,0x01,0x00,0x00,0x00]) # ser.write(data) # time.sleep(1) # counter += 1 while 1 : # get keyboard input #input = raw_input(">> ") input = getChar() # Python 3 users # input = input(">> ") if input == 'o': ser.close() exit() else: # send the character to the device # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device) ser.write(input + '\r\n') out = '' # let's wait one second before reading output (let's give device time to answer) time.sleep(0.2) while ser.inWaiting() > 0: out += ser.read(1) if out != '': print ">>" + out