Python + Arduino with Mac OS X


Question

I'm having trouble communicating between my Arduino and Python. I have a couple of questions that I hope can be answered, but first and most importantly, I need to simply establish a connection.

For Windows, apparently the solution is rather convenient, but on Mac OS X, I apparently need to access some system files (which I am not familiar with). The Python documentation points me to the specific post Re: Can Python do serial port stuff?, but I don't think it quite serves my purposes.

At this point, trying to merely see evidence of communication I've tried this.

Arduino:

void setup(){
    Serial.begin(9600);
}

void loop()
{
    int d = Serial.read();
    Serial.println(d,BYTE);
}

Python: (pretty much from the mentioned link...)

 #!usr/bin/python
 import os, fcntl, termios, sys

 serialPath = '/dev/tty.usbmodemfa141'

 ser= os.open(serialPath, 0)
 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] = range(7)
 settings = termios.tcgetattr(ser)
 settings[ospeed] = termios.B9600
 settings[ispeed] = termios.B0
 print 2

As evidenced here, I really don't understand what the modules I am importing are doing exactly. While reading the documentation I see no obvious way to send data over serial. So am I right in guessing that whatever the output of this program is it will be sent over automatically?

1
6
10/10/2013 7:53:54 PM

Accepted Answer

The easiest way to communicate in Python with the Arduino (or any microcontroller with serial) is using pySerial.

Here's an example:

import serial
s = serial.Serial(port='/dev/tty.usbmodemfa141', baudrate=9600)

s.write('text')
s.read()
s.readline()

PS: If you're using Python 3, you should send bytes instead of strings (that is, b'text').

14
5/22/2011 2:55:17 PM

On my side I've solved Serial error on OSX using the sudo command; I think that on OSX you have to get admin rights to communicate throw /dev/cu.usbmodem14101 with Serial after a pip install.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon