Other Projects

Arduino and Python

Talking to Arduino over a serial interface is pretty trivial in Python. On Unix-like systems you can read and write to the serial device as if it were a file, but there is also a wrapper library called pySerial that works well across all operating systems.

After installing pySerial, reading data from Arduino is straightforward:

>>> import serial
>>> ser = serial.Serial('/dev/tty.usbserial', 9600)
>>> while True:
...     print ser.readline()
'1 Hello world!\r\n'
'2 Hello world!\r\n'
'3 Hello world!\r\n'

Writing data to Arduino is easy too (the following applies to Python 2.x):

>>> import serial # if you have not already done so
>>> ser = serial.Serial('/dev/tty.usbserial', 9600)
>>> ser.write('5')

In Python 3.x the strings are Unicode by default. When sending data to Arduino, they have to be converted to bytes. This can be done by prefixing the string with b:

Image- arduino_plot_screenshot
>>> ser.write(b'5') # prefix b is required for Python 3.x, optional for Python 2.x

Note that you will need to connect to the same device that you connect to from within the Arduino development environment. I created a symlink between the longer-winded device name and /dev/tty.usbserial to cut down on keystrokes.

It is worth noting that the example above will not work on a Windows machine; the Arduino serial device takes some time to load, and when a serial connection is established it resets the Arduino.

Any write() commands issued before the device initialised will be lost. A robust server side script will read from the serial port until the Arduino declares itself ready, and then issue write commands. Alternatively It is possible to work around this issue by simply placing a ‘time.sleep(2)’ call between the serial connection and the write call.

Python Bridge

Bridge is a python application that communicate with Arduino using pySerial. It replace the Serial Monitor from the Arduino IDE and make use of it’s command line interface to upload and verify code, all in a single window. It’s purpose is to provide a more flexible and lighter way to interact with arduino compatible boards using an external editor. The script has a command line interface that ease the commucation with other applications. Each ino file opened with Bridge has it’s own profile that save the last used board type (ie: uno, nano), serial port and baudrate. An example (.vimrc) is provided for the integration with Vim, using F1 to upload and F2 to open Bridge GUI with the current file.

When also using the provided arduino script, it may serve as a standalone application that can send data to serial input, and monitor serial output through external parser software, allowing easy development of arduino/python interactive scripts.

For More Detail: Arduino and Python

Tags

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button
Close
Close