Michael Crosby


Python talking to Arduino

I just setup my Arduino with an LCD display. You can follow the tutorial here to get the LCD and board wired up. We will also be using the sample code from that tutorial.

The Problem

The issue that I ran into was displaying messages from the Arduino IDE's SerialMonitor worked fine but when I was trying to display a message that I sent via python, it was not showing on the screen. After some help I finally have it working so this is how you fix it.

Python Code

You will need to install pyserial so that you can talk to your board via USB. It's simple if you have build tools installed so just:

sudo easy_install pyserial

Now if we look at the code that does not work first you can see what you need to change. We need to import serial and then setup the connection to the board.

import serial 
port = serial.Serial('pathtoyourboard', 9600)

You will need to look in your Arduino IDE for the path to your board and the 9600 is the rate that is definded in the Arduino code that we are loading onto it. Now we need to write some data do the Arduino and close the connection.

port.write('sometext')
port.close()

If we load the code from the tutorial that I linked at the beginning of this post onto your board and then ran this python code, we would just see a blank LCD. The probelm is that whenever the serial connection is first made, it takes the Arduino two seconds to get that port open and setup. So for our python code to work we need to import the time module and add a sleep for atleast 2 seconds right after our port = serial.Serial statement. Here is the what the final python code will look like with it working and the message changed.

import serial
import time

port = serial.Serial('/dev/tty.usbmodemfd141', 9600)
time.sleep(2)

message = ['My', 'name', 'is', 'michael']

for word in message:
    port.write(word)
    time.sleep(1)

port.close()

So this code makes the connection and waits 2 seconds for the Arduino to get setup, then starts writing data to it. Everything works find and it's good to go. So in the future when you are working with Python and Arduino via USB, wait 2 seconds before sending data to it or it will not get it.

comments powered by Disqus