Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python + Arduino with Mac OS X

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?

like image 606
danem Avatar asked May 18 '11 02:05

danem


2 Answers

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').

like image 68
JBernardo Avatar answered Oct 26 '22 01:10

JBernardo


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.

like image 38
gaellm Avatar answered Oct 26 '22 01:10

gaellm