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.

No comments: