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?