Let's Make Robots!

Code Post - Interfacing Arduino and Python

This is something I've done by hand at least ten times and always seem to lose it so I've decided to post it here. It is an easy way to debug and test stuff will developing software for the Arduino (or any Microcontroller really). There is a python code that sends string messages to the arduino over serial based on which arrow key on your keyboard is pressed. There is also an Arduino code that listens for these messages, then repeats the message back to the PC to make sure it went through. Once the python file recieves the message back from the arduino it prints it out to the screen. 

I was using it for a robot that has a drive motor and a steering motor, so you can hit up to send a "forward" signal, and hit right to send a "turn right" signal. What is nice about it, is that it also records when a key is released, so for example when the right arrow is released a "center" signal is sent so you could return the steering back to center. The arduino code I'm posting doesn't really do anything but show you how to receive and respond to the messages. The arduino just connects to your computer via usb. You might have to change which COM port is used in the code. 

You have to have pygame (http://www.pygame.org/news.html) installed on your computer to use it. That is how I read when the arrow keys are pressed. Change the extention of the python_code to .py and change the extention of the arduino_code to .ino

20 August Edit _____________________________________________________________________

 I'm replacing the arduino code with a similar code that actually controls my robot. I'm using a L293D to control two small dc motors (I'm making some wall racers, more about that later). Here is a good post about the motor driver http://letsmakerobots.com/node/2074, although, I used the "basic implementation" and it seems to work just fine. 

AttachmentSize
python_code.txt4.23 KB
arduino_code1.txt2.25 KB

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
From someone who spends almost as much time digging in my Dropbox for code as I do rewriting code: thank you :)