Tuesday, May 10, 2011

Arduino Python Blink - II

My previous post is about one way communications to Arduino using Python. Now I want to make it two way.

Here is the code I loaded my Duemilanove with.

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

void loop() {
char i=Serial.read();
if(i=='Y'){
digitalWrite(13, HIGH);
Serial.println("At Your Command, The Lights Are On");
} else if (i=='N') {
digitalWrite(13, LOW);
Serial.println("At your Command, The Lights Are Off");
}
}

Just as in my previous post, I accessed Python through the Terminal. I entered the following sequence of commands.

>>> import serial
>>> se=serial.Serial('/dev/tty.usbserial-A9007RxF',9600)

Now we are set to talk to the serial port.

>>> se.write('Y')

The LED lights up.

>>> se.read()
'A'

That is what Python's response to that command is. Arduino's buffer contains, "At Your Command, The Lights Are On". However, se.read() picked only the first character. So now I say to Python,

>>> se.readline()
't Your Command, The Lights Are On\r\n'

The response to se.readline() emptied the buffer completely with the exception of 'A'. 'A' was emptied by the previous command se.read(). There are more exceptions to this. Now I entered the following commands and obtained the following responses as well.

>>> se.write('N')
1
>>> se.write('Y')
1
>>> se.write('N')
1
>>> se.readline()
'At your Command, The Lights Are Off\r\n'
>>> se.readline()
'At your Command, The Lights Are Off\r\n'
>>> se.readline()
'At Your Command, The Lights Are On\r\n'
>>> se.readline()
'At your Command, The Lights Are Off\r\n'
>>>

Every command generates a serial response and that is stored separately from the responses from other commands. Each readline request will fetch then seperately as can be seem above.

So now Arduino and Python can talk to each other.

Monday, May 9, 2011

Arduino Python Blink

Have been working on Arduino for sometime with reference to automating some aspects of my work.
Have been tinkering with Python just for the sake of it.
So now I want to talk to my Arduino using Python.
For the starters this is what I did.

Loaded this code on my Duemilanove.

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

void loop(){
char i=Serial.read();
if (i=='Y'){
digitalWrite(13, HIGH);
} else if(i=='N'){
digitalWrite(13, LOW);
}
}

Dowloaded and installed pyserial.
On a mac, the pyserial tar file downloads to Download folder and unzips to the same folder.
From the terminal: cd /Downloads/pyserial-2.5
From the the terminal: sudo python setup.py install
Lo and behold pyserial is installed.
On terminal: python
That takes us to >>> python prompt.

At the python prompt, either the following can be entered and a py file can be created and run straight from the terminal user prompt.

import serial
arduino=serial.Serial('/dev/tty.usbserial-A9007RxF', 9600)
arduino.write('Y') //This should power the 13
arduino.write('N') //This should power down 13


So simple.
And now to bigger projects... PyRobots?