import time, re, serial timer = 5 ok = re.compile('A') def drawBot(): # Draws a teddy bear robot Egyptian-walking-style silhouette # ================================================================================================================== commands = ['d', 'g5', 't-38', 'g4', 't33', 'g10', 't-35', 'g1', 't35', 'g-10', 't34', 'g-4', 'u', 'g4', 't-34', 'g10', 't-35', 'd', 'g6', 't-35', 'g10', 't-35', 'g4', 't38', 'g6', 't38', 'g5', 't-33', 'g10', 't-34', 'g10', 't-38', 'g7', 't36', 'g7', 't-34', 'g4', 't34', 'g4', 't36', 'g2', 't36', 'g4', 't-36', 'g2', 't-36', 'g4', 't36', 'g2', 't36', 'g4', 't34', 'g4', 't-34', 'g5', 't-36', 'g5', 't33', 'g5', 't-33', 'g5', 't-36', 'g3', 't36', 'g3', 't36', 'g3', 't-33', 'g3', 't-33', 'g3', 't36', 'g3', 't36', 'g3', 't-36', 'g5', 't-33', 'g5', 't-34', 'g7', 't36', 'g7', 't-34', 'g3', 't34', 'g3', 't36', 'g2', 't36', 'g3', 't-36', 'g2', 't-36', 'g3', 't36', 'g2', 't36', 'g3', 't34', 'g3', 't-34', 'g5', 't-36', 'g5', 't-35', 'g10', 'u', 't35', 'g-20'] # ================================================================================================================== for c in commands: print c executed = False while (executed == False): out = '' ser.write(c) time.sleep(0.25) for i in xrange(1, timer): time.sleep(1) out += ser.read(1) print out+'\n' res = ok.search(out) if (i == timer): print 'Trying again after', i, 'seconds!' break elif res: executed = True break else: continue # configure the serial connections # (the parameters differs on the device you are connecting to) ser = serial.Serial( #port='/dev/ttyUSB0', #port='/dev/rfcomm0', #port='/dev/rfcomm1', #port='/dev/rfcomm2', port='COM13', baudrate=9600, timeout=1 ) print 'Enter your commands below.\r\nInsert "exit" to leave the application.' input=1 while 1 : # get keyboard input input = raw_input(">> ") # Python 3 users # input = input(">> ") if input == 'exit': ser.close() exit() elif input == 'draw': drawBot() 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 [some time] before reading output # (that is, let's give device time to answer) #time.sleep(0.25) time.sleep(1) while ser.inWaiting() > 0: out += ser.readline() #ser.read(1) if out != '': print ">>" + out