[Tutor] Raw Bits! (Control characters ahoy!)

Hugo González Monteverde hugonz-lists at h-lab.net
Tue Apr 18 07:02:59 CEST 2006


doug shawhan wrote:
> I am in the middle of a project that requires me to send and retrieve 
> information from a machine connected to a serial port. My problems are 
> these:
> 
> 1. I cannot send control characters
> 2. I cannot read data streaming from the serial port
> 
> 
> I have been doing fine with:
> 
> os.system("echo '5' >/dev/tty00")
> os.system("echo '8' >/dev/tty00")
> 

Hi Doug,

Echo just opens the file and writes to it, closing it afterwards. if you 
have used setserial correctly on the portt, then the equivalent Python 
commands should work.

Note that the echo command adds a carriage return at the end.

> Reading from the serial port has also been problematic. I find that 
> simply opening the port /dev/tty00 file and using readlines(), read() or 
> whatever gives me empty strings or lists. Pbth.

If you use blocking, then reading should not give you anything empty, 
but data, no matter how long it has to wait.

> 
> So first: how should I go about adding the hex escape sequences (\x0a 
> and \x50) to the above strings in their raw form?

fileo = open('/dev/ttyS0', 'w')
fileo.write('5' + '\x0a\x50')
#\x0a is a linefeed (do you want to do that?)
fileo.close()

You may use fileo.flush() instead of close, for avoiding buffering and 
not having to close the file.

> second: what method should I use to read a raw stream from the serial 
> port for a given period?
> 


fileo = open('/dev/ttyS0') 	#read only
data =  fileo.read(1) 		#just one char
fileo.close()


#This waits forever. For a given period, use the select module (UN*X only)

import select
select([fileo.fileno()],[],[], 1.0)

#This will wait for 1 second for output from the file. Then the return 
value will tell you if the filehandles have data. ([], [], [])  means no 
data to read.


> I have looked carefully at the neat and tidy miniterm.py example in the 
> pyserial examples directory, and see how one can continuously read via a 
> thread from the port, but have not been able to replicate it thus far.
> 

I never use threads for that, I always use select(). Then  again, I'm a 
unixhead.


Hugo


More information about the Tutor mailing list