Making a Robot With Arduino Part 5: The PC Program
The remote control part of the robot already done, now to control it. Because I am out of component. So I decide to write a program to do so. The control program uses python, and it control via serial interface to the arduino, without the microntroller.
Python have many stuff in their standard library, but they don’t have a serial library. On the other hand, python community have created many library that is not in the standard library, pyserial is one http://pyserial.sourceforge.net/. To install it, just use
pip install pyserial
The library is very easy to use too. You need a sleep because sometime the arduino will drop the command if you send it too fast. So just use sleep as a delay. The serial port on windows it is comN, on the constructure replace ‘your serial port’ with a number without quote, it could be 0 for com1, etc. On linux you can specify the path, ‘/deve/ttyUSB0′ or 1 or what not.
import serialimport datetime.time as times = serial.Serial('your_usb_serial_port') time.sleep(2) s.write('serial command') s.close()
Essentially just 4 line minus import just to send serial command.
To make it fancy, I just bundle it with tkinter library for UI, which is part of the python standard library.
from Tkinter import * import serial import time class RobotUI: def __init__(self,master,port): self.port = port frame = Frame(master) frame.pack() self.forward_button = Button(frame,text="Forward",command=self.move_forward) self.forward_button.pack(side=TOP) self.backward_button = Button(frame,text="Backward",command=self.move_backward) self.backward_button.pack(side=BOTTOM) self.left_button = Button(frame,text="Rotate Left",command=self.rotate_left) self.left_button.pack(side=LEFT) self.right_button = Button(frame,text="Rotate Right",command=self.rotate_right) self.right_button.pack(side=LEFT) def move_forward(self): print "forward" self.move_('w') def move_backward(self): print "backward" self.move_('s') def rotate_left(self): print "left" self.move_('a') def rotate_right(self): print "right" self.move_('d') def move_(self,direction): s = serial.Serial(self.port) time.sleep(2) s.write(direction) s.close() root = Tk() app = RobotUI(root,2) root.mainloop()
Again the code for the controller can be found here https://gist.github.com/1378327
Now the robot is complete. And can be used. The last post, is on newsoftserial library for arduino. Not directly related to the robot. I experiment on it as I build it.