Pages: [1]   Go Down
Author Topic: Interfacing with python - problem for writing and reading on serial port  (Read 2329 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
#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:
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:
import serial
arduino = serial.Serial('/dev/ttyACM0', 9600)

while 1:
print arduino.read()

And
Code:
#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:
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.
« Last Edit: October 16, 2012, 11:20:00 am by nax_ » Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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

Pages: [1]   Go Up
Jump to: