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开发者_JAVA技巧, 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?
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'
).
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.
I have done this using Perl under Linux, but have no experience with Python or Mac. I can give you a few pointers to look for.
First, in your Python program you need to put the proper device address for your USB port in serialPath
as otherwise your data will not reach the Arduino. In Linux I did a lsusb after I connected the board and found the device name from that.
In your Arduino code change it to be
void loop()
{
if(Serial.available() > 0)
{
d = Serial.read();
Serial.println(d,BYTE);
}
}
as otherwise you will be dumping a bunch of -1s if there is no data.
精彩评论