Go Down

Topic: Interfacing with python - problem for writing and reading on serial port (Read 2457 times) previous topic - next topic

nax_

Hi everyone,
I'm facing some issues when interfacing my Arduino UNO with python.
I notice that serial communication only works when Arduino IDE Serial Monitor is open, when I close it my python script freeze.

My goal is to transmit serial command throught arduino by using python.
I've got the following code for my Arduino :

Code: [Select]
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);

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

void loop() // run over and over
{

 if (mySerial.available())
   Serial.write(mySerial.read());

 if (Serial.available()){
     char car = Serial.read();
     mySerial.write(car);
 }
}


And the python code
Code: [Select]

import serial
arduino = serial.Serial('/dev/ttyACM0', 9600)

cmd = "\xAA\x00\x03\x25\x26\x00\x00\xBB"
arduino.write(cmd)
raw = arduino.read(3)
length = ord(raw[2])
raw += arduino.read(length + 2)
for i in raw:
print ord(i)


This example is for reading RFID tag (I've connected an RFID chip to arduino's ports 2 and 3)

When Serial Monitor is opened it works like a charm, but when it's closed Python freezes after arduino.write(cmd), (the read function freezes)

It's very strange and I can't figure out what's wrong.
Thank for your help.

PS : I should mention that a code like :

Code: [Select]
import serial
arduino = serial.Serial('/dev/ttyACM0', 9600)

while 1:
print arduino.read()


And
Code: [Select]

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);

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

void loop() // run over and over
{
     Serial.write(0x65);
}


Works

PS2 : I found some related topic here : http://stackoverflow.com/questions/11385915/serial-interface-initialisation-with-arduino-and-c
and it has something to do with the DTR signal (?)
So the command serial.setDTR(false) before works.

Code: [Select]
import serial, time

#open the serial port
s = serial.Serial(port='/dev/tty.usbserial-A5006HGR', baudrate=9600)
#disable DTR
s.setDTR(level=False)
#wait for 2 seconds
time.sleep(2)



I don't understand this unusual situation.

elric91

Not 100% sure, but the magic may come from the
Code: [Select]
time.sleep(2) command

See : http://www.arduino.cc/playground/interfacing/python

Go Up