Question re threading and serial i/o

Frank Millman frank at chagford.com
Fri Nov 7 13:43:26 CET 2003


> Frank Millman wrote:
> > 
> > This is my Mk 3 version, using select() -
> >     def scan():
> >         p = file('/dev/ttyS0')
> >         while x:
> >             ans = select.select([p],[],[],0.1)
> >             if ans[0]:
> >                 print ord(p.read(1))
> >         p.close()
> > 
> > The scanner sends a string consisting of 'code' <tab> 'qty' <cr>. If I
> > scan a code of '1' and a quantity of '1', I would expect the program
> > to display 49 9 49 13. The Mk 2 version does this correctly.
> > 
> > The Mk 3 version behaves differently. After the first scan, it
> > displays 49. After each subsequent scan, it displays 9 49 13 49.
> > 
> > If anyone can explain what I am doing wrong, I will be most grateful.
> > In the meantime I am sticking with Mk 2, as it is doing the job.
> 
Peter Hansen wrote:

> Not entirely sure...  but what is "x" in the while statement?
> 

"x" is a global variable with a value of 1. It stays 1 until the main
thread wants to terminate the program, in which case it sets it to 0
and the secondary thread stops. This works ok.

> Another possibility is that you have not opened the file in non-blocking
> mode.  I don't know what the effect of that would be on the select()
> statement, but if you did use non-blocking, you could change the read()
> call to get a whole bunch of data at a time, instead of only one byte.
> If you did p.read(1024), for example, on a non-blocking file, you should
> get back anywhere from 1 to 1024 bytes after select indicates it is
> readable.  If nothing else, this will speed up your final result, in
> either case.  (You can't do that on a block read, of course, since 
> it would then block until all 1024 bytes were available, which might
> never happen.)
> 
> -Peter

This was indeed the problem.

I changed
    p = file('/dev/ttyS0')
    p.read(1)
to
    p = os.open('/dev/ttyS0',os.O_RDONLY|os.O_NONBLOCK)
    os.read(p,1)
and it behaved correctly.

Out of interest, is there another way to open a serial port in
non-blocking mode?

Reading chunks of up to 1024 works as you predicted, and should be
faster - I will follow this up.

Thanks a lot, Peter, I really appreciate your valuable input.

Frank




More information about the Python-list mailing list