Arduino Python Serial

Hello All,

I have been working on getting Arduino to communicate to Python through the serial port (USB).
I have achieved one way communications but now I’ve moved on to bidirectional. I found a blog that has some code and copied it but it doesn’t seem to work fully. The return from Arduino is ‘1L’ instead of ‘"LED Activated’. I tried to figure out the issue but I am stomped, can anyone give a hand?

Arduino Code:

int ledPin = 13; // choose the pin for the LED
char msg = ' '; // variable to hold data from serial

void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
Serial.begin(9600);
Serial.print("Program Initiated\n");
}

void loop(){
// While data is sent over serial assign it to the msg
while (Serial.available()>0){
msg=Serial.read();
}

// Turn LED on/off if we recieve 'Y'/'N' over serial
if (msg=='Y') {
digitalWrite(ledPin, HIGH); // turn LED ON
Serial.print("LED Activated\n");
msg=' ';
} else if (msg=='N') {
digitalWrite(ledPin, LOW); // turn LED OFF
}
}

Python Code:

import serial
import time

locations='com5'

for device in locations:
try:
print "Trying...",device
arduino = serial.Serial(locations, 9600)
break
except:
print "Failed to connect on",device

try:
arduino.write('Y')
time.sleep(1)
print arduino.readline()
except:
print "Failed to send!"

Python Shell result:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

================================ RESTART ================================

Trying... c
Program Initiated

arduino.write('Y')
1L

I get the LED to come on but as you can see instead of getting the proper return I get 1L. Why?

Have you tried terminating your output string with \r\n ? Python might not be recognizing \n alone as the terminator.

Jim

Have you tried terminating your output string with \r\n ? Python might not be recognizing \n alone as the terminator.

I don’t see ANY terminator being sent.

Serial data transmission is relatively slow. The python sends data that takes time to get to the Arduino. The Arduino takes some time to process that data, and sends a response, which takes time to get back to the PC.

If the sleep() function’s argument is in seconds, 1 second should be long enough. But, it, as on the Arduino, the time is in milliseconds, 1 millisecond is not long enough to get data out, processed, and get the whole response back.