caramellcube
Posts: 5
Joined: Sat Feb 22, 2014 8:51 am

SOLVED script hanging on serial readline()

Tue Jun 10, 2014 6:38 pm

Hi, I could use some help with an odd problem I've been getting using the serial command readline(). I'm trying to get a raspberry pi to communicate through USB with an arduino I've programmed to respond to various commands. First of all, typing into a python prompt, I get this:

Code: Select all

>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0', 9600)
>>> ser.write('1')
1
>>>ser.readline
s,Mag,166,643,-452,152.72,...(big string of data as expected)
when I do it that way, it works fine, but I need to get a script to do it at the push of a button, so I wrote this:

Code: Select all

import serial

print "step 1"
ser = serial.Serial('/dev/ttyUSB0', 9600)
print "step 2"
ser.write('1')
print "step 3"
ser.readline()
print "step 4"
Every time I've run this, it gets to step 3 then hangs. There's no error message, and I have to alt-f4 and kill the program to get anything working again. I thought at first it might be a timing issue, so I tried it with a 1 second delay, but the same problem happened. I don't understand what's causing it, any advice would be much appreciated.
Last edited by caramellcube on Wed Jun 11, 2014 6:12 am, edited 1 time in total.

PiGraham
Posts: 5029
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: script hanging on serial readline()

Tue Jun 10, 2014 6:45 pm

Does the data include newline characters?
If not perhaps the interactive execution implements a timeout that the scripted execution does not.

What happens if you use ser.read(1) to repeatedly read single characters?

caramellcube
Posts: 5
Joined: Sat Feb 22, 2014 8:51 am

Re: script hanging on serial readline()

Tue Jun 10, 2014 8:10 pm

Thanks for the quick reply, I should have mentioned the string always ends with \r\n, generated by Serial.println(""); on the arduino. I just tried replacing readline() with read(1) and got the same problem. adding a 3 second pause with sleep(3) just before the read(1) gives the same.

EDIT - found it...
It turns out it was a timing issue, but in a different place. Establishing a serial connection to an arduino causes it to reset, so it was never online at the moment the pi was sending data, and so never replied. The following code works fine:

Code: Select all

import serial
from time import sleep

ser = serial.Serial('/dev/ttyUSB0', 9600)
sleep(3)
ser.write('1')
sleep(3)
print str(ser.readline())

Return to “Python”